[ARM] MVE compare vector splat combine
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blob276791165f504c8d7f87c7a5dec8dadbb4a2b5ac
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::QPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SHL, VT, Custom);
254 setOperationAction(ISD::SRA, VT, Custom);
255 setOperationAction(ISD::SRL, VT, Custom);
256 setOperationAction(ISD::SMIN, VT, Legal);
257 setOperationAction(ISD::SMAX, VT, Legal);
258 setOperationAction(ISD::UMIN, VT, Legal);
259 setOperationAction(ISD::UMAX, VT, Legal);
260 setOperationAction(ISD::ABS, VT, Legal);
261 setOperationAction(ISD::SETCC, VT, Custom);
263 // No native support for these.
264 setOperationAction(ISD::UDIV, VT, Expand);
265 setOperationAction(ISD::SDIV, VT, Expand);
266 setOperationAction(ISD::UREM, VT, Expand);
267 setOperationAction(ISD::SREM, VT, Expand);
269 if (!HasMVEFP) {
270 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
271 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
272 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
273 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
277 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
278 for (auto VT : FloatTypes) {
279 addRegisterClass(VT, &ARM::QPRRegClass);
280 if (!HasMVEFP)
281 setAllExpand(VT);
283 // These are legal or custom whether we have MVE.fp or not
284 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
285 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
286 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
287 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
288 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
289 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
290 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
291 setOperationAction(ISD::SETCC, VT, Custom);
293 if (HasMVEFP) {
294 setOperationAction(ISD::FMINNUM, VT, Legal);
295 setOperationAction(ISD::FMAXNUM, VT, Legal);
296 setOperationAction(ISD::FROUND, VT, Legal);
298 // No native support for these.
299 setOperationAction(ISD::FDIV, VT, Expand);
300 setOperationAction(ISD::FREM, VT, Expand);
301 setOperationAction(ISD::FSQRT, VT, Expand);
302 setOperationAction(ISD::FSIN, VT, Expand);
303 setOperationAction(ISD::FCOS, VT, Expand);
304 setOperationAction(ISD::FPOW, VT, Expand);
305 setOperationAction(ISD::FLOG, VT, Expand);
306 setOperationAction(ISD::FLOG2, VT, Expand);
307 setOperationAction(ISD::FLOG10, VT, Expand);
308 setOperationAction(ISD::FEXP, VT, Expand);
309 setOperationAction(ISD::FEXP2, VT, Expand);
310 setOperationAction(ISD::FNEARBYINT, VT, Expand);
314 // We 'support' these types up to bitcast/load/store level, regardless of
315 // MVE integer-only / float support. Only doing FP data processing on the FP
316 // vector types is inhibited at integer-only level.
317 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
318 for (auto VT : LongTypes) {
319 addRegisterClass(VT, &ARM::QPRRegClass);
320 setAllExpand(VT);
321 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
323 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
325 // We can do bitwise operations on v2i64 vectors
326 setOperationAction(ISD::AND, MVT::v2i64, Legal);
327 setOperationAction(ISD::OR, MVT::v2i64, Legal);
328 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
330 // It is legal to extload from v4i8 to v4i16 or v4i32.
331 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
332 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
333 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
335 // Some truncating stores are legal too.
336 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
337 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
338 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
340 // Predicate types
341 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
342 for (auto VT : pTypes) {
343 addRegisterClass(VT, &ARM::VCCRRegClass);
344 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
345 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
346 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
347 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
348 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
350 setOperationAction(ISD::SETCC, VT, Custom);
351 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
355 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
356 const ARMSubtarget &STI)
357 : TargetLowering(TM), Subtarget(&STI) {
358 RegInfo = Subtarget->getRegisterInfo();
359 Itins = Subtarget->getInstrItineraryData();
361 setBooleanContents(ZeroOrOneBooleanContent);
362 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
364 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
365 !Subtarget->isTargetWatchOS()) {
366 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
367 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
368 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
369 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
370 : CallingConv::ARM_AAPCS);
373 if (Subtarget->isTargetMachO()) {
374 // Uses VFP for Thumb libfuncs if available.
375 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
376 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
377 static const struct {
378 const RTLIB::Libcall Op;
379 const char * const Name;
380 const ISD::CondCode Cond;
381 } LibraryCalls[] = {
382 // Single-precision floating-point arithmetic.
383 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
384 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
385 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
386 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
388 // Double-precision floating-point arithmetic.
389 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
390 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
391 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
392 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
394 // Single-precision comparisons.
395 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
396 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
397 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
398 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
399 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
400 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
401 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
402 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
404 // Double-precision comparisons.
405 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
406 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
407 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
408 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
409 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
410 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
411 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
412 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
414 // Floating-point to integer conversions.
415 // i64 conversions are done via library routines even when generating VFP
416 // instructions, so use the same ones.
417 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
418 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
419 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
420 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
422 // Conversions between floating types.
423 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
424 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
426 // Integer to floating-point conversions.
427 // i64 conversions are done via library routines even when generating VFP
428 // instructions, so use the same ones.
429 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
430 // e.g., __floatunsidf vs. __floatunssidfvfp.
431 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
432 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
433 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
434 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
437 for (const auto &LC : LibraryCalls) {
438 setLibcallName(LC.Op, LC.Name);
439 if (LC.Cond != ISD::SETCC_INVALID)
440 setCmpLibcallCC(LC.Op, LC.Cond);
445 // These libcalls are not available in 32-bit.
446 setLibcallName(RTLIB::SHL_I128, nullptr);
447 setLibcallName(RTLIB::SRL_I128, nullptr);
448 setLibcallName(RTLIB::SRA_I128, nullptr);
450 // RTLIB
451 if (Subtarget->isAAPCS_ABI() &&
452 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
453 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
454 static const struct {
455 const RTLIB::Libcall Op;
456 const char * const Name;
457 const CallingConv::ID CC;
458 const ISD::CondCode Cond;
459 } LibraryCalls[] = {
460 // Double-precision floating-point arithmetic helper functions
461 // RTABI chapter 4.1.2, Table 2
462 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
463 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
464 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
465 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
467 // Double-precision floating-point comparison helper functions
468 // RTABI chapter 4.1.2, Table 3
469 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
470 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
471 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
472 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
473 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
474 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
475 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
476 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
478 // Single-precision floating-point arithmetic helper functions
479 // RTABI chapter 4.1.2, Table 4
480 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
481 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
482 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
483 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
485 // Single-precision floating-point comparison helper functions
486 // RTABI chapter 4.1.2, Table 5
487 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
488 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
489 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
490 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
491 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
492 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
493 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
494 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
496 // Floating-point to integer conversions.
497 // RTABI chapter 4.1.2, Table 6
498 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
499 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
500 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
501 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
502 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
503 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
504 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
505 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
507 // Conversions between floating types.
508 // RTABI chapter 4.1.2, Table 7
509 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
513 // Integer to floating-point conversions.
514 // RTABI chapter 4.1.2, Table 8
515 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
516 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
517 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
518 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
519 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
520 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
521 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
522 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
524 // Long long helper functions
525 // RTABI chapter 4.2, Table 9
526 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
527 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 // Integer division functions
532 // RTABI chapter 4.3.1
533 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
534 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
535 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
536 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
537 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
538 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
539 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
540 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
543 for (const auto &LC : LibraryCalls) {
544 setLibcallName(LC.Op, LC.Name);
545 setLibcallCallingConv(LC.Op, LC.CC);
546 if (LC.Cond != ISD::SETCC_INVALID)
547 setCmpLibcallCC(LC.Op, LC.Cond);
550 // EABI dependent RTLIB
551 if (TM.Options.EABIVersion == EABI::EABI4 ||
552 TM.Options.EABIVersion == EABI::EABI5) {
553 static const struct {
554 const RTLIB::Libcall Op;
555 const char *const Name;
556 const CallingConv::ID CC;
557 const ISD::CondCode Cond;
558 } MemOpsLibraryCalls[] = {
559 // Memory operations
560 // RTABI chapter 4.3.4
561 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
562 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 for (const auto &LC : MemOpsLibraryCalls) {
567 setLibcallName(LC.Op, LC.Name);
568 setLibcallCallingConv(LC.Op, LC.CC);
569 if (LC.Cond != ISD::SETCC_INVALID)
570 setCmpLibcallCC(LC.Op, LC.Cond);
575 if (Subtarget->isTargetWindows()) {
576 static const struct {
577 const RTLIB::Libcall Op;
578 const char * const Name;
579 const CallingConv::ID CC;
580 } LibraryCalls[] = {
581 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
582 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
583 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
584 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
585 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
586 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
587 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
588 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
591 for (const auto &LC : LibraryCalls) {
592 setLibcallName(LC.Op, LC.Name);
593 setLibcallCallingConv(LC.Op, LC.CC);
597 // Use divmod compiler-rt calls for iOS 5.0 and later.
598 if (Subtarget->isTargetMachO() &&
599 !(Subtarget->isTargetIOS() &&
600 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
601 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
602 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
605 // The half <-> float conversion functions are always soft-float on
606 // non-watchos platforms, but are needed for some targets which use a
607 // hard-float calling convention by default.
608 if (!Subtarget->isTargetWatchABI()) {
609 if (Subtarget->isAAPCS_ABI()) {
610 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
611 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
612 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
613 } else {
614 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
615 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
616 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
620 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
621 // a __gnu_ prefix (which is the default).
622 if (Subtarget->isTargetAEABI()) {
623 static const struct {
624 const RTLIB::Libcall Op;
625 const char * const Name;
626 const CallingConv::ID CC;
627 } LibraryCalls[] = {
628 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
629 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
630 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
633 for (const auto &LC : LibraryCalls) {
634 setLibcallName(LC.Op, LC.Name);
635 setLibcallCallingConv(LC.Op, LC.CC);
639 if (Subtarget->isThumb1Only())
640 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
641 else
642 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
644 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
645 Subtarget->hasFPRegs()) {
646 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
647 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
648 if (!Subtarget->hasVFP2Base())
649 setAllExpand(MVT::f32);
650 if (!Subtarget->hasFP64())
651 setAllExpand(MVT::f64);
654 if (Subtarget->hasFullFP16()) {
655 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
656 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
657 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
658 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
660 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
661 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
664 for (MVT VT : MVT::vector_valuetypes()) {
665 for (MVT InnerVT : MVT::vector_valuetypes()) {
666 setTruncStoreAction(VT, InnerVT, Expand);
667 addAllExtLoads(VT, InnerVT, Expand);
670 setOperationAction(ISD::MULHS, VT, Expand);
671 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
672 setOperationAction(ISD::MULHU, VT, Expand);
673 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
675 setOperationAction(ISD::BSWAP, VT, Expand);
678 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
679 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
681 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
682 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
684 if (Subtarget->hasMVEIntegerOps())
685 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
687 // Combine low-overhead loop intrinsics so that we can lower i1 types.
688 if (Subtarget->hasLOB()) {
689 setTargetDAGCombine(ISD::BRCOND);
690 setTargetDAGCombine(ISD::BR_CC);
693 if (Subtarget->hasNEON()) {
694 addDRTypeForNEON(MVT::v2f32);
695 addDRTypeForNEON(MVT::v8i8);
696 addDRTypeForNEON(MVT::v4i16);
697 addDRTypeForNEON(MVT::v2i32);
698 addDRTypeForNEON(MVT::v1i64);
700 addQRTypeForNEON(MVT::v4f32);
701 addQRTypeForNEON(MVT::v2f64);
702 addQRTypeForNEON(MVT::v16i8);
703 addQRTypeForNEON(MVT::v8i16);
704 addQRTypeForNEON(MVT::v4i32);
705 addQRTypeForNEON(MVT::v2i64);
707 if (Subtarget->hasFullFP16()) {
708 addQRTypeForNEON(MVT::v8f16);
709 addDRTypeForNEON(MVT::v4f16);
713 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
714 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
715 // none of Neon, MVE or VFP supports any arithmetic operations on it.
716 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
717 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
718 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
719 // FIXME: Code duplication: FDIV and FREM are expanded always, see
720 // ARMTargetLowering::addTypeForNEON method for details.
721 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
722 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
723 // FIXME: Create unittest.
724 // In another words, find a way when "copysign" appears in DAG with vector
725 // operands.
726 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
727 // FIXME: Code duplication: SETCC has custom operation action, see
728 // ARMTargetLowering::addTypeForNEON method for details.
729 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
730 // FIXME: Create unittest for FNEG and for FABS.
731 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
732 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
733 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
734 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
735 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
736 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
737 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
738 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
739 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
740 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
741 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
742 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
743 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
744 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
745 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
746 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
747 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
748 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
751 if (Subtarget->hasNEON()) {
752 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
753 // supported for v4f32.
754 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
755 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
756 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
757 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
758 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
759 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
760 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
761 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
762 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
763 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
764 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
765 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
766 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
767 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
769 // Mark v2f32 intrinsics.
770 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
771 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
772 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
773 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
774 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
775 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
776 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
777 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
778 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
779 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
780 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
781 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
782 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
783 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
785 // Neon does not support some operations on v1i64 and v2i64 types.
786 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
787 // Custom handling for some quad-vector types to detect VMULL.
788 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
789 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
790 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
791 // Custom handling for some vector types to avoid expensive expansions
792 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
793 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
794 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
795 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
796 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
797 // a destination type that is wider than the source, and nor does
798 // it have a FP_TO_[SU]INT instruction with a narrower destination than
799 // source.
800 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
801 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
802 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
803 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
804 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
805 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
806 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
807 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
809 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
810 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
812 // NEON does not have single instruction CTPOP for vectors with element
813 // types wider than 8-bits. However, custom lowering can leverage the
814 // v8i8/v16i8 vcnt instruction.
815 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
816 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
817 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
818 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
819 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
820 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
822 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
823 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
825 // NEON does not have single instruction CTTZ for vectors.
826 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
827 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
828 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
829 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
831 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
832 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
833 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
834 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
836 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
838 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
839 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
841 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
842 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
843 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
844 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
846 // NEON only has FMA instructions as of VFP4.
847 if (!Subtarget->hasVFP4Base()) {
848 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
849 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
852 setTargetDAGCombine(ISD::INTRINSIC_VOID);
853 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
854 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
855 setTargetDAGCombine(ISD::SHL);
856 setTargetDAGCombine(ISD::SRL);
857 setTargetDAGCombine(ISD::SRA);
858 setTargetDAGCombine(ISD::SIGN_EXTEND);
859 setTargetDAGCombine(ISD::ZERO_EXTEND);
860 setTargetDAGCombine(ISD::ANY_EXTEND);
861 setTargetDAGCombine(ISD::STORE);
862 setTargetDAGCombine(ISD::FP_TO_SINT);
863 setTargetDAGCombine(ISD::FP_TO_UINT);
864 setTargetDAGCombine(ISD::FDIV);
865 setTargetDAGCombine(ISD::LOAD);
867 // It is legal to extload from v4i8 to v4i16 or v4i32.
868 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
869 MVT::v2i32}) {
870 for (MVT VT : MVT::integer_vector_valuetypes()) {
871 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
872 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
873 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
878 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
879 setTargetDAGCombine(ISD::BUILD_VECTOR);
880 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
881 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
884 if (!Subtarget->hasFP64()) {
885 // When targeting a floating-point unit with only single-precision
886 // operations, f64 is legal for the few double-precision instructions which
887 // are present However, no double-precision operations other than moves,
888 // loads and stores are provided by the hardware.
889 setOperationAction(ISD::FADD, MVT::f64, Expand);
890 setOperationAction(ISD::FSUB, MVT::f64, Expand);
891 setOperationAction(ISD::FMUL, MVT::f64, Expand);
892 setOperationAction(ISD::FMA, MVT::f64, Expand);
893 setOperationAction(ISD::FDIV, MVT::f64, Expand);
894 setOperationAction(ISD::FREM, MVT::f64, Expand);
895 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
896 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
897 setOperationAction(ISD::FNEG, MVT::f64, Expand);
898 setOperationAction(ISD::FABS, MVT::f64, Expand);
899 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
900 setOperationAction(ISD::FSIN, MVT::f64, Expand);
901 setOperationAction(ISD::FCOS, MVT::f64, Expand);
902 setOperationAction(ISD::FPOW, MVT::f64, Expand);
903 setOperationAction(ISD::FLOG, MVT::f64, Expand);
904 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
905 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
906 setOperationAction(ISD::FEXP, MVT::f64, Expand);
907 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
908 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
909 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
910 setOperationAction(ISD::FRINT, MVT::f64, Expand);
911 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
912 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
913 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
914 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
915 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
916 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
917 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
918 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
919 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
922 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()){
923 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
924 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
927 if (!Subtarget->hasFP16())
928 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
930 if (!Subtarget->hasFP64())
931 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
933 computeRegisterProperties(Subtarget->getRegisterInfo());
935 // ARM does not have floating-point extending loads.
936 for (MVT VT : MVT::fp_valuetypes()) {
937 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
938 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
941 // ... or truncating stores
942 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
943 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
944 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
946 // ARM does not have i1 sign extending load.
947 for (MVT VT : MVT::integer_valuetypes())
948 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
950 // ARM supports all 4 flavors of integer indexed load / store.
951 if (!Subtarget->isThumb1Only()) {
952 for (unsigned im = (unsigned)ISD::PRE_INC;
953 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
954 setIndexedLoadAction(im, MVT::i1, Legal);
955 setIndexedLoadAction(im, MVT::i8, Legal);
956 setIndexedLoadAction(im, MVT::i16, Legal);
957 setIndexedLoadAction(im, MVT::i32, Legal);
958 setIndexedStoreAction(im, MVT::i1, Legal);
959 setIndexedStoreAction(im, MVT::i8, Legal);
960 setIndexedStoreAction(im, MVT::i16, Legal);
961 setIndexedStoreAction(im, MVT::i32, Legal);
963 } else {
964 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
965 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
966 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
969 setOperationAction(ISD::SADDO, MVT::i32, Custom);
970 setOperationAction(ISD::UADDO, MVT::i32, Custom);
971 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
972 setOperationAction(ISD::USUBO, MVT::i32, Custom);
974 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
975 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
977 // i64 operation support.
978 setOperationAction(ISD::MUL, MVT::i64, Expand);
979 setOperationAction(ISD::MULHU, MVT::i32, Expand);
980 if (Subtarget->isThumb1Only()) {
981 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
982 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
984 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
985 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
986 setOperationAction(ISD::MULHS, MVT::i32, Expand);
988 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
989 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
990 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
991 setOperationAction(ISD::SRL, MVT::i64, Custom);
992 setOperationAction(ISD::SRA, MVT::i64, Custom);
993 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
995 // MVE lowers 64 bit shifts to lsll and lsrl
996 // assuming that ISD::SRL and SRA of i64 are already marked custom
997 if (Subtarget->hasMVEIntegerOps())
998 setOperationAction(ISD::SHL, MVT::i64, Custom);
1000 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1001 if (Subtarget->isThumb1Only()) {
1002 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1003 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1004 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1007 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1008 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1010 // ARM does not have ROTL.
1011 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1012 for (MVT VT : MVT::vector_valuetypes()) {
1013 setOperationAction(ISD::ROTL, VT, Expand);
1014 setOperationAction(ISD::ROTR, VT, Expand);
1016 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1017 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1018 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1019 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1020 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1023 // @llvm.readcyclecounter requires the Performance Monitors extension.
1024 // Default to the 0 expansion on unsupported platforms.
1025 // FIXME: Technically there are older ARM CPUs that have
1026 // implementation-specific ways of obtaining this information.
1027 if (Subtarget->hasPerfMon())
1028 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1030 // Only ARMv6 has BSWAP.
1031 if (!Subtarget->hasV6Ops())
1032 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1034 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1035 : Subtarget->hasDivideInARMMode();
1036 if (!hasDivide) {
1037 // These are expanded into libcalls if the cpu doesn't have HW divider.
1038 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1039 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1042 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1043 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1044 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1046 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1047 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1050 setOperationAction(ISD::SREM, MVT::i32, Expand);
1051 setOperationAction(ISD::UREM, MVT::i32, Expand);
1053 // Register based DivRem for AEABI (RTABI 4.2)
1054 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1055 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1056 Subtarget->isTargetWindows()) {
1057 setOperationAction(ISD::SREM, MVT::i64, Custom);
1058 setOperationAction(ISD::UREM, MVT::i64, Custom);
1059 HasStandaloneRem = false;
1061 if (Subtarget->isTargetWindows()) {
1062 const struct {
1063 const RTLIB::Libcall Op;
1064 const char * const Name;
1065 const CallingConv::ID CC;
1066 } LibraryCalls[] = {
1067 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1068 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1069 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1070 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1072 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1073 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1074 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1075 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1078 for (const auto &LC : LibraryCalls) {
1079 setLibcallName(LC.Op, LC.Name);
1080 setLibcallCallingConv(LC.Op, LC.CC);
1082 } else {
1083 const struct {
1084 const RTLIB::Libcall Op;
1085 const char * const Name;
1086 const CallingConv::ID CC;
1087 } LibraryCalls[] = {
1088 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1089 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1090 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1091 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1093 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1094 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1095 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1096 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1099 for (const auto &LC : LibraryCalls) {
1100 setLibcallName(LC.Op, LC.Name);
1101 setLibcallCallingConv(LC.Op, LC.CC);
1105 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1106 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1107 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1108 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1109 } else {
1110 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1111 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1114 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1115 for (auto &VT : {MVT::f32, MVT::f64})
1116 setOperationAction(ISD::FPOWI, VT, Custom);
1118 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1119 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1120 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1121 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1123 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1124 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1126 // Use the default implementation.
1127 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1128 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1129 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1130 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1131 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1132 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1134 if (Subtarget->isTargetWindows())
1135 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1136 else
1137 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1139 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1140 // the default expansion.
1141 InsertFencesForAtomic = false;
1142 if (Subtarget->hasAnyDataBarrier() &&
1143 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1144 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1145 // to ldrex/strex loops already.
1146 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1147 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1148 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1150 // On v8, we have particularly efficient implementations of atomic fences
1151 // if they can be combined with nearby atomic loads and stores.
1152 if (!Subtarget->hasAcquireRelease() ||
1153 getTargetMachine().getOptLevel() == 0) {
1154 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1155 InsertFencesForAtomic = true;
1157 } else {
1158 // If there's anything we can use as a barrier, go through custom lowering
1159 // for ATOMIC_FENCE.
1160 // If target has DMB in thumb, Fences can be inserted.
1161 if (Subtarget->hasDataBarrier())
1162 InsertFencesForAtomic = true;
1164 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1165 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1167 // Set them all for expansion, which will force libcalls.
1168 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1169 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1170 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1171 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1172 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1173 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1174 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1175 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1176 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1177 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1178 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1179 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1180 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1181 // Unordered/Monotonic case.
1182 if (!InsertFencesForAtomic) {
1183 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1184 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1188 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1190 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1191 if (!Subtarget->hasV6Ops()) {
1192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1197 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1198 !Subtarget->isThumb1Only()) {
1199 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1200 // iff target supports vfp2.
1201 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1202 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1205 // We want to custom lower some of our intrinsics.
1206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1207 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1208 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1209 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1210 if (Subtarget->useSjLjEH())
1211 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1213 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1214 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1215 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1216 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1217 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1218 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1219 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1220 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1221 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1222 if (Subtarget->hasFullFP16()) {
1223 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1224 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1225 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1228 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1230 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1231 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1232 if (Subtarget->hasFullFP16())
1233 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1234 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1235 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1238 // We don't support sin/cos/fmod/copysign/pow
1239 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1240 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1241 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1242 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1243 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1244 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1245 setOperationAction(ISD::FREM, MVT::f64, Expand);
1246 setOperationAction(ISD::FREM, MVT::f32, Expand);
1247 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1248 !Subtarget->isThumb1Only()) {
1249 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1252 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1253 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1255 if (!Subtarget->hasVFP4Base()) {
1256 setOperationAction(ISD::FMA, MVT::f64, Expand);
1257 setOperationAction(ISD::FMA, MVT::f32, Expand);
1260 // Various VFP goodness
1261 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1262 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1263 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1264 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1265 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1268 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1269 if (!Subtarget->hasFP16()) {
1270 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1271 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1275 // Use __sincos_stret if available.
1276 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1277 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1278 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1279 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1282 // FP-ARMv8 implements a lot of rounding-like FP operations.
1283 if (Subtarget->hasFPARMv8Base()) {
1284 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1285 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1286 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1287 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1288 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1289 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1290 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1291 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1292 if (Subtarget->hasNEON()) {
1293 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1294 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1295 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1296 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1299 if (Subtarget->hasFP64()) {
1300 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1301 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1302 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1303 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1304 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1305 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1306 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1307 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1311 // FP16 often need to be promoted to call lib functions
1312 if (Subtarget->hasFullFP16()) {
1313 setOperationAction(ISD::FREM, MVT::f16, Promote);
1314 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1315 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1316 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1317 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1318 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1319 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1320 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1321 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1322 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1323 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1324 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1326 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1329 if (Subtarget->hasNEON()) {
1330 // vmin and vmax aren't available in a scalar form, so we use
1331 // a NEON instruction with an undef lane instead.
1332 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1333 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1334 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1335 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1336 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1337 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1338 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1339 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1341 if (Subtarget->hasFullFP16()) {
1342 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1343 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1344 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1345 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1347 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1348 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1349 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1350 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1354 // We have target-specific dag combine patterns for the following nodes:
1355 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1356 setTargetDAGCombine(ISD::ADD);
1357 setTargetDAGCombine(ISD::SUB);
1358 setTargetDAGCombine(ISD::MUL);
1359 setTargetDAGCombine(ISD::AND);
1360 setTargetDAGCombine(ISD::OR);
1361 setTargetDAGCombine(ISD::XOR);
1363 if (Subtarget->hasV6Ops())
1364 setTargetDAGCombine(ISD::SRL);
1365 if (Subtarget->isThumb1Only())
1366 setTargetDAGCombine(ISD::SHL);
1368 setStackPointerRegisterToSaveRestore(ARM::SP);
1370 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1371 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1372 setSchedulingPreference(Sched::RegPressure);
1373 else
1374 setSchedulingPreference(Sched::Hybrid);
1376 //// temporary - rewrite interface to use type
1377 MaxStoresPerMemset = 8;
1378 MaxStoresPerMemsetOptSize = 4;
1379 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1380 MaxStoresPerMemcpyOptSize = 2;
1381 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1382 MaxStoresPerMemmoveOptSize = 2;
1384 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1385 // are at least 4 bytes aligned.
1386 setMinStackArgumentAlignment(4);
1388 // Prefer likely predicted branches to selects on out-of-order cores.
1389 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1391 setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1393 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1395 if (Subtarget->isThumb() || Subtarget->isThumb2())
1396 setTargetDAGCombine(ISD::ABS);
1399 bool ARMTargetLowering::useSoftFloat() const {
1400 return Subtarget->useSoftFloat();
1403 // FIXME: It might make sense to define the representative register class as the
1404 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1405 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1406 // SPR's representative would be DPR_VFP2. This should work well if register
1407 // pressure tracking were modified such that a register use would increment the
1408 // pressure of the register class's representative and all of it's super
1409 // classes' representatives transitively. We have not implemented this because
1410 // of the difficulty prior to coalescing of modeling operand register classes
1411 // due to the common occurrence of cross class copies and subregister insertions
1412 // and extractions.
1413 std::pair<const TargetRegisterClass *, uint8_t>
1414 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1415 MVT VT) const {
1416 const TargetRegisterClass *RRC = nullptr;
1417 uint8_t Cost = 1;
1418 switch (VT.SimpleTy) {
1419 default:
1420 return TargetLowering::findRepresentativeClass(TRI, VT);
1421 // Use DPR as representative register class for all floating point
1422 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1423 // the cost is 1 for both f32 and f64.
1424 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1425 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1426 RRC = &ARM::DPRRegClass;
1427 // When NEON is used for SP, only half of the register file is available
1428 // because operations that define both SP and DP results will be constrained
1429 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1430 // coalescing by double-counting the SP regs. See the FIXME above.
1431 if (Subtarget->useNEONForSinglePrecisionFP())
1432 Cost = 2;
1433 break;
1434 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1435 case MVT::v4f32: case MVT::v2f64:
1436 RRC = &ARM::DPRRegClass;
1437 Cost = 2;
1438 break;
1439 case MVT::v4i64:
1440 RRC = &ARM::DPRRegClass;
1441 Cost = 4;
1442 break;
1443 case MVT::v8i64:
1444 RRC = &ARM::DPRRegClass;
1445 Cost = 8;
1446 break;
1448 return std::make_pair(RRC, Cost);
1451 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1452 switch ((ARMISD::NodeType)Opcode) {
1453 case ARMISD::FIRST_NUMBER: break;
1454 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1455 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1456 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1457 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1458 case ARMISD::CALL: return "ARMISD::CALL";
1459 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1460 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1461 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1462 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1463 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1464 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1465 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1466 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1467 case ARMISD::CMP: return "ARMISD::CMP";
1468 case ARMISD::CMN: return "ARMISD::CMN";
1469 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1470 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1471 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1472 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1473 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1475 case ARMISD::CMOV: return "ARMISD::CMOV";
1476 case ARMISD::SUBS: return "ARMISD::SUBS";
1478 case ARMISD::SSAT: return "ARMISD::SSAT";
1479 case ARMISD::USAT: return "ARMISD::USAT";
1481 case ARMISD::ASRL: return "ARMISD::ASRL";
1482 case ARMISD::LSRL: return "ARMISD::LSRL";
1483 case ARMISD::LSLL: return "ARMISD::LSLL";
1485 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1486 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1487 case ARMISD::RRX: return "ARMISD::RRX";
1489 case ARMISD::ADDC: return "ARMISD::ADDC";
1490 case ARMISD::ADDE: return "ARMISD::ADDE";
1491 case ARMISD::SUBC: return "ARMISD::SUBC";
1492 case ARMISD::SUBE: return "ARMISD::SUBE";
1494 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1495 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1496 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1497 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1498 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1500 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1501 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1502 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1504 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1506 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1508 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1510 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1512 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1514 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1515 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1517 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1518 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1519 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1520 case ARMISD::VCNE: return "ARMISD::VCNE";
1521 case ARMISD::VCNEZ: return "ARMISD::VCNEZ";
1522 case ARMISD::VCGE: return "ARMISD::VCGE";
1523 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1524 case ARMISD::VCLE: return "ARMISD::VCLE";
1525 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1526 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1527 case ARMISD::VCGT: return "ARMISD::VCGT";
1528 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1529 case ARMISD::VCLT: return "ARMISD::VCLT";
1530 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1531 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1532 case ARMISD::VTST: return "ARMISD::VTST";
1534 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1535 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1536 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1537 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1538 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1539 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1540 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1541 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1542 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1543 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1544 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1545 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1546 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1547 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1548 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1549 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1550 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1551 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1552 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1553 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1554 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1555 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1556 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1557 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1558 case ARMISD::VDUP: return "ARMISD::VDUP";
1559 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1560 case ARMISD::VEXT: return "ARMISD::VEXT";
1561 case ARMISD::VREV64: return "ARMISD::VREV64";
1562 case ARMISD::VREV32: return "ARMISD::VREV32";
1563 case ARMISD::VREV16: return "ARMISD::VREV16";
1564 case ARMISD::VZIP: return "ARMISD::VZIP";
1565 case ARMISD::VUZP: return "ARMISD::VUZP";
1566 case ARMISD::VTRN: return "ARMISD::VTRN";
1567 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1568 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1569 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1570 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1571 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1572 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1573 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1574 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1575 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1576 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1577 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1578 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1579 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1580 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1581 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1582 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1583 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1584 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1585 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1586 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1587 case ARMISD::BFI: return "ARMISD::BFI";
1588 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1589 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1590 case ARMISD::VBSL: return "ARMISD::VBSL";
1591 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1592 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1593 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1594 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1595 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1596 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1597 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1598 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1599 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1600 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1601 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1602 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1603 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1604 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1605 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1606 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1607 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1608 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1609 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1610 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1611 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1612 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1613 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1614 case ARMISD::WLS: return "ARMISD::WLS";
1615 case ARMISD::LE: return "ARMISD::LE";
1616 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1618 return nullptr;
1621 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1622 EVT VT) const {
1623 if (!VT.isVector())
1624 return getPointerTy(DL);
1626 // MVE has a predicate register.
1627 if (Subtarget->hasMVEIntegerOps() &&
1628 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1629 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1630 return VT.changeVectorElementTypeToInteger();
1633 /// getRegClassFor - Return the register class that should be used for the
1634 /// specified value type.
1635 const TargetRegisterClass *
1636 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1637 (void)isDivergent;
1638 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1639 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1640 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1641 // MVE Q registers.
1642 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1643 if (VT == MVT::v4i64)
1644 return &ARM::QQPRRegClass;
1645 if (VT == MVT::v8i64)
1646 return &ARM::QQQQPRRegClass;
1648 return TargetLowering::getRegClassFor(VT);
1651 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1652 // source/dest is aligned and the copy size is large enough. We therefore want
1653 // to align such objects passed to memory intrinsics.
1654 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1655 unsigned &PrefAlign) const {
1656 if (!isa<MemIntrinsic>(CI))
1657 return false;
1658 MinSize = 8;
1659 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1660 // cycle faster than 4-byte aligned LDM.
1661 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1662 return true;
1665 // Create a fast isel object.
1666 FastISel *
1667 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1668 const TargetLibraryInfo *libInfo) const {
1669 return ARM::createFastISel(funcInfo, libInfo);
1672 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1673 unsigned NumVals = N->getNumValues();
1674 if (!NumVals)
1675 return Sched::RegPressure;
1677 for (unsigned i = 0; i != NumVals; ++i) {
1678 EVT VT = N->getValueType(i);
1679 if (VT == MVT::Glue || VT == MVT::Other)
1680 continue;
1681 if (VT.isFloatingPoint() || VT.isVector())
1682 return Sched::ILP;
1685 if (!N->isMachineOpcode())
1686 return Sched::RegPressure;
1688 // Load are scheduled for latency even if there instruction itinerary
1689 // is not available.
1690 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1691 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1693 if (MCID.getNumDefs() == 0)
1694 return Sched::RegPressure;
1695 if (!Itins->isEmpty() &&
1696 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1697 return Sched::ILP;
1699 return Sched::RegPressure;
1702 //===----------------------------------------------------------------------===//
1703 // Lowering Code
1704 //===----------------------------------------------------------------------===//
1706 static bool isSRL16(const SDValue &Op) {
1707 if (Op.getOpcode() != ISD::SRL)
1708 return false;
1709 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1710 return Const->getZExtValue() == 16;
1711 return false;
1714 static bool isSRA16(const SDValue &Op) {
1715 if (Op.getOpcode() != ISD::SRA)
1716 return false;
1717 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1718 return Const->getZExtValue() == 16;
1719 return false;
1722 static bool isSHL16(const SDValue &Op) {
1723 if (Op.getOpcode() != ISD::SHL)
1724 return false;
1725 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1726 return Const->getZExtValue() == 16;
1727 return false;
1730 // Check for a signed 16-bit value. We special case SRA because it makes it
1731 // more simple when also looking for SRAs that aren't sign extending a
1732 // smaller value. Without the check, we'd need to take extra care with
1733 // checking order for some operations.
1734 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1735 if (isSRA16(Op))
1736 return isSHL16(Op.getOperand(0));
1737 return DAG.ComputeNumSignBits(Op) == 17;
1740 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1741 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1742 switch (CC) {
1743 default: llvm_unreachable("Unknown condition code!");
1744 case ISD::SETNE: return ARMCC::NE;
1745 case ISD::SETEQ: return ARMCC::EQ;
1746 case ISD::SETGT: return ARMCC::GT;
1747 case ISD::SETGE: return ARMCC::GE;
1748 case ISD::SETLT: return ARMCC::LT;
1749 case ISD::SETLE: return ARMCC::LE;
1750 case ISD::SETUGT: return ARMCC::HI;
1751 case ISD::SETUGE: return ARMCC::HS;
1752 case ISD::SETULT: return ARMCC::LO;
1753 case ISD::SETULE: return ARMCC::LS;
1757 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1758 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1759 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1760 CondCode2 = ARMCC::AL;
1761 InvalidOnQNaN = true;
1762 switch (CC) {
1763 default: llvm_unreachable("Unknown FP condition!");
1764 case ISD::SETEQ:
1765 case ISD::SETOEQ:
1766 CondCode = ARMCC::EQ;
1767 InvalidOnQNaN = false;
1768 break;
1769 case ISD::SETGT:
1770 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1771 case ISD::SETGE:
1772 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1773 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1774 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1775 case ISD::SETONE:
1776 CondCode = ARMCC::MI;
1777 CondCode2 = ARMCC::GT;
1778 InvalidOnQNaN = false;
1779 break;
1780 case ISD::SETO: CondCode = ARMCC::VC; break;
1781 case ISD::SETUO: CondCode = ARMCC::VS; break;
1782 case ISD::SETUEQ:
1783 CondCode = ARMCC::EQ;
1784 CondCode2 = ARMCC::VS;
1785 InvalidOnQNaN = false;
1786 break;
1787 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1788 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1789 case ISD::SETLT:
1790 case ISD::SETULT: CondCode = ARMCC::LT; break;
1791 case ISD::SETLE:
1792 case ISD::SETULE: CondCode = ARMCC::LE; break;
1793 case ISD::SETNE:
1794 case ISD::SETUNE:
1795 CondCode = ARMCC::NE;
1796 InvalidOnQNaN = false;
1797 break;
1801 //===----------------------------------------------------------------------===//
1802 // Calling Convention Implementation
1803 //===----------------------------------------------------------------------===//
1805 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1806 /// account presence of floating point hardware and calling convention
1807 /// limitations, such as support for variadic functions.
1808 CallingConv::ID
1809 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1810 bool isVarArg) const {
1811 switch (CC) {
1812 default:
1813 report_fatal_error("Unsupported calling convention");
1814 case CallingConv::ARM_AAPCS:
1815 case CallingConv::ARM_APCS:
1816 case CallingConv::GHC:
1817 return CC;
1818 case CallingConv::PreserveMost:
1819 return CallingConv::PreserveMost;
1820 case CallingConv::ARM_AAPCS_VFP:
1821 case CallingConv::Swift:
1822 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1823 case CallingConv::C:
1824 if (!Subtarget->isAAPCS_ABI())
1825 return CallingConv::ARM_APCS;
1826 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1827 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1828 !isVarArg)
1829 return CallingConv::ARM_AAPCS_VFP;
1830 else
1831 return CallingConv::ARM_AAPCS;
1832 case CallingConv::Fast:
1833 case CallingConv::CXX_FAST_TLS:
1834 if (!Subtarget->isAAPCS_ABI()) {
1835 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1836 return CallingConv::Fast;
1837 return CallingConv::ARM_APCS;
1838 } else if (Subtarget->hasVFP2Base() &&
1839 !Subtarget->isThumb1Only() && !isVarArg)
1840 return CallingConv::ARM_AAPCS_VFP;
1841 else
1842 return CallingConv::ARM_AAPCS;
1846 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1847 bool isVarArg) const {
1848 return CCAssignFnForNode(CC, false, isVarArg);
1851 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1852 bool isVarArg) const {
1853 return CCAssignFnForNode(CC, true, isVarArg);
1856 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1857 /// CallingConvention.
1858 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1859 bool Return,
1860 bool isVarArg) const {
1861 switch (getEffectiveCallingConv(CC, isVarArg)) {
1862 default:
1863 report_fatal_error("Unsupported calling convention");
1864 case CallingConv::ARM_APCS:
1865 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1866 case CallingConv::ARM_AAPCS:
1867 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1868 case CallingConv::ARM_AAPCS_VFP:
1869 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1870 case CallingConv::Fast:
1871 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1872 case CallingConv::GHC:
1873 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1874 case CallingConv::PreserveMost:
1875 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1879 /// LowerCallResult - Lower the result values of a call into the
1880 /// appropriate copies out of appropriate physical registers.
1881 SDValue ARMTargetLowering::LowerCallResult(
1882 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1883 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1884 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1885 SDValue ThisVal) const {
1886 // Assign locations to each value returned by this call.
1887 SmallVector<CCValAssign, 16> RVLocs;
1888 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1889 *DAG.getContext());
1890 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1892 // Copy all of the result registers out of their specified physreg.
1893 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1894 CCValAssign VA = RVLocs[i];
1896 // Pass 'this' value directly from the argument to return value, to avoid
1897 // reg unit interference
1898 if (i == 0 && isThisReturn) {
1899 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1900 "unexpected return calling convention register assignment");
1901 InVals.push_back(ThisVal);
1902 continue;
1905 SDValue Val;
1906 if (VA.needsCustom()) {
1907 // Handle f64 or half of a v2f64.
1908 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1909 InFlag);
1910 Chain = Lo.getValue(1);
1911 InFlag = Lo.getValue(2);
1912 VA = RVLocs[++i]; // skip ahead to next loc
1913 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1914 InFlag);
1915 Chain = Hi.getValue(1);
1916 InFlag = Hi.getValue(2);
1917 if (!Subtarget->isLittle())
1918 std::swap (Lo, Hi);
1919 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1921 if (VA.getLocVT() == MVT::v2f64) {
1922 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1923 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1924 DAG.getConstant(0, dl, MVT::i32));
1926 VA = RVLocs[++i]; // skip ahead to next loc
1927 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1928 Chain = Lo.getValue(1);
1929 InFlag = Lo.getValue(2);
1930 VA = RVLocs[++i]; // skip ahead to next loc
1931 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1932 Chain = Hi.getValue(1);
1933 InFlag = Hi.getValue(2);
1934 if (!Subtarget->isLittle())
1935 std::swap (Lo, Hi);
1936 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1937 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1938 DAG.getConstant(1, dl, MVT::i32));
1940 } else {
1941 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1942 InFlag);
1943 Chain = Val.getValue(1);
1944 InFlag = Val.getValue(2);
1947 switch (VA.getLocInfo()) {
1948 default: llvm_unreachable("Unknown loc info!");
1949 case CCValAssign::Full: break;
1950 case CCValAssign::BCvt:
1951 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1952 break;
1955 InVals.push_back(Val);
1958 return Chain;
1961 /// LowerMemOpCallTo - Store the argument to the stack.
1962 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1963 SDValue Arg, const SDLoc &dl,
1964 SelectionDAG &DAG,
1965 const CCValAssign &VA,
1966 ISD::ArgFlagsTy Flags) const {
1967 unsigned LocMemOffset = VA.getLocMemOffset();
1968 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1969 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1970 StackPtr, PtrOff);
1971 return DAG.getStore(
1972 Chain, dl, Arg, PtrOff,
1973 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1976 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1977 SDValue Chain, SDValue &Arg,
1978 RegsToPassVector &RegsToPass,
1979 CCValAssign &VA, CCValAssign &NextVA,
1980 SDValue &StackPtr,
1981 SmallVectorImpl<SDValue> &MemOpChains,
1982 ISD::ArgFlagsTy Flags) const {
1983 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1984 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1985 unsigned id = Subtarget->isLittle() ? 0 : 1;
1986 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1988 if (NextVA.isRegLoc())
1989 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1990 else {
1991 assert(NextVA.isMemLoc());
1992 if (!StackPtr.getNode())
1993 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1994 getPointerTy(DAG.getDataLayout()));
1996 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1997 dl, DAG, NextVA,
1998 Flags));
2002 /// LowerCall - Lowering a call into a callseq_start <-
2003 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2004 /// nodes.
2005 SDValue
2006 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2007 SmallVectorImpl<SDValue> &InVals) const {
2008 SelectionDAG &DAG = CLI.DAG;
2009 SDLoc &dl = CLI.DL;
2010 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2011 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2012 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2013 SDValue Chain = CLI.Chain;
2014 SDValue Callee = CLI.Callee;
2015 bool &isTailCall = CLI.IsTailCall;
2016 CallingConv::ID CallConv = CLI.CallConv;
2017 bool doesNotRet = CLI.DoesNotReturn;
2018 bool isVarArg = CLI.IsVarArg;
2020 MachineFunction &MF = DAG.getMachineFunction();
2021 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2022 bool isThisReturn = false;
2023 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2024 bool PreferIndirect = false;
2026 // Disable tail calls if they're not supported.
2027 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2028 isTailCall = false;
2030 if (isa<GlobalAddressSDNode>(Callee)) {
2031 // If we're optimizing for minimum size and the function is called three or
2032 // more times in this block, we can improve codesize by calling indirectly
2033 // as BLXr has a 16-bit encoding.
2034 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2035 if (CLI.CS) {
2036 auto *BB = CLI.CS.getParent();
2037 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2038 count_if(GV->users(), [&BB](const User *U) {
2039 return isa<Instruction>(U) &&
2040 cast<Instruction>(U)->getParent() == BB;
2041 }) > 2;
2044 if (isTailCall) {
2045 // Check if it's really possible to do a tail call.
2046 isTailCall = IsEligibleForTailCallOptimization(
2047 Callee, CallConv, isVarArg, isStructRet,
2048 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2049 PreferIndirect);
2050 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2051 report_fatal_error("failed to perform tail call elimination on a call "
2052 "site marked musttail");
2053 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2054 // detected sibcalls.
2055 if (isTailCall)
2056 ++NumTailCalls;
2059 // Analyze operands of the call, assigning locations to each operand.
2060 SmallVector<CCValAssign, 16> ArgLocs;
2061 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2062 *DAG.getContext());
2063 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2065 // Get a count of how many bytes are to be pushed on the stack.
2066 unsigned NumBytes = CCInfo.getNextStackOffset();
2068 if (isTailCall) {
2069 // For tail calls, memory operands are available in our caller's stack.
2070 NumBytes = 0;
2071 } else {
2072 // Adjust the stack pointer for the new arguments...
2073 // These operations are automatically eliminated by the prolog/epilog pass
2074 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2077 SDValue StackPtr =
2078 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2080 RegsToPassVector RegsToPass;
2081 SmallVector<SDValue, 8> MemOpChains;
2083 // Walk the register/memloc assignments, inserting copies/loads. In the case
2084 // of tail call optimization, arguments are handled later.
2085 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2086 i != e;
2087 ++i, ++realArgIdx) {
2088 CCValAssign &VA = ArgLocs[i];
2089 SDValue Arg = OutVals[realArgIdx];
2090 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2091 bool isByVal = Flags.isByVal();
2093 // Promote the value if needed.
2094 switch (VA.getLocInfo()) {
2095 default: llvm_unreachable("Unknown loc info!");
2096 case CCValAssign::Full: break;
2097 case CCValAssign::SExt:
2098 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2099 break;
2100 case CCValAssign::ZExt:
2101 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2102 break;
2103 case CCValAssign::AExt:
2104 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2105 break;
2106 case CCValAssign::BCvt:
2107 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2108 break;
2111 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2112 if (VA.needsCustom()) {
2113 if (VA.getLocVT() == MVT::v2f64) {
2114 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2115 DAG.getConstant(0, dl, MVT::i32));
2116 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2117 DAG.getConstant(1, dl, MVT::i32));
2119 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2120 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2122 VA = ArgLocs[++i]; // skip ahead to next loc
2123 if (VA.isRegLoc()) {
2124 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2125 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2126 } else {
2127 assert(VA.isMemLoc());
2129 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2130 dl, DAG, VA, Flags));
2132 } else {
2133 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2134 StackPtr, MemOpChains, Flags);
2136 } else if (VA.isRegLoc()) {
2137 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2138 Outs[0].VT == MVT::i32) {
2139 assert(VA.getLocVT() == MVT::i32 &&
2140 "unexpected calling convention register assignment");
2141 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2142 "unexpected use of 'returned'");
2143 isThisReturn = true;
2145 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2146 } else if (isByVal) {
2147 assert(VA.isMemLoc());
2148 unsigned offset = 0;
2150 // True if this byval aggregate will be split between registers
2151 // and memory.
2152 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2153 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2155 if (CurByValIdx < ByValArgsCount) {
2157 unsigned RegBegin, RegEnd;
2158 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2160 EVT PtrVT =
2161 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2162 unsigned int i, j;
2163 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2164 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2165 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2166 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2167 MachinePointerInfo(),
2168 DAG.InferPtrAlignment(AddArg));
2169 MemOpChains.push_back(Load.getValue(1));
2170 RegsToPass.push_back(std::make_pair(j, Load));
2173 // If parameter size outsides register area, "offset" value
2174 // helps us to calculate stack slot for remained part properly.
2175 offset = RegEnd - RegBegin;
2177 CCInfo.nextInRegsParam();
2180 if (Flags.getByValSize() > 4*offset) {
2181 auto PtrVT = getPointerTy(DAG.getDataLayout());
2182 unsigned LocMemOffset = VA.getLocMemOffset();
2183 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2184 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2185 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2186 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2187 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2188 MVT::i32);
2189 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2190 MVT::i32);
2192 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2193 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2194 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2195 Ops));
2197 } else if (!isTailCall) {
2198 assert(VA.isMemLoc());
2200 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2201 dl, DAG, VA, Flags));
2205 if (!MemOpChains.empty())
2206 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2208 // Build a sequence of copy-to-reg nodes chained together with token chain
2209 // and flag operands which copy the outgoing args into the appropriate regs.
2210 SDValue InFlag;
2211 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2212 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2213 RegsToPass[i].second, InFlag);
2214 InFlag = Chain.getValue(1);
2217 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2218 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2219 // node so that legalize doesn't hack it.
2220 bool isDirect = false;
2222 const TargetMachine &TM = getTargetMachine();
2223 const Module *Mod = MF.getFunction().getParent();
2224 const GlobalValue *GV = nullptr;
2225 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2226 GV = G->getGlobal();
2227 bool isStub =
2228 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2230 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2231 bool isLocalARMFunc = false;
2232 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2233 auto PtrVt = getPointerTy(DAG.getDataLayout());
2235 if (Subtarget->genLongCalls()) {
2236 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2237 "long-calls codegen is not position independent!");
2238 // Handle a global address or an external symbol. If it's not one of
2239 // those, the target's already in a register, so we don't need to do
2240 // anything extra.
2241 if (isa<GlobalAddressSDNode>(Callee)) {
2242 // Create a constant pool entry for the callee address
2243 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2244 ARMConstantPoolValue *CPV =
2245 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2247 // Get the address of the callee into a register
2248 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2249 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2250 Callee = DAG.getLoad(
2251 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2252 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2253 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2254 const char *Sym = S->getSymbol();
2256 // Create a constant pool entry for the callee address
2257 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2258 ARMConstantPoolValue *CPV =
2259 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2260 ARMPCLabelIndex, 0);
2261 // Get the address of the callee into a register
2262 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2263 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2264 Callee = DAG.getLoad(
2265 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2266 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2268 } else if (isa<GlobalAddressSDNode>(Callee)) {
2269 if (!PreferIndirect) {
2270 isDirect = true;
2271 bool isDef = GV->isStrongDefinitionForLinker();
2273 // ARM call to a local ARM function is predicable.
2274 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2275 // tBX takes a register source operand.
2276 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2277 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2278 Callee = DAG.getNode(
2279 ARMISD::WrapperPIC, dl, PtrVt,
2280 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2281 Callee = DAG.getLoad(
2282 PtrVt, dl, DAG.getEntryNode(), Callee,
2283 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2284 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2285 MachineMemOperand::MOInvariant);
2286 } else if (Subtarget->isTargetCOFF()) {
2287 assert(Subtarget->isTargetWindows() &&
2288 "Windows is the only supported COFF target");
2289 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2290 ? ARMII::MO_DLLIMPORT
2291 : ARMII::MO_NO_FLAG;
2292 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2293 TargetFlags);
2294 if (GV->hasDLLImportStorageClass())
2295 Callee =
2296 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2297 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2298 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2299 } else {
2300 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2303 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2304 isDirect = true;
2305 // tBX takes a register source operand.
2306 const char *Sym = S->getSymbol();
2307 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2308 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2309 ARMConstantPoolValue *CPV =
2310 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2311 ARMPCLabelIndex, 4);
2312 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2313 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2314 Callee = DAG.getLoad(
2315 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2316 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2317 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2318 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2319 } else {
2320 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2324 // FIXME: handle tail calls differently.
2325 unsigned CallOpc;
2326 if (Subtarget->isThumb()) {
2327 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2328 CallOpc = ARMISD::CALL_NOLINK;
2329 else
2330 CallOpc = ARMISD::CALL;
2331 } else {
2332 if (!isDirect && !Subtarget->hasV5TOps())
2333 CallOpc = ARMISD::CALL_NOLINK;
2334 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2335 // Emit regular call when code size is the priority
2336 !Subtarget->hasMinSize())
2337 // "mov lr, pc; b _foo" to avoid confusing the RSP
2338 CallOpc = ARMISD::CALL_NOLINK;
2339 else
2340 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2343 std::vector<SDValue> Ops;
2344 Ops.push_back(Chain);
2345 Ops.push_back(Callee);
2347 // Add argument registers to the end of the list so that they are known live
2348 // into the call.
2349 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2350 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2351 RegsToPass[i].second.getValueType()));
2353 // Add a register mask operand representing the call-preserved registers.
2354 if (!isTailCall) {
2355 const uint32_t *Mask;
2356 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2357 if (isThisReturn) {
2358 // For 'this' returns, use the R0-preserving mask if applicable
2359 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2360 if (!Mask) {
2361 // Set isThisReturn to false if the calling convention is not one that
2362 // allows 'returned' to be modeled in this way, so LowerCallResult does
2363 // not try to pass 'this' straight through
2364 isThisReturn = false;
2365 Mask = ARI->getCallPreservedMask(MF, CallConv);
2367 } else
2368 Mask = ARI->getCallPreservedMask(MF, CallConv);
2370 assert(Mask && "Missing call preserved mask for calling convention");
2371 Ops.push_back(DAG.getRegisterMask(Mask));
2374 if (InFlag.getNode())
2375 Ops.push_back(InFlag);
2377 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2378 if (isTailCall) {
2379 MF.getFrameInfo().setHasTailCall();
2380 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2383 // Returns a chain and a flag for retval copy to use.
2384 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2385 InFlag = Chain.getValue(1);
2387 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2388 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2389 if (!Ins.empty())
2390 InFlag = Chain.getValue(1);
2392 // Handle result values, copying them out of physregs into vregs that we
2393 // return.
2394 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2395 InVals, isThisReturn,
2396 isThisReturn ? OutVals[0] : SDValue());
2399 /// HandleByVal - Every parameter *after* a byval parameter is passed
2400 /// on the stack. Remember the next parameter register to allocate,
2401 /// and then confiscate the rest of the parameter registers to insure
2402 /// this.
2403 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2404 unsigned Align) const {
2405 // Byval (as with any stack) slots are always at least 4 byte aligned.
2406 Align = std::max(Align, 4U);
2408 unsigned Reg = State->AllocateReg(GPRArgRegs);
2409 if (!Reg)
2410 return;
2412 unsigned AlignInRegs = Align / 4;
2413 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2414 for (unsigned i = 0; i < Waste; ++i)
2415 Reg = State->AllocateReg(GPRArgRegs);
2417 if (!Reg)
2418 return;
2420 unsigned Excess = 4 * (ARM::R4 - Reg);
2422 // Special case when NSAA != SP and parameter size greater than size of
2423 // all remained GPR regs. In that case we can't split parameter, we must
2424 // send it to stack. We also must set NCRN to R4, so waste all
2425 // remained registers.
2426 const unsigned NSAAOffset = State->getNextStackOffset();
2427 if (NSAAOffset != 0 && Size > Excess) {
2428 while (State->AllocateReg(GPRArgRegs))
2430 return;
2433 // First register for byval parameter is the first register that wasn't
2434 // allocated before this method call, so it would be "reg".
2435 // If parameter is small enough to be saved in range [reg, r4), then
2436 // the end (first after last) register would be reg + param-size-in-regs,
2437 // else parameter would be splitted between registers and stack,
2438 // end register would be r4 in this case.
2439 unsigned ByValRegBegin = Reg;
2440 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2441 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2442 // Note, first register is allocated in the beginning of function already,
2443 // allocate remained amount of registers we need.
2444 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2445 State->AllocateReg(GPRArgRegs);
2446 // A byval parameter that is split between registers and memory needs its
2447 // size truncated here.
2448 // In the case where the entire structure fits in registers, we set the
2449 // size in memory to zero.
2450 Size = std::max<int>(Size - Excess, 0);
2453 /// MatchingStackOffset - Return true if the given stack call argument is
2454 /// already available in the same position (relatively) of the caller's
2455 /// incoming argument stack.
2456 static
2457 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2458 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2459 const TargetInstrInfo *TII) {
2460 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2461 int FI = std::numeric_limits<int>::max();
2462 if (Arg.getOpcode() == ISD::CopyFromReg) {
2463 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2464 if (!TargetRegisterInfo::isVirtualRegister(VR))
2465 return false;
2466 MachineInstr *Def = MRI->getVRegDef(VR);
2467 if (!Def)
2468 return false;
2469 if (!Flags.isByVal()) {
2470 if (!TII->isLoadFromStackSlot(*Def, FI))
2471 return false;
2472 } else {
2473 return false;
2475 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2476 if (Flags.isByVal())
2477 // ByVal argument is passed in as a pointer but it's now being
2478 // dereferenced. e.g.
2479 // define @foo(%struct.X* %A) {
2480 // tail call @bar(%struct.X* byval %A)
2481 // }
2482 return false;
2483 SDValue Ptr = Ld->getBasePtr();
2484 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2485 if (!FINode)
2486 return false;
2487 FI = FINode->getIndex();
2488 } else
2489 return false;
2491 assert(FI != std::numeric_limits<int>::max());
2492 if (!MFI.isFixedObjectIndex(FI))
2493 return false;
2494 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2497 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2498 /// for tail call optimization. Targets which want to do tail call
2499 /// optimization should implement this function.
2500 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2501 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2502 bool isCalleeStructRet, bool isCallerStructRet,
2503 const SmallVectorImpl<ISD::OutputArg> &Outs,
2504 const SmallVectorImpl<SDValue> &OutVals,
2505 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2506 const bool isIndirect) const {
2507 MachineFunction &MF = DAG.getMachineFunction();
2508 const Function &CallerF = MF.getFunction();
2509 CallingConv::ID CallerCC = CallerF.getCallingConv();
2511 assert(Subtarget->supportsTailCall());
2513 // Indirect tail calls cannot be optimized for Thumb1 if the args
2514 // to the call take up r0-r3. The reason is that there are no legal registers
2515 // left to hold the pointer to the function to be called.
2516 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2517 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2518 return false;
2520 // Look for obvious safe cases to perform tail call optimization that do not
2521 // require ABI changes. This is what gcc calls sibcall.
2523 // Exception-handling functions need a special set of instructions to indicate
2524 // a return to the hardware. Tail-calling another function would probably
2525 // break this.
2526 if (CallerF.hasFnAttribute("interrupt"))
2527 return false;
2529 // Also avoid sibcall optimization if either caller or callee uses struct
2530 // return semantics.
2531 if (isCalleeStructRet || isCallerStructRet)
2532 return false;
2534 // Externally-defined functions with weak linkage should not be
2535 // tail-called on ARM when the OS does not support dynamic
2536 // pre-emption of symbols, as the AAELF spec requires normal calls
2537 // to undefined weak functions to be replaced with a NOP or jump to the
2538 // next instruction. The behaviour of branch instructions in this
2539 // situation (as used for tail calls) is implementation-defined, so we
2540 // cannot rely on the linker replacing the tail call with a return.
2541 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2542 const GlobalValue *GV = G->getGlobal();
2543 const Triple &TT = getTargetMachine().getTargetTriple();
2544 if (GV->hasExternalWeakLinkage() &&
2545 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2546 return false;
2549 // Check that the call results are passed in the same way.
2550 LLVMContext &C = *DAG.getContext();
2551 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2552 CCAssignFnForReturn(CalleeCC, isVarArg),
2553 CCAssignFnForReturn(CallerCC, isVarArg)))
2554 return false;
2555 // The callee has to preserve all registers the caller needs to preserve.
2556 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2557 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2558 if (CalleeCC != CallerCC) {
2559 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2560 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2561 return false;
2564 // If Caller's vararg or byval argument has been split between registers and
2565 // stack, do not perform tail call, since part of the argument is in caller's
2566 // local frame.
2567 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2568 if (AFI_Caller->getArgRegsSaveSize())
2569 return false;
2571 // If the callee takes no arguments then go on to check the results of the
2572 // call.
2573 if (!Outs.empty()) {
2574 // Check if stack adjustment is needed. For now, do not do this if any
2575 // argument is passed on the stack.
2576 SmallVector<CCValAssign, 16> ArgLocs;
2577 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2578 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2579 if (CCInfo.getNextStackOffset()) {
2580 // Check if the arguments are already laid out in the right way as
2581 // the caller's fixed stack objects.
2582 MachineFrameInfo &MFI = MF.getFrameInfo();
2583 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2584 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2585 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2586 i != e;
2587 ++i, ++realArgIdx) {
2588 CCValAssign &VA = ArgLocs[i];
2589 EVT RegVT = VA.getLocVT();
2590 SDValue Arg = OutVals[realArgIdx];
2591 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2592 if (VA.getLocInfo() == CCValAssign::Indirect)
2593 return false;
2594 if (VA.needsCustom()) {
2595 // f64 and vector types are split into multiple registers or
2596 // register/stack-slot combinations. The types will not match
2597 // the registers; give up on memory f64 refs until we figure
2598 // out what to do about this.
2599 if (!VA.isRegLoc())
2600 return false;
2601 if (!ArgLocs[++i].isRegLoc())
2602 return false;
2603 if (RegVT == MVT::v2f64) {
2604 if (!ArgLocs[++i].isRegLoc())
2605 return false;
2606 if (!ArgLocs[++i].isRegLoc())
2607 return false;
2609 } else if (!VA.isRegLoc()) {
2610 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2611 MFI, MRI, TII))
2612 return false;
2617 const MachineRegisterInfo &MRI = MF.getRegInfo();
2618 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2619 return false;
2622 return true;
2625 bool
2626 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2627 MachineFunction &MF, bool isVarArg,
2628 const SmallVectorImpl<ISD::OutputArg> &Outs,
2629 LLVMContext &Context) const {
2630 SmallVector<CCValAssign, 16> RVLocs;
2631 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2632 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2635 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2636 const SDLoc &DL, SelectionDAG &DAG) {
2637 const MachineFunction &MF = DAG.getMachineFunction();
2638 const Function &F = MF.getFunction();
2640 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2642 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2643 // version of the "preferred return address". These offsets affect the return
2644 // instruction if this is a return from PL1 without hypervisor extensions.
2645 // IRQ/FIQ: +4 "subs pc, lr, #4"
2646 // SWI: 0 "subs pc, lr, #0"
2647 // ABORT: +4 "subs pc, lr, #4"
2648 // UNDEF: +4/+2 "subs pc, lr, #0"
2649 // UNDEF varies depending on where the exception came from ARM or Thumb
2650 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2652 int64_t LROffset;
2653 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2654 IntKind == "ABORT")
2655 LROffset = 4;
2656 else if (IntKind == "SWI" || IntKind == "UNDEF")
2657 LROffset = 0;
2658 else
2659 report_fatal_error("Unsupported interrupt attribute. If present, value "
2660 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2662 RetOps.insert(RetOps.begin() + 1,
2663 DAG.getConstant(LROffset, DL, MVT::i32, false));
2665 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2668 SDValue
2669 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2670 bool isVarArg,
2671 const SmallVectorImpl<ISD::OutputArg> &Outs,
2672 const SmallVectorImpl<SDValue> &OutVals,
2673 const SDLoc &dl, SelectionDAG &DAG) const {
2674 // CCValAssign - represent the assignment of the return value to a location.
2675 SmallVector<CCValAssign, 16> RVLocs;
2677 // CCState - Info about the registers and stack slots.
2678 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2679 *DAG.getContext());
2681 // Analyze outgoing return values.
2682 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2684 SDValue Flag;
2685 SmallVector<SDValue, 4> RetOps;
2686 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2687 bool isLittleEndian = Subtarget->isLittle();
2689 MachineFunction &MF = DAG.getMachineFunction();
2690 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2691 AFI->setReturnRegsCount(RVLocs.size());
2693 // Copy the result values into the output registers.
2694 for (unsigned i = 0, realRVLocIdx = 0;
2695 i != RVLocs.size();
2696 ++i, ++realRVLocIdx) {
2697 CCValAssign &VA = RVLocs[i];
2698 assert(VA.isRegLoc() && "Can only return in registers!");
2700 SDValue Arg = OutVals[realRVLocIdx];
2701 bool ReturnF16 = false;
2703 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2704 // Half-precision return values can be returned like this:
2706 // t11 f16 = fadd ...
2707 // t12: i16 = bitcast t11
2708 // t13: i32 = zero_extend t12
2709 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2711 // to avoid code generation for bitcasts, we simply set Arg to the node
2712 // that produces the f16 value, t11 in this case.
2714 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2715 SDValue ZE = Arg.getOperand(0);
2716 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2717 SDValue BC = ZE.getOperand(0);
2718 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2719 Arg = BC.getOperand(0);
2720 ReturnF16 = true;
2726 switch (VA.getLocInfo()) {
2727 default: llvm_unreachable("Unknown loc info!");
2728 case CCValAssign::Full: break;
2729 case CCValAssign::BCvt:
2730 if (!ReturnF16)
2731 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2732 break;
2735 if (VA.needsCustom()) {
2736 if (VA.getLocVT() == MVT::v2f64) {
2737 // Extract the first half and return it in two registers.
2738 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2739 DAG.getConstant(0, dl, MVT::i32));
2740 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2741 DAG.getVTList(MVT::i32, MVT::i32), Half);
2743 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2744 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2745 Flag);
2746 Flag = Chain.getValue(1);
2747 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2748 VA = RVLocs[++i]; // skip ahead to next loc
2749 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2750 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2751 Flag);
2752 Flag = Chain.getValue(1);
2753 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2754 VA = RVLocs[++i]; // skip ahead to next loc
2756 // Extract the 2nd half and fall through to handle it as an f64 value.
2757 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2758 DAG.getConstant(1, dl, MVT::i32));
2760 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2761 // available.
2762 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2763 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2764 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2765 fmrrd.getValue(isLittleEndian ? 0 : 1),
2766 Flag);
2767 Flag = Chain.getValue(1);
2768 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2769 VA = RVLocs[++i]; // skip ahead to next loc
2770 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2771 fmrrd.getValue(isLittleEndian ? 1 : 0),
2772 Flag);
2773 } else
2774 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2776 // Guarantee that all emitted copies are
2777 // stuck together, avoiding something bad.
2778 Flag = Chain.getValue(1);
2779 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2780 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2782 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2783 const MCPhysReg *I =
2784 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2785 if (I) {
2786 for (; *I; ++I) {
2787 if (ARM::GPRRegClass.contains(*I))
2788 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2789 else if (ARM::DPRRegClass.contains(*I))
2790 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2791 else
2792 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2796 // Update chain and glue.
2797 RetOps[0] = Chain;
2798 if (Flag.getNode())
2799 RetOps.push_back(Flag);
2801 // CPUs which aren't M-class use a special sequence to return from
2802 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2803 // though we use "subs pc, lr, #N").
2805 // M-class CPUs actually use a normal return sequence with a special
2806 // (hardware-provided) value in LR, so the normal code path works.
2807 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2808 !Subtarget->isMClass()) {
2809 if (Subtarget->isThumb1Only())
2810 report_fatal_error("interrupt attribute is not supported in Thumb1");
2811 return LowerInterruptReturn(RetOps, dl, DAG);
2814 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2817 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2818 if (N->getNumValues() != 1)
2819 return false;
2820 if (!N->hasNUsesOfValue(1, 0))
2821 return false;
2823 SDValue TCChain = Chain;
2824 SDNode *Copy = *N->use_begin();
2825 if (Copy->getOpcode() == ISD::CopyToReg) {
2826 // If the copy has a glue operand, we conservatively assume it isn't safe to
2827 // perform a tail call.
2828 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2829 return false;
2830 TCChain = Copy->getOperand(0);
2831 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2832 SDNode *VMov = Copy;
2833 // f64 returned in a pair of GPRs.
2834 SmallPtrSet<SDNode*, 2> Copies;
2835 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2836 UI != UE; ++UI) {
2837 if (UI->getOpcode() != ISD::CopyToReg)
2838 return false;
2839 Copies.insert(*UI);
2841 if (Copies.size() > 2)
2842 return false;
2844 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2845 UI != UE; ++UI) {
2846 SDValue UseChain = UI->getOperand(0);
2847 if (Copies.count(UseChain.getNode()))
2848 // Second CopyToReg
2849 Copy = *UI;
2850 else {
2851 // We are at the top of this chain.
2852 // If the copy has a glue operand, we conservatively assume it
2853 // isn't safe to perform a tail call.
2854 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2855 return false;
2856 // First CopyToReg
2857 TCChain = UseChain;
2860 } else if (Copy->getOpcode() == ISD::BITCAST) {
2861 // f32 returned in a single GPR.
2862 if (!Copy->hasOneUse())
2863 return false;
2864 Copy = *Copy->use_begin();
2865 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2866 return false;
2867 // If the copy has a glue operand, we conservatively assume it isn't safe to
2868 // perform a tail call.
2869 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2870 return false;
2871 TCChain = Copy->getOperand(0);
2872 } else {
2873 return false;
2876 bool HasRet = false;
2877 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2878 UI != UE; ++UI) {
2879 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2880 UI->getOpcode() != ARMISD::INTRET_FLAG)
2881 return false;
2882 HasRet = true;
2885 if (!HasRet)
2886 return false;
2888 Chain = TCChain;
2889 return true;
2892 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2893 if (!Subtarget->supportsTailCall())
2894 return false;
2896 auto Attr =
2897 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2898 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2899 return false;
2901 return true;
2904 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2905 // and pass the lower and high parts through.
2906 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2907 SDLoc DL(Op);
2908 SDValue WriteValue = Op->getOperand(2);
2910 // This function is only supposed to be called for i64 type argument.
2911 assert(WriteValue.getValueType() == MVT::i64
2912 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2914 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2915 DAG.getConstant(0, DL, MVT::i32));
2916 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2917 DAG.getConstant(1, DL, MVT::i32));
2918 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2919 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2922 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2923 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2924 // one of the above mentioned nodes. It has to be wrapped because otherwise
2925 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2926 // be used to form addressing mode. These wrapped nodes will be selected
2927 // into MOVi.
2928 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2929 SelectionDAG &DAG) const {
2930 EVT PtrVT = Op.getValueType();
2931 // FIXME there is no actual debug info here
2932 SDLoc dl(Op);
2933 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2934 SDValue Res;
2936 // When generating execute-only code Constant Pools must be promoted to the
2937 // global data section. It's a bit ugly that we can't share them across basic
2938 // blocks, but this way we guarantee that execute-only behaves correct with
2939 // position-independent addressing modes.
2940 if (Subtarget->genExecuteOnly()) {
2941 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2942 auto T = const_cast<Type*>(CP->getType());
2943 auto C = const_cast<Constant*>(CP->getConstVal());
2944 auto M = const_cast<Module*>(DAG.getMachineFunction().
2945 getFunction().getParent());
2946 auto GV = new GlobalVariable(
2947 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2948 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2949 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2950 Twine(AFI->createPICLabelUId())
2952 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2953 dl, PtrVT);
2954 return LowerGlobalAddress(GA, DAG);
2957 if (CP->isMachineConstantPoolEntry())
2958 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2959 CP->getAlignment());
2960 else
2961 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2962 CP->getAlignment());
2963 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2966 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2967 return MachineJumpTableInfo::EK_Inline;
2970 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2971 SelectionDAG &DAG) const {
2972 MachineFunction &MF = DAG.getMachineFunction();
2973 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2974 unsigned ARMPCLabelIndex = 0;
2975 SDLoc DL(Op);
2976 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2977 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2978 SDValue CPAddr;
2979 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2980 if (!IsPositionIndependent) {
2981 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2982 } else {
2983 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2984 ARMPCLabelIndex = AFI->createPICLabelUId();
2985 ARMConstantPoolValue *CPV =
2986 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2987 ARMCP::CPBlockAddress, PCAdj);
2988 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2990 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2991 SDValue Result = DAG.getLoad(
2992 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2993 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2994 if (!IsPositionIndependent)
2995 return Result;
2996 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2997 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3000 /// Convert a TLS address reference into the correct sequence of loads
3001 /// and calls to compute the variable's address for Darwin, and return an
3002 /// SDValue containing the final node.
3004 /// Darwin only has one TLS scheme which must be capable of dealing with the
3005 /// fully general situation, in the worst case. This means:
3006 /// + "extern __thread" declaration.
3007 /// + Defined in a possibly unknown dynamic library.
3009 /// The general system is that each __thread variable has a [3 x i32] descriptor
3010 /// which contains information used by the runtime to calculate the address. The
3011 /// only part of this the compiler needs to know about is the first word, which
3012 /// contains a function pointer that must be called with the address of the
3013 /// entire descriptor in "r0".
3015 /// Since this descriptor may be in a different unit, in general access must
3016 /// proceed along the usual ARM rules. A common sequence to produce is:
3018 /// movw rT1, :lower16:_var$non_lazy_ptr
3019 /// movt rT1, :upper16:_var$non_lazy_ptr
3020 /// ldr r0, [rT1]
3021 /// ldr rT2, [r0]
3022 /// blx rT2
3023 /// [...address now in r0...]
3024 SDValue
3025 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3026 SelectionDAG &DAG) const {
3027 assert(Subtarget->isTargetDarwin() &&
3028 "This function expects a Darwin target");
3029 SDLoc DL(Op);
3031 // First step is to get the address of the actua global symbol. This is where
3032 // the TLS descriptor lives.
3033 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3035 // The first entry in the descriptor is a function pointer that we must call
3036 // to obtain the address of the variable.
3037 SDValue Chain = DAG.getEntryNode();
3038 SDValue FuncTLVGet = DAG.getLoad(
3039 MVT::i32, DL, Chain, DescAddr,
3040 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3041 /* Alignment = */ 4,
3042 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3043 MachineMemOperand::MOInvariant);
3044 Chain = FuncTLVGet.getValue(1);
3046 MachineFunction &F = DAG.getMachineFunction();
3047 MachineFrameInfo &MFI = F.getFrameInfo();
3048 MFI.setAdjustsStack(true);
3050 // TLS calls preserve all registers except those that absolutely must be
3051 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3052 // silly).
3053 auto TRI =
3054 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3055 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3056 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3058 // Finally, we can make the call. This is just a degenerate version of a
3059 // normal AArch64 call node: r0 takes the address of the descriptor, and
3060 // returns the address of the variable in this thread.
3061 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3062 Chain =
3063 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3064 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3065 DAG.getRegisterMask(Mask), Chain.getValue(1));
3066 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3069 SDValue
3070 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3071 SelectionDAG &DAG) const {
3072 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3074 SDValue Chain = DAG.getEntryNode();
3075 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3076 SDLoc DL(Op);
3078 // Load the current TEB (thread environment block)
3079 SDValue Ops[] = {Chain,
3080 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3081 DAG.getConstant(15, DL, MVT::i32),
3082 DAG.getConstant(0, DL, MVT::i32),
3083 DAG.getConstant(13, DL, MVT::i32),
3084 DAG.getConstant(0, DL, MVT::i32),
3085 DAG.getConstant(2, DL, MVT::i32)};
3086 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3087 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3089 SDValue TEB = CurrentTEB.getValue(0);
3090 Chain = CurrentTEB.getValue(1);
3092 // Load the ThreadLocalStoragePointer from the TEB
3093 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3094 SDValue TLSArray =
3095 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3096 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3098 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3099 // offset into the TLSArray.
3101 // Load the TLS index from the C runtime
3102 SDValue TLSIndex =
3103 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3104 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3105 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3107 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3108 DAG.getConstant(2, DL, MVT::i32));
3109 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3110 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3111 MachinePointerInfo());
3113 // Get the offset of the start of the .tls section (section base)
3114 const auto *GA = cast<GlobalAddressSDNode>(Op);
3115 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3116 SDValue Offset = DAG.getLoad(
3117 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3118 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3119 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3121 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3124 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3125 SDValue
3126 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3127 SelectionDAG &DAG) const {
3128 SDLoc dl(GA);
3129 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3130 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3131 MachineFunction &MF = DAG.getMachineFunction();
3132 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3133 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3134 ARMConstantPoolValue *CPV =
3135 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3136 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3137 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3138 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3139 Argument = DAG.getLoad(
3140 PtrVT, dl, DAG.getEntryNode(), Argument,
3141 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3142 SDValue Chain = Argument.getValue(1);
3144 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3145 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3147 // call __tls_get_addr.
3148 ArgListTy Args;
3149 ArgListEntry Entry;
3150 Entry.Node = Argument;
3151 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3152 Args.push_back(Entry);
3154 // FIXME: is there useful debug info available here?
3155 TargetLowering::CallLoweringInfo CLI(DAG);
3156 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3157 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3158 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3160 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3161 return CallResult.first;
3164 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3165 // "local exec" model.
3166 SDValue
3167 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3168 SelectionDAG &DAG,
3169 TLSModel::Model model) const {
3170 const GlobalValue *GV = GA->getGlobal();
3171 SDLoc dl(GA);
3172 SDValue Offset;
3173 SDValue Chain = DAG.getEntryNode();
3174 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3175 // Get the Thread Pointer
3176 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3178 if (model == TLSModel::InitialExec) {
3179 MachineFunction &MF = DAG.getMachineFunction();
3180 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3181 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3182 // Initial exec model.
3183 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3184 ARMConstantPoolValue *CPV =
3185 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3186 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3187 true);
3188 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3189 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3190 Offset = DAG.getLoad(
3191 PtrVT, dl, Chain, Offset,
3192 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3193 Chain = Offset.getValue(1);
3195 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3196 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3198 Offset = DAG.getLoad(
3199 PtrVT, dl, Chain, Offset,
3200 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3201 } else {
3202 // local exec model
3203 assert(model == TLSModel::LocalExec);
3204 ARMConstantPoolValue *CPV =
3205 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3206 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3207 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3208 Offset = DAG.getLoad(
3209 PtrVT, dl, Chain, Offset,
3210 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3213 // The address of the thread local variable is the add of the thread
3214 // pointer with the offset of the variable.
3215 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3218 SDValue
3219 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3220 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3221 if (DAG.getTarget().useEmulatedTLS())
3222 return LowerToTLSEmulatedModel(GA, DAG);
3224 if (Subtarget->isTargetDarwin())
3225 return LowerGlobalTLSAddressDarwin(Op, DAG);
3227 if (Subtarget->isTargetWindows())
3228 return LowerGlobalTLSAddressWindows(Op, DAG);
3230 // TODO: implement the "local dynamic" model
3231 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3232 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3234 switch (model) {
3235 case TLSModel::GeneralDynamic:
3236 case TLSModel::LocalDynamic:
3237 return LowerToTLSGeneralDynamicModel(GA, DAG);
3238 case TLSModel::InitialExec:
3239 case TLSModel::LocalExec:
3240 return LowerToTLSExecModels(GA, DAG, model);
3242 llvm_unreachable("bogus TLS model");
3245 /// Return true if all users of V are within function F, looking through
3246 /// ConstantExprs.
3247 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3248 SmallVector<const User*,4> Worklist;
3249 for (auto *U : V->users())
3250 Worklist.push_back(U);
3251 while (!Worklist.empty()) {
3252 auto *U = Worklist.pop_back_val();
3253 if (isa<ConstantExpr>(U)) {
3254 for (auto *UU : U->users())
3255 Worklist.push_back(UU);
3256 continue;
3259 auto *I = dyn_cast<Instruction>(U);
3260 if (!I || I->getParent()->getParent() != F)
3261 return false;
3263 return true;
3266 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3267 const GlobalValue *GV, SelectionDAG &DAG,
3268 EVT PtrVT, const SDLoc &dl) {
3269 // If we're creating a pool entry for a constant global with unnamed address,
3270 // and the global is small enough, we can emit it inline into the constant pool
3271 // to save ourselves an indirection.
3273 // This is a win if the constant is only used in one function (so it doesn't
3274 // need to be duplicated) or duplicating the constant wouldn't increase code
3275 // size (implying the constant is no larger than 4 bytes).
3276 const Function &F = DAG.getMachineFunction().getFunction();
3278 // We rely on this decision to inline being idemopotent and unrelated to the
3279 // use-site. We know that if we inline a variable at one use site, we'll
3280 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3281 // doesn't know about this optimization, so bail out if it's enabled else
3282 // we could decide to inline here (and thus never emit the GV) but require
3283 // the GV from fast-isel generated code.
3284 if (!EnableConstpoolPromotion ||
3285 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3286 return SDValue();
3288 auto *GVar = dyn_cast<GlobalVariable>(GV);
3289 if (!GVar || !GVar->hasInitializer() ||
3290 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3291 !GVar->hasLocalLinkage())
3292 return SDValue();
3294 // If we inline a value that contains relocations, we move the relocations
3295 // from .data to .text. This is not allowed in position-independent code.
3296 auto *Init = GVar->getInitializer();
3297 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3298 Init->needsRelocation())
3299 return SDValue();
3301 // The constant islands pass can only really deal with alignment requests
3302 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3303 // any type wanting greater alignment requirements than 4 bytes. We also
3304 // can only promote constants that are multiples of 4 bytes in size or
3305 // are paddable to a multiple of 4. Currently we only try and pad constants
3306 // that are strings for simplicity.
3307 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3308 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3309 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3310 unsigned RequiredPadding = 4 - (Size % 4);
3311 bool PaddingPossible =
3312 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3313 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3314 Size == 0)
3315 return SDValue();
3317 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3318 MachineFunction &MF = DAG.getMachineFunction();
3319 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3321 // We can't bloat the constant pool too much, else the ConstantIslands pass
3322 // may fail to converge. If we haven't promoted this global yet (it may have
3323 // multiple uses), and promoting it would increase the constant pool size (Sz
3324 // > 4), ensure we have space to do so up to MaxTotal.
3325 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3326 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3327 ConstpoolPromotionMaxTotal)
3328 return SDValue();
3330 // This is only valid if all users are in a single function; we can't clone
3331 // the constant in general. The LLVM IR unnamed_addr allows merging
3332 // constants, but not cloning them.
3334 // We could potentially allow cloning if we could prove all uses of the
3335 // constant in the current function don't care about the address, like
3336 // printf format strings. But that isn't implemented for now.
3337 if (!allUsersAreInFunction(GVar, &F))
3338 return SDValue();
3340 // We're going to inline this global. Pad it out if needed.
3341 if (RequiredPadding != 4) {
3342 StringRef S = CDAInit->getAsString();
3344 SmallVector<uint8_t,16> V(S.size());
3345 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3346 while (RequiredPadding--)
3347 V.push_back(0);
3348 Init = ConstantDataArray::get(*DAG.getContext(), V);
3351 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3352 SDValue CPAddr =
3353 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3354 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3355 AFI->markGlobalAsPromotedToConstantPool(GVar);
3356 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3357 PaddedSize - 4);
3359 ++NumConstpoolPromoted;
3360 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3363 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3364 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3365 if (!(GV = GA->getBaseObject()))
3366 return false;
3367 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3368 return V->isConstant();
3369 return isa<Function>(GV);
3372 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3373 SelectionDAG &DAG) const {
3374 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3375 default: llvm_unreachable("unknown object format");
3376 case Triple::COFF:
3377 return LowerGlobalAddressWindows(Op, DAG);
3378 case Triple::ELF:
3379 return LowerGlobalAddressELF(Op, DAG);
3380 case Triple::MachO:
3381 return LowerGlobalAddressDarwin(Op, DAG);
3385 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3386 SelectionDAG &DAG) const {
3387 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3388 SDLoc dl(Op);
3389 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3390 const TargetMachine &TM = getTargetMachine();
3391 bool IsRO = isReadOnly(GV);
3393 // promoteToConstantPool only if not generating XO text section
3394 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3395 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3396 return V;
3398 if (isPositionIndependent()) {
3399 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3400 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3401 UseGOT_PREL ? ARMII::MO_GOT : 0);
3402 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3403 if (UseGOT_PREL)
3404 Result =
3405 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3406 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3407 return Result;
3408 } else if (Subtarget->isROPI() && IsRO) {
3409 // PC-relative.
3410 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3411 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3412 return Result;
3413 } else if (Subtarget->isRWPI() && !IsRO) {
3414 // SB-relative.
3415 SDValue RelAddr;
3416 if (Subtarget->useMovt()) {
3417 ++NumMovwMovt;
3418 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3419 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3420 } else { // use literal pool for address constant
3421 ARMConstantPoolValue *CPV =
3422 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3423 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3424 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3425 RelAddr = DAG.getLoad(
3426 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3427 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3429 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3430 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3431 return Result;
3434 // If we have T2 ops, we can materialize the address directly via movt/movw
3435 // pair. This is always cheaper.
3436 if (Subtarget->useMovt()) {
3437 ++NumMovwMovt;
3438 // FIXME: Once remat is capable of dealing with instructions with register
3439 // operands, expand this into two nodes.
3440 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3441 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3442 } else {
3443 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3444 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3445 return DAG.getLoad(
3446 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3447 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3451 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3452 SelectionDAG &DAG) const {
3453 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3454 "ROPI/RWPI not currently supported for Darwin");
3455 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3456 SDLoc dl(Op);
3457 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3459 if (Subtarget->useMovt())
3460 ++NumMovwMovt;
3462 // FIXME: Once remat is capable of dealing with instructions with register
3463 // operands, expand this into multiple nodes
3464 unsigned Wrapper =
3465 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3467 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3468 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3470 if (Subtarget->isGVIndirectSymbol(GV))
3471 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3472 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3473 return Result;
3476 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3477 SelectionDAG &DAG) const {
3478 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3479 assert(Subtarget->useMovt() &&
3480 "Windows on ARM expects to use movw/movt");
3481 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3482 "ROPI/RWPI not currently supported for Windows");
3484 const TargetMachine &TM = getTargetMachine();
3485 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3486 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3487 if (GV->hasDLLImportStorageClass())
3488 TargetFlags = ARMII::MO_DLLIMPORT;
3489 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3490 TargetFlags = ARMII::MO_COFFSTUB;
3491 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3492 SDValue Result;
3493 SDLoc DL(Op);
3495 ++NumMovwMovt;
3497 // FIXME: Once remat is capable of dealing with instructions with register
3498 // operands, expand this into two nodes.
3499 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3500 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3501 TargetFlags));
3502 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3503 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3504 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3505 return Result;
3508 SDValue
3509 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3510 SDLoc dl(Op);
3511 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3512 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3513 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3514 Op.getOperand(1), Val);
3517 SDValue
3518 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3519 SDLoc dl(Op);
3520 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3521 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3524 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3525 SelectionDAG &DAG) const {
3526 SDLoc dl(Op);
3527 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3528 Op.getOperand(0));
3531 SDValue
3532 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3533 const ARMSubtarget *Subtarget) const {
3534 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3535 SDLoc dl(Op);
3536 switch (IntNo) {
3537 default: return SDValue(); // Don't custom lower most intrinsics.
3538 case Intrinsic::thread_pointer: {
3539 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3540 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3542 case Intrinsic::eh_sjlj_lsda: {
3543 MachineFunction &MF = DAG.getMachineFunction();
3544 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3545 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3546 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3547 SDValue CPAddr;
3548 bool IsPositionIndependent = isPositionIndependent();
3549 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3550 ARMConstantPoolValue *CPV =
3551 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3552 ARMCP::CPLSDA, PCAdj);
3553 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3554 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3555 SDValue Result = DAG.getLoad(
3556 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3557 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3559 if (IsPositionIndependent) {
3560 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3561 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3563 return Result;
3565 case Intrinsic::arm_neon_vabs:
3566 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3567 Op.getOperand(1));
3568 case Intrinsic::arm_neon_vmulls:
3569 case Intrinsic::arm_neon_vmullu: {
3570 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3571 ? ARMISD::VMULLs : ARMISD::VMULLu;
3572 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3573 Op.getOperand(1), Op.getOperand(2));
3575 case Intrinsic::arm_neon_vminnm:
3576 case Intrinsic::arm_neon_vmaxnm: {
3577 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3578 ? ISD::FMINNUM : ISD::FMAXNUM;
3579 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3580 Op.getOperand(1), Op.getOperand(2));
3582 case Intrinsic::arm_neon_vminu:
3583 case Intrinsic::arm_neon_vmaxu: {
3584 if (Op.getValueType().isFloatingPoint())
3585 return SDValue();
3586 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3587 ? ISD::UMIN : ISD::UMAX;
3588 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3589 Op.getOperand(1), Op.getOperand(2));
3591 case Intrinsic::arm_neon_vmins:
3592 case Intrinsic::arm_neon_vmaxs: {
3593 // v{min,max}s is overloaded between signed integers and floats.
3594 if (!Op.getValueType().isFloatingPoint()) {
3595 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3596 ? ISD::SMIN : ISD::SMAX;
3597 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3598 Op.getOperand(1), Op.getOperand(2));
3600 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3601 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3602 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3603 Op.getOperand(1), Op.getOperand(2));
3605 case Intrinsic::arm_neon_vtbl1:
3606 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3607 Op.getOperand(1), Op.getOperand(2));
3608 case Intrinsic::arm_neon_vtbl2:
3609 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3610 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3614 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3615 const ARMSubtarget *Subtarget) {
3616 SDLoc dl(Op);
3617 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3618 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3619 if (SSID == SyncScope::SingleThread)
3620 return Op;
3622 if (!Subtarget->hasDataBarrier()) {
3623 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3624 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3625 // here.
3626 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3627 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3628 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3629 DAG.getConstant(0, dl, MVT::i32));
3632 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3633 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3634 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3635 if (Subtarget->isMClass()) {
3636 // Only a full system barrier exists in the M-class architectures.
3637 Domain = ARM_MB::SY;
3638 } else if (Subtarget->preferISHSTBarriers() &&
3639 Ord == AtomicOrdering::Release) {
3640 // Swift happens to implement ISHST barriers in a way that's compatible with
3641 // Release semantics but weaker than ISH so we'd be fools not to use
3642 // it. Beware: other processors probably don't!
3643 Domain = ARM_MB::ISHST;
3646 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3647 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3648 DAG.getConstant(Domain, dl, MVT::i32));
3651 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3652 const ARMSubtarget *Subtarget) {
3653 // ARM pre v5TE and Thumb1 does not have preload instructions.
3654 if (!(Subtarget->isThumb2() ||
3655 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3656 // Just preserve the chain.
3657 return Op.getOperand(0);
3659 SDLoc dl(Op);
3660 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3661 if (!isRead &&
3662 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3663 // ARMv7 with MP extension has PLDW.
3664 return Op.getOperand(0);
3666 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3667 if (Subtarget->isThumb()) {
3668 // Invert the bits.
3669 isRead = ~isRead & 1;
3670 isData = ~isData & 1;
3673 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3674 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3675 DAG.getConstant(isData, dl, MVT::i32));
3678 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3679 MachineFunction &MF = DAG.getMachineFunction();
3680 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3682 // vastart just stores the address of the VarArgsFrameIndex slot into the
3683 // memory location argument.
3684 SDLoc dl(Op);
3685 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3686 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3687 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3688 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3689 MachinePointerInfo(SV));
3692 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3693 CCValAssign &NextVA,
3694 SDValue &Root,
3695 SelectionDAG &DAG,
3696 const SDLoc &dl) const {
3697 MachineFunction &MF = DAG.getMachineFunction();
3698 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3700 const TargetRegisterClass *RC;
3701 if (AFI->isThumb1OnlyFunction())
3702 RC = &ARM::tGPRRegClass;
3703 else
3704 RC = &ARM::GPRRegClass;
3706 // Transform the arguments stored in physical registers into virtual ones.
3707 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3708 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3710 SDValue ArgValue2;
3711 if (NextVA.isMemLoc()) {
3712 MachineFrameInfo &MFI = MF.getFrameInfo();
3713 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3715 // Create load node to retrieve arguments from the stack.
3716 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3717 ArgValue2 = DAG.getLoad(
3718 MVT::i32, dl, Root, FIN,
3719 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3720 } else {
3721 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3722 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3724 if (!Subtarget->isLittle())
3725 std::swap (ArgValue, ArgValue2);
3726 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3729 // The remaining GPRs hold either the beginning of variable-argument
3730 // data, or the beginning of an aggregate passed by value (usually
3731 // byval). Either way, we allocate stack slots adjacent to the data
3732 // provided by our caller, and store the unallocated registers there.
3733 // If this is a variadic function, the va_list pointer will begin with
3734 // these values; otherwise, this reassembles a (byval) structure that
3735 // was split between registers and memory.
3736 // Return: The frame index registers were stored into.
3737 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3738 const SDLoc &dl, SDValue &Chain,
3739 const Value *OrigArg,
3740 unsigned InRegsParamRecordIdx,
3741 int ArgOffset, unsigned ArgSize) const {
3742 // Currently, two use-cases possible:
3743 // Case #1. Non-var-args function, and we meet first byval parameter.
3744 // Setup first unallocated register as first byval register;
3745 // eat all remained registers
3746 // (these two actions are performed by HandleByVal method).
3747 // Then, here, we initialize stack frame with
3748 // "store-reg" instructions.
3749 // Case #2. Var-args function, that doesn't contain byval parameters.
3750 // The same: eat all remained unallocated registers,
3751 // initialize stack frame.
3753 MachineFunction &MF = DAG.getMachineFunction();
3754 MachineFrameInfo &MFI = MF.getFrameInfo();
3755 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3756 unsigned RBegin, REnd;
3757 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3758 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3759 } else {
3760 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3761 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3762 REnd = ARM::R4;
3765 if (REnd != RBegin)
3766 ArgOffset = -4 * (ARM::R4 - RBegin);
3768 auto PtrVT = getPointerTy(DAG.getDataLayout());
3769 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3770 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3772 SmallVector<SDValue, 4> MemOps;
3773 const TargetRegisterClass *RC =
3774 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3776 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3777 unsigned VReg = MF.addLiveIn(Reg, RC);
3778 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3779 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3780 MachinePointerInfo(OrigArg, 4 * i));
3781 MemOps.push_back(Store);
3782 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3785 if (!MemOps.empty())
3786 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3787 return FrameIndex;
3790 // Setup stack frame, the va_list pointer will start from.
3791 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3792 const SDLoc &dl, SDValue &Chain,
3793 unsigned ArgOffset,
3794 unsigned TotalArgRegsSaveSize,
3795 bool ForceMutable) const {
3796 MachineFunction &MF = DAG.getMachineFunction();
3797 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3799 // Try to store any remaining integer argument regs
3800 // to their spots on the stack so that they may be loaded by dereferencing
3801 // the result of va_next.
3802 // If there is no regs to be stored, just point address after last
3803 // argument passed via stack.
3804 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3805 CCInfo.getInRegsParamsCount(),
3806 CCInfo.getNextStackOffset(),
3807 std::max(4U, TotalArgRegsSaveSize));
3808 AFI->setVarArgsFrameIndex(FrameIndex);
3811 SDValue ARMTargetLowering::LowerFormalArguments(
3812 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3813 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3814 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3815 MachineFunction &MF = DAG.getMachineFunction();
3816 MachineFrameInfo &MFI = MF.getFrameInfo();
3818 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3820 // Assign locations to all of the incoming arguments.
3821 SmallVector<CCValAssign, 16> ArgLocs;
3822 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3823 *DAG.getContext());
3824 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3826 SmallVector<SDValue, 16> ArgValues;
3827 SDValue ArgValue;
3828 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3829 unsigned CurArgIdx = 0;
3831 // Initially ArgRegsSaveSize is zero.
3832 // Then we increase this value each time we meet byval parameter.
3833 // We also increase this value in case of varargs function.
3834 AFI->setArgRegsSaveSize(0);
3836 // Calculate the amount of stack space that we need to allocate to store
3837 // byval and variadic arguments that are passed in registers.
3838 // We need to know this before we allocate the first byval or variadic
3839 // argument, as they will be allocated a stack slot below the CFA (Canonical
3840 // Frame Address, the stack pointer at entry to the function).
3841 unsigned ArgRegBegin = ARM::R4;
3842 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3843 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3844 break;
3846 CCValAssign &VA = ArgLocs[i];
3847 unsigned Index = VA.getValNo();
3848 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3849 if (!Flags.isByVal())
3850 continue;
3852 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3853 unsigned RBegin, REnd;
3854 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3855 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3857 CCInfo.nextInRegsParam();
3859 CCInfo.rewindByValRegsInfo();
3861 int lastInsIndex = -1;
3862 if (isVarArg && MFI.hasVAStart()) {
3863 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3864 if (RegIdx != array_lengthof(GPRArgRegs))
3865 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3868 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3869 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3870 auto PtrVT = getPointerTy(DAG.getDataLayout());
3872 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3873 CCValAssign &VA = ArgLocs[i];
3874 if (Ins[VA.getValNo()].isOrigArg()) {
3875 std::advance(CurOrigArg,
3876 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3877 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3879 // Arguments stored in registers.
3880 if (VA.isRegLoc()) {
3881 EVT RegVT = VA.getLocVT();
3883 if (VA.needsCustom()) {
3884 // f64 and vector types are split up into multiple registers or
3885 // combinations of registers and stack slots.
3886 if (VA.getLocVT() == MVT::v2f64) {
3887 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3888 Chain, DAG, dl);
3889 VA = ArgLocs[++i]; // skip ahead to next loc
3890 SDValue ArgValue2;
3891 if (VA.isMemLoc()) {
3892 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3893 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3894 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3895 MachinePointerInfo::getFixedStack(
3896 DAG.getMachineFunction(), FI));
3897 } else {
3898 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3899 Chain, DAG, dl);
3901 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3902 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3903 ArgValue, ArgValue1,
3904 DAG.getIntPtrConstant(0, dl));
3905 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3906 ArgValue, ArgValue2,
3907 DAG.getIntPtrConstant(1, dl));
3908 } else
3909 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3910 } else {
3911 const TargetRegisterClass *RC;
3914 if (RegVT == MVT::f16)
3915 RC = &ARM::HPRRegClass;
3916 else if (RegVT == MVT::f32)
3917 RC = &ARM::SPRRegClass;
3918 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3919 RC = &ARM::DPRRegClass;
3920 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3921 RC = &ARM::QPRRegClass;
3922 else if (RegVT == MVT::i32)
3923 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3924 : &ARM::GPRRegClass;
3925 else
3926 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3928 // Transform the arguments in physical registers into virtual ones.
3929 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3930 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3932 // If this value is passed in r0 and has the returned attribute (e.g.
3933 // C++ 'structors), record this fact for later use.
3934 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
3935 AFI->setPreservesR0();
3939 // If this is an 8 or 16-bit value, it is really passed promoted
3940 // to 32 bits. Insert an assert[sz]ext to capture this, then
3941 // truncate to the right size.
3942 switch (VA.getLocInfo()) {
3943 default: llvm_unreachable("Unknown loc info!");
3944 case CCValAssign::Full: break;
3945 case CCValAssign::BCvt:
3946 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3947 break;
3948 case CCValAssign::SExt:
3949 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3950 DAG.getValueType(VA.getValVT()));
3951 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3952 break;
3953 case CCValAssign::ZExt:
3954 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3955 DAG.getValueType(VA.getValVT()));
3956 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3957 break;
3960 InVals.push_back(ArgValue);
3961 } else { // VA.isRegLoc()
3962 // sanity check
3963 assert(VA.isMemLoc());
3964 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3966 int index = VA.getValNo();
3968 // Some Ins[] entries become multiple ArgLoc[] entries.
3969 // Process them only once.
3970 if (index != lastInsIndex)
3972 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3973 // FIXME: For now, all byval parameter objects are marked mutable.
3974 // This can be changed with more analysis.
3975 // In case of tail call optimization mark all arguments mutable.
3976 // Since they could be overwritten by lowering of arguments in case of
3977 // a tail call.
3978 if (Flags.isByVal()) {
3979 assert(Ins[index].isOrigArg() &&
3980 "Byval arguments cannot be implicit");
3981 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3983 int FrameIndex = StoreByValRegs(
3984 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3985 VA.getLocMemOffset(), Flags.getByValSize());
3986 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3987 CCInfo.nextInRegsParam();
3988 } else {
3989 unsigned FIOffset = VA.getLocMemOffset();
3990 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3991 FIOffset, true);
3993 // Create load nodes to retrieve arguments from the stack.
3994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3995 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3996 MachinePointerInfo::getFixedStack(
3997 DAG.getMachineFunction(), FI)));
3999 lastInsIndex = index;
4004 // varargs
4005 if (isVarArg && MFI.hasVAStart())
4006 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4007 CCInfo.getNextStackOffset(),
4008 TotalArgRegsSaveSize);
4010 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4012 return Chain;
4015 /// isFloatingPointZero - Return true if this is +0.0.
4016 static bool isFloatingPointZero(SDValue Op) {
4017 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4018 return CFP->getValueAPF().isPosZero();
4019 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4020 // Maybe this has already been legalized into the constant pool?
4021 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4022 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4023 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4024 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4025 return CFP->getValueAPF().isPosZero();
4027 } else if (Op->getOpcode() == ISD::BITCAST &&
4028 Op->getValueType(0) == MVT::f64) {
4029 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4030 // created by LowerConstantFP().
4031 SDValue BitcastOp = Op->getOperand(0);
4032 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4033 isNullConstant(BitcastOp->getOperand(0)))
4034 return true;
4036 return false;
4039 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4040 /// the given operands.
4041 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4042 SDValue &ARMcc, SelectionDAG &DAG,
4043 const SDLoc &dl) const {
4044 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4045 unsigned C = RHSC->getZExtValue();
4046 if (!isLegalICmpImmediate((int32_t)C)) {
4047 // Constant does not fit, try adjusting it by one.
4048 switch (CC) {
4049 default: break;
4050 case ISD::SETLT:
4051 case ISD::SETGE:
4052 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4053 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4054 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4056 break;
4057 case ISD::SETULT:
4058 case ISD::SETUGE:
4059 if (C != 0 && isLegalICmpImmediate(C-1)) {
4060 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4061 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4063 break;
4064 case ISD::SETLE:
4065 case ISD::SETGT:
4066 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4067 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4068 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4070 break;
4071 case ISD::SETULE:
4072 case ISD::SETUGT:
4073 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4074 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4075 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4077 break;
4080 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4081 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4082 // In ARM and Thumb-2, the compare instructions can shift their second
4083 // operand.
4084 CC = ISD::getSetCCSwappedOperands(CC);
4085 std::swap(LHS, RHS);
4088 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4090 // If the RHS is a constant zero then the V (overflow) flag will never be
4091 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4092 // simpler for other passes (like the peephole optimiser) to deal with.
4093 if (isNullConstant(RHS)) {
4094 switch (CondCode) {
4095 default: break;
4096 case ARMCC::GE:
4097 CondCode = ARMCC::PL;
4098 break;
4099 case ARMCC::LT:
4100 CondCode = ARMCC::MI;
4101 break;
4105 ARMISD::NodeType CompareType;
4106 switch (CondCode) {
4107 default:
4108 CompareType = ARMISD::CMP;
4109 break;
4110 case ARMCC::EQ:
4111 case ARMCC::NE:
4112 // Uses only Z Flag
4113 CompareType = ARMISD::CMPZ;
4114 break;
4116 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4117 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4120 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4121 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4122 SelectionDAG &DAG, const SDLoc &dl,
4123 bool InvalidOnQNaN) const {
4124 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4125 SDValue Cmp;
4126 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4127 if (!isFloatingPointZero(RHS))
4128 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4129 else
4130 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4131 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4134 /// duplicateCmp - Glue values can have only one use, so this function
4135 /// duplicates a comparison node.
4136 SDValue
4137 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4138 unsigned Opc = Cmp.getOpcode();
4139 SDLoc DL(Cmp);
4140 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4141 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4143 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4144 Cmp = Cmp.getOperand(0);
4145 Opc = Cmp.getOpcode();
4146 if (Opc == ARMISD::CMPFP)
4147 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4148 Cmp.getOperand(1), Cmp.getOperand(2));
4149 else {
4150 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4151 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4152 Cmp.getOperand(1));
4154 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4157 // This function returns three things: the arithmetic computation itself
4158 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4159 // comparison and the condition code define the case in which the arithmetic
4160 // computation *does not* overflow.
4161 std::pair<SDValue, SDValue>
4162 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4163 SDValue &ARMcc) const {
4164 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4166 SDValue Value, OverflowCmp;
4167 SDValue LHS = Op.getOperand(0);
4168 SDValue RHS = Op.getOperand(1);
4169 SDLoc dl(Op);
4171 // FIXME: We are currently always generating CMPs because we don't support
4172 // generating CMN through the backend. This is not as good as the natural
4173 // CMP case because it causes a register dependency and cannot be folded
4174 // later.
4176 switch (Op.getOpcode()) {
4177 default:
4178 llvm_unreachable("Unknown overflow instruction!");
4179 case ISD::SADDO:
4180 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4181 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4182 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4183 break;
4184 case ISD::UADDO:
4185 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4186 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4187 // We do not use it in the USUBO case as Value may not be used.
4188 Value = DAG.getNode(ARMISD::ADDC, dl,
4189 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4190 .getValue(0);
4191 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4192 break;
4193 case ISD::SSUBO:
4194 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4195 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4196 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4197 break;
4198 case ISD::USUBO:
4199 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4200 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4201 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4202 break;
4203 case ISD::UMULO:
4204 // We generate a UMUL_LOHI and then check if the high word is 0.
4205 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4206 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4207 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4208 LHS, RHS);
4209 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4210 DAG.getConstant(0, dl, MVT::i32));
4211 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4212 break;
4213 case ISD::SMULO:
4214 // We generate a SMUL_LOHI and then check if all the bits of the high word
4215 // are the same as the sign bit of the low word.
4216 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4217 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4218 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4219 LHS, RHS);
4220 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4221 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4222 Value.getValue(0),
4223 DAG.getConstant(31, dl, MVT::i32)));
4224 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4225 break;
4226 } // switch (...)
4228 return std::make_pair(Value, OverflowCmp);
4231 SDValue
4232 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4233 // Let legalize expand this if it isn't a legal type yet.
4234 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4235 return SDValue();
4237 SDValue Value, OverflowCmp;
4238 SDValue ARMcc;
4239 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4240 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4241 SDLoc dl(Op);
4242 // We use 0 and 1 as false and true values.
4243 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4244 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4245 EVT VT = Op.getValueType();
4247 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4248 ARMcc, CCR, OverflowCmp);
4250 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4251 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4254 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4255 SelectionDAG &DAG) {
4256 SDLoc DL(BoolCarry);
4257 EVT CarryVT = BoolCarry.getValueType();
4259 // This converts the boolean value carry into the carry flag by doing
4260 // ARMISD::SUBC Carry, 1
4261 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4262 DAG.getVTList(CarryVT, MVT::i32),
4263 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4264 return Carry.getValue(1);
4267 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4268 SelectionDAG &DAG) {
4269 SDLoc DL(Flags);
4271 // Now convert the carry flag into a boolean carry. We do this
4272 // using ARMISD:ADDE 0, 0, Carry
4273 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4274 DAG.getConstant(0, DL, MVT::i32),
4275 DAG.getConstant(0, DL, MVT::i32), Flags);
4278 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4279 SelectionDAG &DAG) const {
4280 // Let legalize expand this if it isn't a legal type yet.
4281 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4282 return SDValue();
4284 SDValue LHS = Op.getOperand(0);
4285 SDValue RHS = Op.getOperand(1);
4286 SDLoc dl(Op);
4288 EVT VT = Op.getValueType();
4289 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4290 SDValue Value;
4291 SDValue Overflow;
4292 switch (Op.getOpcode()) {
4293 default:
4294 llvm_unreachable("Unknown overflow instruction!");
4295 case ISD::UADDO:
4296 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4297 // Convert the carry flag into a boolean value.
4298 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4299 break;
4300 case ISD::USUBO: {
4301 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4302 // Convert the carry flag into a boolean value.
4303 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4304 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4305 // value. So compute 1 - C.
4306 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4307 DAG.getConstant(1, dl, MVT::i32), Overflow);
4308 break;
4312 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4315 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4316 SDValue Cond = Op.getOperand(0);
4317 SDValue SelectTrue = Op.getOperand(1);
4318 SDValue SelectFalse = Op.getOperand(2);
4319 SDLoc dl(Op);
4320 unsigned Opc = Cond.getOpcode();
4322 if (Cond.getResNo() == 1 &&
4323 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4324 Opc == ISD::USUBO)) {
4325 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4326 return SDValue();
4328 SDValue Value, OverflowCmp;
4329 SDValue ARMcc;
4330 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4331 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4332 EVT VT = Op.getValueType();
4334 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4335 OverflowCmp, DAG);
4338 // Convert:
4340 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4341 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4343 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4344 const ConstantSDNode *CMOVTrue =
4345 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4346 const ConstantSDNode *CMOVFalse =
4347 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4349 if (CMOVTrue && CMOVFalse) {
4350 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4351 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4353 SDValue True;
4354 SDValue False;
4355 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4356 True = SelectTrue;
4357 False = SelectFalse;
4358 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4359 True = SelectFalse;
4360 False = SelectTrue;
4363 if (True.getNode() && False.getNode()) {
4364 EVT VT = Op.getValueType();
4365 SDValue ARMcc = Cond.getOperand(2);
4366 SDValue CCR = Cond.getOperand(3);
4367 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4368 assert(True.getValueType() == VT);
4369 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4374 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4375 // undefined bits before doing a full-word comparison with zero.
4376 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4377 DAG.getConstant(1, dl, Cond.getValueType()));
4379 return DAG.getSelectCC(dl, Cond,
4380 DAG.getConstant(0, dl, Cond.getValueType()),
4381 SelectTrue, SelectFalse, ISD::SETNE);
4384 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4385 bool &swpCmpOps, bool &swpVselOps) {
4386 // Start by selecting the GE condition code for opcodes that return true for
4387 // 'equality'
4388 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4389 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4390 CondCode = ARMCC::GE;
4392 // and GT for opcodes that return false for 'equality'.
4393 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4394 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4395 CondCode = ARMCC::GT;
4397 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4398 // to swap the compare operands.
4399 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4400 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4401 swpCmpOps = true;
4403 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4404 // If we have an unordered opcode, we need to swap the operands to the VSEL
4405 // instruction (effectively negating the condition).
4407 // This also has the effect of swapping which one of 'less' or 'greater'
4408 // returns true, so we also swap the compare operands. It also switches
4409 // whether we return true for 'equality', so we compensate by picking the
4410 // opposite condition code to our original choice.
4411 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4412 CC == ISD::SETUGT) {
4413 swpCmpOps = !swpCmpOps;
4414 swpVselOps = !swpVselOps;
4415 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4418 // 'ordered' is 'anything but unordered', so use the VS condition code and
4419 // swap the VSEL operands.
4420 if (CC == ISD::SETO) {
4421 CondCode = ARMCC::VS;
4422 swpVselOps = true;
4425 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4426 // code and swap the VSEL operands. Also do this if we don't care about the
4427 // unordered case.
4428 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4429 CondCode = ARMCC::EQ;
4430 swpVselOps = true;
4434 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4435 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4436 SDValue Cmp, SelectionDAG &DAG) const {
4437 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4438 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4439 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4440 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4441 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4443 SDValue TrueLow = TrueVal.getValue(0);
4444 SDValue TrueHigh = TrueVal.getValue(1);
4445 SDValue FalseLow = FalseVal.getValue(0);
4446 SDValue FalseHigh = FalseVal.getValue(1);
4448 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4449 ARMcc, CCR, Cmp);
4450 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4451 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4453 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4454 } else {
4455 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4456 Cmp);
4460 static bool isGTorGE(ISD::CondCode CC) {
4461 return CC == ISD::SETGT || CC == ISD::SETGE;
4464 static bool isLTorLE(ISD::CondCode CC) {
4465 return CC == ISD::SETLT || CC == ISD::SETLE;
4468 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4469 // All of these conditions (and their <= and >= counterparts) will do:
4470 // x < k ? k : x
4471 // x > k ? x : k
4472 // k < x ? x : k
4473 // k > x ? k : x
4474 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4475 const SDValue TrueVal, const SDValue FalseVal,
4476 const ISD::CondCode CC, const SDValue K) {
4477 return (isGTorGE(CC) &&
4478 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4479 (isLTorLE(CC) &&
4480 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4483 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4484 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4485 const SDValue TrueVal, const SDValue FalseVal,
4486 const ISD::CondCode CC, const SDValue K) {
4487 return (isGTorGE(CC) &&
4488 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4489 (isLTorLE(CC) &&
4490 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4493 // Check if two chained conditionals could be converted into SSAT or USAT.
4495 // SSAT can replace a set of two conditional selectors that bound a number to an
4496 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4498 // x < -k ? -k : (x > k ? k : x)
4499 // x < -k ? -k : (x < k ? x : k)
4500 // x > -k ? (x > k ? k : x) : -k
4501 // x < k ? (x < -k ? -k : x) : k
4502 // etc.
4504 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4505 // a power of 2.
4507 // It returns true if the conversion can be done, false otherwise.
4508 // Additionally, the variable is returned in parameter V, the constant in K and
4509 // usat is set to true if the conditional represents an unsigned saturation
4510 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4511 uint64_t &K, bool &usat) {
4512 SDValue LHS1 = Op.getOperand(0);
4513 SDValue RHS1 = Op.getOperand(1);
4514 SDValue TrueVal1 = Op.getOperand(2);
4515 SDValue FalseVal1 = Op.getOperand(3);
4516 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4518 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4519 if (Op2.getOpcode() != ISD::SELECT_CC)
4520 return false;
4522 SDValue LHS2 = Op2.getOperand(0);
4523 SDValue RHS2 = Op2.getOperand(1);
4524 SDValue TrueVal2 = Op2.getOperand(2);
4525 SDValue FalseVal2 = Op2.getOperand(3);
4526 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4528 // Find out which are the constants and which are the variables
4529 // in each conditional
4530 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4531 ? &RHS1
4532 : nullptr;
4533 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4534 ? &RHS2
4535 : nullptr;
4536 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4537 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4538 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4539 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4541 // We must detect cases where the original operations worked with 16- or
4542 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4543 // must work with sign-extended values but the select operations return
4544 // the original non-extended value.
4545 SDValue V2TmpReg = V2Tmp;
4546 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4547 V2TmpReg = V2Tmp->getOperand(0);
4549 // Check that the registers and the constants have the correct values
4550 // in both conditionals
4551 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4552 V2TmpReg != V2)
4553 return false;
4555 // Figure out which conditional is saturating the lower/upper bound.
4556 const SDValue *LowerCheckOp =
4557 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4558 ? &Op
4559 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4560 ? &Op2
4561 : nullptr;
4562 const SDValue *UpperCheckOp =
4563 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4564 ? &Op
4565 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4566 ? &Op2
4567 : nullptr;
4569 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4570 return false;
4572 // Check that the constant in the lower-bound check is
4573 // the opposite of the constant in the upper-bound check
4574 // in 1's complement.
4575 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4576 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4577 int64_t PosVal = std::max(Val1, Val2);
4578 int64_t NegVal = std::min(Val1, Val2);
4580 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4581 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4582 isPowerOf2_64(PosVal + 1)) {
4584 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4585 if (Val1 == ~Val2)
4586 usat = false;
4587 else if (NegVal == 0)
4588 usat = true;
4589 else
4590 return false;
4592 V = V2;
4593 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4595 return true;
4598 return false;
4601 // Check if a condition of the type x < k ? k : x can be converted into a
4602 // bit operation instead of conditional moves.
4603 // Currently this is allowed given:
4604 // - The conditions and values match up
4605 // - k is 0 or -1 (all ones)
4606 // This function will not check the last condition, thats up to the caller
4607 // It returns true if the transformation can be made, and in such case
4608 // returns x in V, and k in SatK.
4609 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4610 SDValue &SatK)
4612 SDValue LHS = Op.getOperand(0);
4613 SDValue RHS = Op.getOperand(1);
4614 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4615 SDValue TrueVal = Op.getOperand(2);
4616 SDValue FalseVal = Op.getOperand(3);
4618 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4619 ? &RHS
4620 : nullptr;
4622 // No constant operation in comparison, early out
4623 if (!K)
4624 return false;
4626 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4627 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4628 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4630 // If the constant on left and right side, or variable on left and right,
4631 // does not match, early out
4632 if (*K != KTmp || V != VTmp)
4633 return false;
4635 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4636 SatK = *K;
4637 return true;
4640 return false;
4643 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4644 if (VT == MVT::f32)
4645 return !Subtarget->hasVFP2Base();
4646 if (VT == MVT::f64)
4647 return !Subtarget->hasFP64();
4648 if (VT == MVT::f16)
4649 return !Subtarget->hasFullFP16();
4650 return false;
4653 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4654 EVT VT = Op.getValueType();
4655 SDLoc dl(Op);
4657 // Try to convert two saturating conditional selects into a single SSAT
4658 SDValue SatValue;
4659 uint64_t SatConstant;
4660 bool SatUSat;
4661 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4662 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4663 if (SatUSat)
4664 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4665 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4666 else
4667 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4668 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4671 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4672 // into more efficient bit operations, which is possible when k is 0 or -1
4673 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4674 // single instructions. On Thumb the shift and the bit operation will be two
4675 // instructions.
4676 // Only allow this transformation on full-width (32-bit) operations
4677 SDValue LowerSatConstant;
4678 if (VT == MVT::i32 &&
4679 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4680 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4681 DAG.getConstant(31, dl, VT));
4682 if (isNullConstant(LowerSatConstant)) {
4683 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4684 DAG.getAllOnesConstant(dl, VT));
4685 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4686 } else if (isAllOnesConstant(LowerSatConstant))
4687 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4690 SDValue LHS = Op.getOperand(0);
4691 SDValue RHS = Op.getOperand(1);
4692 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4693 SDValue TrueVal = Op.getOperand(2);
4694 SDValue FalseVal = Op.getOperand(3);
4696 if (isUnsupportedFloatingType(LHS.getValueType())) {
4697 DAG.getTargetLoweringInfo().softenSetCCOperands(
4698 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4700 // If softenSetCCOperands only returned one value, we should compare it to
4701 // zero.
4702 if (!RHS.getNode()) {
4703 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4704 CC = ISD::SETNE;
4708 if (LHS.getValueType() == MVT::i32) {
4709 // Try to generate VSEL on ARMv8.
4710 // The VSEL instruction can't use all the usual ARM condition
4711 // codes: it only has two bits to select the condition code, so it's
4712 // constrained to use only GE, GT, VS and EQ.
4714 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4715 // swap the operands of the previous compare instruction (effectively
4716 // inverting the compare condition, swapping 'less' and 'greater') and
4717 // sometimes need to swap the operands to the VSEL (which inverts the
4718 // condition in the sense of firing whenever the previous condition didn't)
4719 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4720 TrueVal.getValueType() == MVT::f32 ||
4721 TrueVal.getValueType() == MVT::f64)) {
4722 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4723 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4724 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4725 CC = ISD::getSetCCInverse(CC, true);
4726 std::swap(TrueVal, FalseVal);
4730 SDValue ARMcc;
4731 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4732 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4733 // Choose GE over PL, which vsel does now support
4734 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4735 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4736 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4739 ARMCC::CondCodes CondCode, CondCode2;
4740 bool InvalidOnQNaN;
4741 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4743 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4744 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4745 // must use VSEL (limited condition codes), due to not having conditional f16
4746 // moves.
4747 if (Subtarget->hasFPARMv8Base() &&
4748 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4749 (TrueVal.getValueType() == MVT::f16 ||
4750 TrueVal.getValueType() == MVT::f32 ||
4751 TrueVal.getValueType() == MVT::f64)) {
4752 bool swpCmpOps = false;
4753 bool swpVselOps = false;
4754 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4756 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4757 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4758 if (swpCmpOps)
4759 std::swap(LHS, RHS);
4760 if (swpVselOps)
4761 std::swap(TrueVal, FalseVal);
4765 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4766 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4767 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4768 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4769 if (CondCode2 != ARMCC::AL) {
4770 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4771 // FIXME: Needs another CMP because flag can have but one use.
4772 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4773 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4775 return Result;
4778 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4779 /// to morph to an integer compare sequence.
4780 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4781 const ARMSubtarget *Subtarget) {
4782 SDNode *N = Op.getNode();
4783 if (!N->hasOneUse())
4784 // Otherwise it requires moving the value from fp to integer registers.
4785 return false;
4786 if (!N->getNumValues())
4787 return false;
4788 EVT VT = Op.getValueType();
4789 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4790 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4791 // vmrs are very slow, e.g. cortex-a8.
4792 return false;
4794 if (isFloatingPointZero(Op)) {
4795 SeenZero = true;
4796 return true;
4798 return ISD::isNormalLoad(N);
4801 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4802 if (isFloatingPointZero(Op))
4803 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4805 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4806 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4807 Ld->getPointerInfo(), Ld->getAlignment(),
4808 Ld->getMemOperand()->getFlags());
4810 llvm_unreachable("Unknown VFP cmp argument!");
4813 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4814 SDValue &RetVal1, SDValue &RetVal2) {
4815 SDLoc dl(Op);
4817 if (isFloatingPointZero(Op)) {
4818 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4819 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4820 return;
4823 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4824 SDValue Ptr = Ld->getBasePtr();
4825 RetVal1 =
4826 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4827 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4829 EVT PtrType = Ptr.getValueType();
4830 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4831 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4832 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4833 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4834 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4835 Ld->getMemOperand()->getFlags());
4836 return;
4839 llvm_unreachable("Unknown VFP cmp argument!");
4842 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4843 /// f32 and even f64 comparisons to integer ones.
4844 SDValue
4845 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4846 SDValue Chain = Op.getOperand(0);
4847 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4848 SDValue LHS = Op.getOperand(2);
4849 SDValue RHS = Op.getOperand(3);
4850 SDValue Dest = Op.getOperand(4);
4851 SDLoc dl(Op);
4853 bool LHSSeenZero = false;
4854 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4855 bool RHSSeenZero = false;
4856 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4857 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4858 // If unsafe fp math optimization is enabled and there are no other uses of
4859 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4860 // to an integer comparison.
4861 if (CC == ISD::SETOEQ)
4862 CC = ISD::SETEQ;
4863 else if (CC == ISD::SETUNE)
4864 CC = ISD::SETNE;
4866 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4867 SDValue ARMcc;
4868 if (LHS.getValueType() == MVT::f32) {
4869 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4870 bitcastf32Toi32(LHS, DAG), Mask);
4871 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4872 bitcastf32Toi32(RHS, DAG), Mask);
4873 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4874 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4875 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4876 Chain, Dest, ARMcc, CCR, Cmp);
4879 SDValue LHS1, LHS2;
4880 SDValue RHS1, RHS2;
4881 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4882 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4883 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4884 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4885 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4886 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4887 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4888 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4889 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4892 return SDValue();
4895 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4896 SDValue Chain = Op.getOperand(0);
4897 SDValue Cond = Op.getOperand(1);
4898 SDValue Dest = Op.getOperand(2);
4899 SDLoc dl(Op);
4901 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4902 // instruction.
4903 unsigned Opc = Cond.getOpcode();
4904 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4905 !Subtarget->isThumb1Only();
4906 if (Cond.getResNo() == 1 &&
4907 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4908 Opc == ISD::USUBO || OptimizeMul)) {
4909 // Only lower legal XALUO ops.
4910 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4911 return SDValue();
4913 // The actual operation with overflow check.
4914 SDValue Value, OverflowCmp;
4915 SDValue ARMcc;
4916 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4918 // Reverse the condition code.
4919 ARMCC::CondCodes CondCode =
4920 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4921 CondCode = ARMCC::getOppositeCondition(CondCode);
4922 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4923 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4925 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4926 OverflowCmp);
4929 return SDValue();
4932 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4933 SDValue Chain = Op.getOperand(0);
4934 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4935 SDValue LHS = Op.getOperand(2);
4936 SDValue RHS = Op.getOperand(3);
4937 SDValue Dest = Op.getOperand(4);
4938 SDLoc dl(Op);
4940 if (isUnsupportedFloatingType(LHS.getValueType())) {
4941 DAG.getTargetLoweringInfo().softenSetCCOperands(
4942 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4944 // If softenSetCCOperands only returned one value, we should compare it to
4945 // zero.
4946 if (!RHS.getNode()) {
4947 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4948 CC = ISD::SETNE;
4952 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4953 // instruction.
4954 unsigned Opc = LHS.getOpcode();
4955 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4956 !Subtarget->isThumb1Only();
4957 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4958 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4959 Opc == ISD::USUBO || OptimizeMul) &&
4960 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4961 // Only lower legal XALUO ops.
4962 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4963 return SDValue();
4965 // The actual operation with overflow check.
4966 SDValue Value, OverflowCmp;
4967 SDValue ARMcc;
4968 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4970 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4971 // Reverse the condition code.
4972 ARMCC::CondCodes CondCode =
4973 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4974 CondCode = ARMCC::getOppositeCondition(CondCode);
4975 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4977 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4979 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4980 OverflowCmp);
4983 if (LHS.getValueType() == MVT::i32) {
4984 SDValue ARMcc;
4985 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4986 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4987 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4988 Chain, Dest, ARMcc, CCR, Cmp);
4991 if (getTargetMachine().Options.UnsafeFPMath &&
4992 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4993 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4994 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4995 return Result;
4998 ARMCC::CondCodes CondCode, CondCode2;
4999 bool InvalidOnQNaN;
5000 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5002 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5003 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5004 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5005 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5006 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5007 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5008 if (CondCode2 != ARMCC::AL) {
5009 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5010 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5011 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5013 return Res;
5016 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5017 SDValue Chain = Op.getOperand(0);
5018 SDValue Table = Op.getOperand(1);
5019 SDValue Index = Op.getOperand(2);
5020 SDLoc dl(Op);
5022 EVT PTy = getPointerTy(DAG.getDataLayout());
5023 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5024 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5025 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5026 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5027 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5028 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5029 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5030 // which does another jump to the destination. This also makes it easier
5031 // to translate it to TBB / TBH later (Thumb2 only).
5032 // FIXME: This might not work if the function is extremely large.
5033 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5034 Addr, Op.getOperand(2), JTI);
5036 if (isPositionIndependent() || Subtarget->isROPI()) {
5037 Addr =
5038 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5039 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5040 Chain = Addr.getValue(1);
5041 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5042 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5043 } else {
5044 Addr =
5045 DAG.getLoad(PTy, dl, Chain, Addr,
5046 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5047 Chain = Addr.getValue(1);
5048 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5052 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5053 EVT VT = Op.getValueType();
5054 SDLoc dl(Op);
5056 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5057 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5058 return Op;
5059 return DAG.UnrollVectorOp(Op.getNode());
5062 const bool HasFullFP16 =
5063 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5065 EVT NewTy;
5066 const EVT OpTy = Op.getOperand(0).getValueType();
5067 if (OpTy == MVT::v4f32)
5068 NewTy = MVT::v4i32;
5069 else if (OpTy == MVT::v4f16 && HasFullFP16)
5070 NewTy = MVT::v4i16;
5071 else if (OpTy == MVT::v8f16 && HasFullFP16)
5072 NewTy = MVT::v8i16;
5073 else
5074 llvm_unreachable("Invalid type for custom lowering!");
5076 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5077 return DAG.UnrollVectorOp(Op.getNode());
5079 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5080 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5083 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5084 EVT VT = Op.getValueType();
5085 if (VT.isVector())
5086 return LowerVectorFP_TO_INT(Op, DAG);
5087 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5088 RTLIB::Libcall LC;
5089 if (Op.getOpcode() == ISD::FP_TO_SINT)
5090 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5091 Op.getValueType());
5092 else
5093 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5094 Op.getValueType());
5095 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5096 /*isSigned*/ false, SDLoc(Op)).first;
5099 return Op;
5102 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5103 EVT VT = Op.getValueType();
5104 SDLoc dl(Op);
5106 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5107 if (VT.getVectorElementType() == MVT::f32)
5108 return Op;
5109 return DAG.UnrollVectorOp(Op.getNode());
5112 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5113 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5114 "Invalid type for custom lowering!");
5116 const bool HasFullFP16 =
5117 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5119 EVT DestVecType;
5120 if (VT == MVT::v4f32)
5121 DestVecType = MVT::v4i32;
5122 else if (VT == MVT::v4f16 && HasFullFP16)
5123 DestVecType = MVT::v4i16;
5124 else if (VT == MVT::v8f16 && HasFullFP16)
5125 DestVecType = MVT::v8i16;
5126 else
5127 return DAG.UnrollVectorOp(Op.getNode());
5129 unsigned CastOpc;
5130 unsigned Opc;
5131 switch (Op.getOpcode()) {
5132 default: llvm_unreachable("Invalid opcode!");
5133 case ISD::SINT_TO_FP:
5134 CastOpc = ISD::SIGN_EXTEND;
5135 Opc = ISD::SINT_TO_FP;
5136 break;
5137 case ISD::UINT_TO_FP:
5138 CastOpc = ISD::ZERO_EXTEND;
5139 Opc = ISD::UINT_TO_FP;
5140 break;
5143 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5144 return DAG.getNode(Opc, dl, VT, Op);
5147 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5148 EVT VT = Op.getValueType();
5149 if (VT.isVector())
5150 return LowerVectorINT_TO_FP(Op, DAG);
5151 if (isUnsupportedFloatingType(VT)) {
5152 RTLIB::Libcall LC;
5153 if (Op.getOpcode() == ISD::SINT_TO_FP)
5154 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5155 Op.getValueType());
5156 else
5157 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5158 Op.getValueType());
5159 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5160 /*isSigned*/ false, SDLoc(Op)).first;
5163 return Op;
5166 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5167 // Implement fcopysign with a fabs and a conditional fneg.
5168 SDValue Tmp0 = Op.getOperand(0);
5169 SDValue Tmp1 = Op.getOperand(1);
5170 SDLoc dl(Op);
5171 EVT VT = Op.getValueType();
5172 EVT SrcVT = Tmp1.getValueType();
5173 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5174 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5175 bool UseNEON = !InGPR && Subtarget->hasNEON();
5177 if (UseNEON) {
5178 // Use VBSL to copy the sign bit.
5179 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5180 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5181 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5182 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5183 if (VT == MVT::f64)
5184 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5185 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5186 DAG.getConstant(32, dl, MVT::i32));
5187 else /*if (VT == MVT::f32)*/
5188 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5189 if (SrcVT == MVT::f32) {
5190 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5191 if (VT == MVT::f64)
5192 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5193 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5194 DAG.getConstant(32, dl, MVT::i32));
5195 } else if (VT == MVT::f32)
5196 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5197 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5198 DAG.getConstant(32, dl, MVT::i32));
5199 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5200 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5202 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5203 dl, MVT::i32);
5204 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5205 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5206 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5208 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5209 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5210 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5211 if (VT == MVT::f32) {
5212 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5213 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5214 DAG.getConstant(0, dl, MVT::i32));
5215 } else {
5216 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5219 return Res;
5222 // Bitcast operand 1 to i32.
5223 if (SrcVT == MVT::f64)
5224 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5225 Tmp1).getValue(1);
5226 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5228 // Or in the signbit with integer operations.
5229 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5230 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5231 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5232 if (VT == MVT::f32) {
5233 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5234 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5235 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5236 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5239 // f64: Or the high part with signbit and then combine two parts.
5240 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5241 Tmp0);
5242 SDValue Lo = Tmp0.getValue(0);
5243 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5244 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5245 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5248 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5249 MachineFunction &MF = DAG.getMachineFunction();
5250 MachineFrameInfo &MFI = MF.getFrameInfo();
5251 MFI.setReturnAddressIsTaken(true);
5253 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5254 return SDValue();
5256 EVT VT = Op.getValueType();
5257 SDLoc dl(Op);
5258 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5259 if (Depth) {
5260 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5261 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5262 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5263 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5264 MachinePointerInfo());
5267 // Return LR, which contains the return address. Mark it an implicit live-in.
5268 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5269 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5272 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5273 const ARMBaseRegisterInfo &ARI =
5274 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5275 MachineFunction &MF = DAG.getMachineFunction();
5276 MachineFrameInfo &MFI = MF.getFrameInfo();
5277 MFI.setFrameAddressIsTaken(true);
5279 EVT VT = Op.getValueType();
5280 SDLoc dl(Op); // FIXME probably not meaningful
5281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5282 unsigned FrameReg = ARI.getFrameRegister(MF);
5283 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5284 while (Depth--)
5285 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5286 MachinePointerInfo());
5287 return FrameAddr;
5290 // FIXME? Maybe this could be a TableGen attribute on some registers and
5291 // this table could be generated automatically from RegInfo.
5292 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5293 SelectionDAG &DAG) const {
5294 unsigned Reg = StringSwitch<unsigned>(RegName)
5295 .Case("sp", ARM::SP)
5296 .Default(0);
5297 if (Reg)
5298 return Reg;
5299 report_fatal_error(Twine("Invalid register name \""
5300 + StringRef(RegName) + "\"."));
5303 // Result is 64 bit value so split into two 32 bit values and return as a
5304 // pair of values.
5305 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5306 SelectionDAG &DAG) {
5307 SDLoc DL(N);
5309 // This function is only supposed to be called for i64 type destination.
5310 assert(N->getValueType(0) == MVT::i64
5311 && "ExpandREAD_REGISTER called for non-i64 type result.");
5313 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5314 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5315 N->getOperand(0),
5316 N->getOperand(1));
5318 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5319 Read.getValue(1)));
5320 Results.push_back(Read.getOperand(0));
5323 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5324 /// When \p DstVT, the destination type of \p BC, is on the vector
5325 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5326 /// it might be possible to combine them, such that everything stays on the
5327 /// vector register bank.
5328 /// \p return The node that would replace \p BT, if the combine
5329 /// is possible.
5330 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5331 SelectionDAG &DAG) {
5332 SDValue Op = BC->getOperand(0);
5333 EVT DstVT = BC->getValueType(0);
5335 // The only vector instruction that can produce a scalar (remember,
5336 // since the bitcast was about to be turned into VMOVDRR, the source
5337 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5338 // Moreover, we can do this combine only if there is one use.
5339 // Finally, if the destination type is not a vector, there is not
5340 // much point on forcing everything on the vector bank.
5341 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5342 !Op.hasOneUse())
5343 return SDValue();
5345 // If the index is not constant, we will introduce an additional
5346 // multiply that will stick.
5347 // Give up in that case.
5348 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5349 if (!Index)
5350 return SDValue();
5351 unsigned DstNumElt = DstVT.getVectorNumElements();
5353 // Compute the new index.
5354 const APInt &APIntIndex = Index->getAPIntValue();
5355 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5356 NewIndex *= APIntIndex;
5357 // Check if the new constant index fits into i32.
5358 if (NewIndex.getBitWidth() > 32)
5359 return SDValue();
5361 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5362 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5363 SDLoc dl(Op);
5364 SDValue ExtractSrc = Op.getOperand(0);
5365 EVT VecVT = EVT::getVectorVT(
5366 *DAG.getContext(), DstVT.getScalarType(),
5367 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5368 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5369 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5370 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5373 /// ExpandBITCAST - If the target supports VFP, this function is called to
5374 /// expand a bit convert where either the source or destination type is i64 to
5375 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5376 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5377 /// vectors), since the legalizer won't know what to do with that.
5378 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5379 const ARMSubtarget *Subtarget) {
5380 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5381 SDLoc dl(N);
5382 SDValue Op = N->getOperand(0);
5384 // This function is only supposed to be called for i64 types, either as the
5385 // source or destination of the bit convert.
5386 EVT SrcVT = Op.getValueType();
5387 EVT DstVT = N->getValueType(0);
5388 const bool HasFullFP16 = Subtarget->hasFullFP16();
5390 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5391 // FullFP16: half values are passed in S-registers, and we don't
5392 // need any of the bitcast and moves:
5394 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5395 // t5: i32 = bitcast t2
5396 // t18: f16 = ARMISD::VMOVhr t5
5397 if (Op.getOpcode() != ISD::CopyFromReg ||
5398 Op.getValueType() != MVT::f32)
5399 return SDValue();
5401 auto Move = N->use_begin();
5402 if (Move->getOpcode() != ARMISD::VMOVhr)
5403 return SDValue();
5405 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5406 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5407 DAG.ReplaceAllUsesWith(*Move, &Copy);
5408 return Copy;
5411 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5412 if (!HasFullFP16)
5413 return SDValue();
5414 // SoftFP: read half-precision arguments:
5416 // t2: i32,ch = ...
5417 // t7: i16 = truncate t2 <~~~~ Op
5418 // t8: f16 = bitcast t7 <~~~~ N
5420 if (Op.getOperand(0).getValueType() == MVT::i32)
5421 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5422 MVT::f16, Op.getOperand(0));
5424 return SDValue();
5427 // Half-precision return values
5428 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5429 if (!HasFullFP16)
5430 return SDValue();
5432 // t11: f16 = fadd t8, t10
5433 // t12: i16 = bitcast t11 <~~~ SDNode N
5434 // t13: i32 = zero_extend t12
5435 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5436 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5438 // transform this into:
5440 // t20: i32 = ARMISD::VMOVrh t11
5441 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5443 auto ZeroExtend = N->use_begin();
5444 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5445 ZeroExtend->getValueType(0) != MVT::i32)
5446 return SDValue();
5448 auto Copy = ZeroExtend->use_begin();
5449 if (Copy->getOpcode() == ISD::CopyToReg &&
5450 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5451 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5452 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5453 return Cvt;
5455 return SDValue();
5458 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5459 return SDValue();
5461 // Turn i64->f64 into VMOVDRR.
5462 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5463 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5464 // if we can combine the bitcast with its source.
5465 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5466 return Val;
5468 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5469 DAG.getConstant(0, dl, MVT::i32));
5470 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5471 DAG.getConstant(1, dl, MVT::i32));
5472 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5473 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5476 // Turn f64->i64 into VMOVRRD.
5477 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5478 SDValue Cvt;
5479 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5480 SrcVT.getVectorNumElements() > 1)
5481 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5482 DAG.getVTList(MVT::i32, MVT::i32),
5483 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5484 else
5485 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5486 DAG.getVTList(MVT::i32, MVT::i32), Op);
5487 // Merge the pieces into a single i64 value.
5488 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5491 return SDValue();
5494 /// getZeroVector - Returns a vector of specified type with all zero elements.
5495 /// Zero vectors are used to represent vector negation and in those cases
5496 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5497 /// not support i64 elements, so sometimes the zero vectors will need to be
5498 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5499 /// zero vector.
5500 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5501 assert(VT.isVector() && "Expected a vector type");
5502 // The canonical modified immediate encoding of a zero vector is....0!
5503 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5504 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5505 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5506 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5509 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5510 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5511 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5512 SelectionDAG &DAG) const {
5513 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5514 EVT VT = Op.getValueType();
5515 unsigned VTBits = VT.getSizeInBits();
5516 SDLoc dl(Op);
5517 SDValue ShOpLo = Op.getOperand(0);
5518 SDValue ShOpHi = Op.getOperand(1);
5519 SDValue ShAmt = Op.getOperand(2);
5520 SDValue ARMcc;
5521 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5522 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5524 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5526 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5527 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5528 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5529 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5530 DAG.getConstant(VTBits, dl, MVT::i32));
5531 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5532 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5533 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5534 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5535 ISD::SETGE, ARMcc, DAG, dl);
5536 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5537 ARMcc, CCR, CmpLo);
5539 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5540 SDValue HiBigShift = Opc == ISD::SRA
5541 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5542 DAG.getConstant(VTBits - 1, dl, VT))
5543 : DAG.getConstant(0, dl, VT);
5544 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5545 ISD::SETGE, ARMcc, DAG, dl);
5546 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5547 ARMcc, CCR, CmpHi);
5549 SDValue Ops[2] = { Lo, Hi };
5550 return DAG.getMergeValues(Ops, dl);
5553 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5554 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5555 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5556 SelectionDAG &DAG) const {
5557 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5558 EVT VT = Op.getValueType();
5559 unsigned VTBits = VT.getSizeInBits();
5560 SDLoc dl(Op);
5561 SDValue ShOpLo = Op.getOperand(0);
5562 SDValue ShOpHi = Op.getOperand(1);
5563 SDValue ShAmt = Op.getOperand(2);
5564 SDValue ARMcc;
5565 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5567 assert(Op.getOpcode() == ISD::SHL_PARTS);
5568 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5569 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5570 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5571 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5572 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5574 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5575 DAG.getConstant(VTBits, dl, MVT::i32));
5576 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5577 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5578 ISD::SETGE, ARMcc, DAG, dl);
5579 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5580 ARMcc, CCR, CmpHi);
5582 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5583 ISD::SETGE, ARMcc, DAG, dl);
5584 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5585 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5586 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5588 SDValue Ops[2] = { Lo, Hi };
5589 return DAG.getMergeValues(Ops, dl);
5592 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5593 SelectionDAG &DAG) const {
5594 // The rounding mode is in bits 23:22 of the FPSCR.
5595 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5596 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5597 // so that the shift + and get folded into a bitfield extract.
5598 SDLoc dl(Op);
5599 SDValue Ops[] = { DAG.getEntryNode(),
5600 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5602 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5603 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5604 DAG.getConstant(1U << 22, dl, MVT::i32));
5605 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5606 DAG.getConstant(22, dl, MVT::i32));
5607 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5608 DAG.getConstant(3, dl, MVT::i32));
5611 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5612 const ARMSubtarget *ST) {
5613 SDLoc dl(N);
5614 EVT VT = N->getValueType(0);
5615 if (VT.isVector()) {
5616 assert(ST->hasNEON());
5618 // Compute the least significant set bit: LSB = X & -X
5619 SDValue X = N->getOperand(0);
5620 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5621 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5623 EVT ElemTy = VT.getVectorElementType();
5625 if (ElemTy == MVT::i8) {
5626 // Compute with: cttz(x) = ctpop(lsb - 1)
5627 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5628 DAG.getTargetConstant(1, dl, ElemTy));
5629 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5630 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5633 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5634 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5635 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5636 unsigned NumBits = ElemTy.getSizeInBits();
5637 SDValue WidthMinus1 =
5638 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5639 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5640 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5641 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5644 // Compute with: cttz(x) = ctpop(lsb - 1)
5646 // Compute LSB - 1.
5647 SDValue Bits;
5648 if (ElemTy == MVT::i64) {
5649 // Load constant 0xffff'ffff'ffff'ffff to register.
5650 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5651 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5652 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5653 } else {
5654 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5655 DAG.getTargetConstant(1, dl, ElemTy));
5656 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5658 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5661 if (!ST->hasV6T2Ops())
5662 return SDValue();
5664 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5665 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5668 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5669 const ARMSubtarget *ST) {
5670 EVT VT = N->getValueType(0);
5671 SDLoc DL(N);
5673 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5674 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5675 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5676 "Unexpected type for custom ctpop lowering");
5678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5679 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5680 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5681 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5683 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5684 unsigned EltSize = 8;
5685 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5686 while (EltSize != VT.getScalarSizeInBits()) {
5687 SmallVector<SDValue, 8> Ops;
5688 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5689 TLI.getPointerTy(DAG.getDataLayout())));
5690 Ops.push_back(Res);
5692 EltSize *= 2;
5693 NumElts /= 2;
5694 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5695 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5698 return Res;
5701 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5702 /// operand of a vector shift operation, where all the elements of the
5703 /// build_vector must have the same constant integer value.
5704 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5705 // Ignore bit_converts.
5706 while (Op.getOpcode() == ISD::BITCAST)
5707 Op = Op.getOperand(0);
5708 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5709 APInt SplatBits, SplatUndef;
5710 unsigned SplatBitSize;
5711 bool HasAnyUndefs;
5712 if (!BVN ||
5713 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5714 ElementBits) ||
5715 SplatBitSize > ElementBits)
5716 return false;
5717 Cnt = SplatBits.getSExtValue();
5718 return true;
5721 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5722 /// operand of a vector shift left operation. That value must be in the range:
5723 /// 0 <= Value < ElementBits for a left shift; or
5724 /// 0 <= Value <= ElementBits for a long left shift.
5725 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5726 assert(VT.isVector() && "vector shift count is not a vector type");
5727 int64_t ElementBits = VT.getScalarSizeInBits();
5728 if (!getVShiftImm(Op, ElementBits, Cnt))
5729 return false;
5730 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5733 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5734 /// operand of a vector shift right operation. For a shift opcode, the value
5735 /// is positive, but for an intrinsic the value count must be negative. The
5736 /// absolute value must be in the range:
5737 /// 1 <= |Value| <= ElementBits for a right shift; or
5738 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5739 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5740 int64_t &Cnt) {
5741 assert(VT.isVector() && "vector shift count is not a vector type");
5742 int64_t ElementBits = VT.getScalarSizeInBits();
5743 if (!getVShiftImm(Op, ElementBits, Cnt))
5744 return false;
5745 if (!isIntrinsic)
5746 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5747 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5748 Cnt = -Cnt;
5749 return true;
5751 return false;
5754 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5755 const ARMSubtarget *ST) {
5756 EVT VT = N->getValueType(0);
5757 SDLoc dl(N);
5758 int64_t Cnt;
5760 if (!VT.isVector())
5761 return SDValue();
5763 // We essentially have two forms here. Shift by an immediate and shift by a
5764 // vector register (there are also shift by a gpr, but that is just handled
5765 // with a tablegen pattern). We cannot easily match shift by an immediate in
5766 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5767 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5768 // signed or unsigned, and a negative shift indicates a shift right).
5769 if (N->getOpcode() == ISD::SHL) {
5770 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5771 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5772 DAG.getConstant(Cnt, dl, MVT::i32));
5773 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5774 N->getOperand(1));
5777 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5778 "unexpected vector shift opcode");
5780 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5781 unsigned VShiftOpc =
5782 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5783 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5784 DAG.getConstant(Cnt, dl, MVT::i32));
5787 // Other right shifts we don't have operations for (we use a shift left by a
5788 // negative number).
5789 EVT ShiftVT = N->getOperand(1).getValueType();
5790 SDValue NegatedCount = DAG.getNode(
5791 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5792 unsigned VShiftOpc =
5793 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5794 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5797 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5798 const ARMSubtarget *ST) {
5799 EVT VT = N->getValueType(0);
5800 SDLoc dl(N);
5802 // We can get here for a node like i32 = ISD::SHL i32, i64
5803 if (VT != MVT::i64)
5804 return SDValue();
5806 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5807 N->getOpcode() == ISD::SHL) &&
5808 "Unknown shift to lower!");
5810 unsigned ShOpc = N->getOpcode();
5811 if (ST->hasMVEIntegerOps()) {
5812 SDValue ShAmt = N->getOperand(1);
5813 unsigned ShPartsOpc = ARMISD::LSLL;
5814 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5816 // If the shift amount is greater than 32 then do the default optimisation
5817 if (Con && Con->getZExtValue() > 32)
5818 return SDValue();
5820 // Extract the lower 32 bits of the shift amount if it's an i64
5821 if (ShAmt->getValueType(0) == MVT::i64)
5822 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt,
5823 DAG.getConstant(0, dl, MVT::i32));
5825 if (ShOpc == ISD::SRL) {
5826 if (!Con)
5827 // There is no t2LSRLr instruction so negate and perform an lsll if the
5828 // shift amount is in a register, emulating a right shift.
5829 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5830 DAG.getConstant(0, dl, MVT::i32), ShAmt);
5831 else
5832 // Else generate an lsrl on the immediate shift amount
5833 ShPartsOpc = ARMISD::LSRL;
5834 } else if (ShOpc == ISD::SRA)
5835 ShPartsOpc = ARMISD::ASRL;
5837 // Lower 32 bits of the destination/source
5838 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5839 DAG.getConstant(0, dl, MVT::i32));
5840 // Upper 32 bits of the destination/source
5841 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5842 DAG.getConstant(1, dl, MVT::i32));
5844 // Generate the shift operation as computed above
5845 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
5846 ShAmt);
5847 // The upper 32 bits come from the second return value of lsll
5848 Hi = SDValue(Lo.getNode(), 1);
5849 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5852 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5853 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
5854 return SDValue();
5856 // If we are in thumb mode, we don't have RRX.
5857 if (ST->isThumb1Only())
5858 return SDValue();
5860 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5861 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5862 DAG.getConstant(0, dl, MVT::i32));
5863 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5864 DAG.getConstant(1, dl, MVT::i32));
5866 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5867 // captures the result into a carry flag.
5868 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5869 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5871 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5872 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5874 // Merge the pieces into a single i64 value.
5875 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5878 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
5879 const ARMSubtarget *ST) {
5880 SDValue TmpOp0, TmpOp1;
5881 bool Invert = false;
5882 bool Swap = false;
5883 unsigned Opc = 0;
5885 SDValue Op0 = Op.getOperand(0);
5886 SDValue Op1 = Op.getOperand(1);
5887 SDValue CC = Op.getOperand(2);
5888 EVT VT = Op.getValueType();
5889 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5890 SDLoc dl(Op);
5892 EVT CmpVT;
5893 if (ST->hasNEON())
5894 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5895 else {
5896 assert(ST->hasMVEIntegerOps() &&
5897 "No hardware support for integer vector comparison!");
5899 if (Op.getValueType().getVectorElementType() != MVT::i1)
5900 return SDValue();
5902 // Make sure we expand floating point setcc to scalar if we do not have
5903 // mve.fp, so that we can handle them from there.
5904 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
5905 return SDValue();
5907 CmpVT = VT;
5910 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5911 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5912 // Special-case integer 64-bit equality comparisons. They aren't legal,
5913 // but they can be lowered with a few vector instructions.
5914 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5915 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5916 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5917 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5918 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5919 DAG.getCondCode(ISD::SETEQ));
5920 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5921 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5922 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5923 if (SetCCOpcode == ISD::SETNE)
5924 Merged = DAG.getNOT(dl, Merged, CmpVT);
5925 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5926 return Merged;
5929 if (CmpVT.getVectorElementType() == MVT::i64)
5930 // 64-bit comparisons are not legal in general.
5931 return SDValue();
5933 if (Op1.getValueType().isFloatingPoint()) {
5934 switch (SetCCOpcode) {
5935 default: llvm_unreachable("Illegal FP comparison");
5936 case ISD::SETUNE:
5937 case ISD::SETNE:
5938 if (ST->hasMVEFloatOps()) {
5939 Opc = ARMISD::VCNE; break;
5940 } else {
5941 Invert = true; LLVM_FALLTHROUGH;
5943 case ISD::SETOEQ:
5944 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5945 case ISD::SETOLT:
5946 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5947 case ISD::SETOGT:
5948 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5949 case ISD::SETOLE:
5950 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5951 case ISD::SETOGE:
5952 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5953 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5954 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5955 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5956 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5957 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5958 case ISD::SETONE:
5959 // Expand this to (OLT | OGT).
5960 TmpOp0 = Op0;
5961 TmpOp1 = Op1;
5962 Opc = ISD::OR;
5963 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5964 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5965 break;
5966 case ISD::SETUO:
5967 Invert = true;
5968 LLVM_FALLTHROUGH;
5969 case ISD::SETO:
5970 // Expand this to (OLT | OGE).
5971 TmpOp0 = Op0;
5972 TmpOp1 = Op1;
5973 Opc = ISD::OR;
5974 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5975 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5976 break;
5978 } else {
5979 // Integer comparisons.
5980 switch (SetCCOpcode) {
5981 default: llvm_unreachable("Illegal integer comparison");
5982 case ISD::SETNE:
5983 if (ST->hasMVEIntegerOps()) {
5984 Opc = ARMISD::VCNE; break;
5985 } else {
5986 Invert = true; LLVM_FALLTHROUGH;
5988 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
5989 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5990 case ISD::SETGT: Opc = ARMISD::VCGT; break;
5991 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5992 case ISD::SETGE: Opc = ARMISD::VCGE; break;
5993 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5994 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5995 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5996 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5999 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6000 if (ST->hasNEON() && Opc == ARMISD::VCEQ) {
6001 SDValue AndOp;
6002 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6003 AndOp = Op0;
6004 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6005 AndOp = Op1;
6007 // Ignore bitconvert.
6008 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6009 AndOp = AndOp.getOperand(0);
6011 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6012 Opc = ARMISD::VTST;
6013 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6014 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6015 Invert = !Invert;
6020 if (Swap)
6021 std::swap(Op0, Op1);
6023 // If one of the operands is a constant vector zero, attempt to fold the
6024 // comparison to a specialized compare-against-zero form.
6025 SDValue SingleOp;
6026 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6027 SingleOp = Op0;
6028 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6029 if (Opc == ARMISD::VCGE)
6030 Opc = ARMISD::VCLEZ;
6031 else if (Opc == ARMISD::VCGT)
6032 Opc = ARMISD::VCLTZ;
6033 SingleOp = Op1;
6036 SDValue Result;
6037 if (SingleOp.getNode()) {
6038 switch (Opc) {
6039 case ARMISD::VCNE:
6040 assert(ST->hasMVEIntegerOps() && "Unexpected DAG node");
6041 Result = DAG.getNode(ARMISD::VCNEZ, dl, CmpVT, SingleOp); break;
6042 case ARMISD::VCEQ:
6043 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
6044 case ARMISD::VCGE:
6045 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
6046 case ARMISD::VCLEZ:
6047 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
6048 case ARMISD::VCGT:
6049 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
6050 case ARMISD::VCLTZ:
6051 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
6052 default:
6053 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
6055 } else {
6056 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
6059 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6061 if (Invert)
6062 Result = DAG.getNOT(dl, Result, VT);
6064 return Result;
6067 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6068 SDValue LHS = Op.getOperand(0);
6069 SDValue RHS = Op.getOperand(1);
6070 SDValue Carry = Op.getOperand(2);
6071 SDValue Cond = Op.getOperand(3);
6072 SDLoc DL(Op);
6074 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6076 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6077 // have to invert the carry first.
6078 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6079 DAG.getConstant(1, DL, MVT::i32), Carry);
6080 // This converts the boolean value carry into the carry flag.
6081 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6083 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6084 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6086 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6087 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6088 SDValue ARMcc = DAG.getConstant(
6089 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6090 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6091 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6092 Cmp.getValue(1), SDValue());
6093 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6094 CCR, Chain.getValue(1));
6097 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6098 /// valid vector constant for a NEON or MVE instruction with a "modified
6099 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6100 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6101 unsigned SplatBitSize, SelectionDAG &DAG,
6102 const SDLoc &dl, EVT &VT, bool is128Bits,
6103 VMOVModImmType type) {
6104 unsigned OpCmode, Imm;
6106 // SplatBitSize is set to the smallest size that splats the vector, so a
6107 // zero vector will always have SplatBitSize == 8. However, NEON modified
6108 // immediate instructions others than VMOV do not support the 8-bit encoding
6109 // of a zero vector, and the default encoding of zero is supposed to be the
6110 // 32-bit version.
6111 if (SplatBits == 0)
6112 SplatBitSize = 32;
6114 switch (SplatBitSize) {
6115 case 8:
6116 if (type != VMOVModImm)
6117 return SDValue();
6118 // Any 1-byte value is OK. Op=0, Cmode=1110.
6119 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6120 OpCmode = 0xe;
6121 Imm = SplatBits;
6122 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6123 break;
6125 case 16:
6126 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6127 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6128 if ((SplatBits & ~0xff) == 0) {
6129 // Value = 0x00nn: Op=x, Cmode=100x.
6130 OpCmode = 0x8;
6131 Imm = SplatBits;
6132 break;
6134 if ((SplatBits & ~0xff00) == 0) {
6135 // Value = 0xnn00: Op=x, Cmode=101x.
6136 OpCmode = 0xa;
6137 Imm = SplatBits >> 8;
6138 break;
6140 return SDValue();
6142 case 32:
6143 // NEON's 32-bit VMOV supports splat values where:
6144 // * only one byte is nonzero, or
6145 // * the least significant byte is 0xff and the second byte is nonzero, or
6146 // * the least significant 2 bytes are 0xff and the third is nonzero.
6147 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6148 if ((SplatBits & ~0xff) == 0) {
6149 // Value = 0x000000nn: Op=x, Cmode=000x.
6150 OpCmode = 0;
6151 Imm = SplatBits;
6152 break;
6154 if ((SplatBits & ~0xff00) == 0) {
6155 // Value = 0x0000nn00: Op=x, Cmode=001x.
6156 OpCmode = 0x2;
6157 Imm = SplatBits >> 8;
6158 break;
6160 if ((SplatBits & ~0xff0000) == 0) {
6161 // Value = 0x00nn0000: Op=x, Cmode=010x.
6162 OpCmode = 0x4;
6163 Imm = SplatBits >> 16;
6164 break;
6166 if ((SplatBits & ~0xff000000) == 0) {
6167 // Value = 0xnn000000: Op=x, Cmode=011x.
6168 OpCmode = 0x6;
6169 Imm = SplatBits >> 24;
6170 break;
6173 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6174 if (type == OtherModImm) return SDValue();
6176 if ((SplatBits & ~0xffff) == 0 &&
6177 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6178 // Value = 0x0000nnff: Op=x, Cmode=1100.
6179 OpCmode = 0xc;
6180 Imm = SplatBits >> 8;
6181 break;
6184 // cmode == 0b1101 is not supported for MVE VMVN
6185 if (type == MVEVMVNModImm)
6186 return SDValue();
6188 if ((SplatBits & ~0xffffff) == 0 &&
6189 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6190 // Value = 0x00nnffff: Op=x, Cmode=1101.
6191 OpCmode = 0xd;
6192 Imm = SplatBits >> 16;
6193 break;
6196 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6197 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6198 // VMOV.I32. A (very) minor optimization would be to replicate the value
6199 // and fall through here to test for a valid 64-bit splat. But, then the
6200 // caller would also need to check and handle the change in size.
6201 return SDValue();
6203 case 64: {
6204 if (type != VMOVModImm)
6205 return SDValue();
6206 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6207 uint64_t BitMask = 0xff;
6208 uint64_t Val = 0;
6209 unsigned ImmMask = 1;
6210 Imm = 0;
6211 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6212 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6213 Val |= BitMask;
6214 Imm |= ImmMask;
6215 } else if ((SplatBits & BitMask) != 0) {
6216 return SDValue();
6218 BitMask <<= 8;
6219 ImmMask <<= 1;
6222 if (DAG.getDataLayout().isBigEndian())
6223 // swap higher and lower 32 bit word
6224 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6226 // Op=1, Cmode=1110.
6227 OpCmode = 0x1e;
6228 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6229 break;
6232 default:
6233 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6236 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6237 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6240 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6241 const ARMSubtarget *ST) const {
6242 EVT VT = Op.getValueType();
6243 bool IsDouble = (VT == MVT::f64);
6244 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6245 const APFloat &FPVal = CFP->getValueAPF();
6247 // Prevent floating-point constants from using literal loads
6248 // when execute-only is enabled.
6249 if (ST->genExecuteOnly()) {
6250 // If we can represent the constant as an immediate, don't lower it
6251 if (isFPImmLegal(FPVal, VT))
6252 return Op;
6253 // Otherwise, construct as integer, and move to float register
6254 APInt INTVal = FPVal.bitcastToAPInt();
6255 SDLoc DL(CFP);
6256 switch (VT.getSimpleVT().SimpleTy) {
6257 default:
6258 llvm_unreachable("Unknown floating point type!");
6259 break;
6260 case MVT::f64: {
6261 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6262 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6263 if (!ST->isLittle())
6264 std::swap(Lo, Hi);
6265 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6267 case MVT::f32:
6268 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6269 DAG.getConstant(INTVal, DL, MVT::i32));
6273 if (!ST->hasVFP3Base())
6274 return SDValue();
6276 // Use the default (constant pool) lowering for double constants when we have
6277 // an SP-only FPU
6278 if (IsDouble && !Subtarget->hasFP64())
6279 return SDValue();
6281 // Try splatting with a VMOV.f32...
6282 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6284 if (ImmVal != -1) {
6285 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6286 // We have code in place to select a valid ConstantFP already, no need to
6287 // do any mangling.
6288 return Op;
6291 // It's a float and we are trying to use NEON operations where
6292 // possible. Lower it to a splat followed by an extract.
6293 SDLoc DL(Op);
6294 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6295 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6296 NewVal);
6297 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6298 DAG.getConstant(0, DL, MVT::i32));
6301 // The rest of our options are NEON only, make sure that's allowed before
6302 // proceeding..
6303 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6304 return SDValue();
6306 EVT VMovVT;
6307 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6309 // It wouldn't really be worth bothering for doubles except for one very
6310 // important value, which does happen to match: 0.0. So make sure we don't do
6311 // anything stupid.
6312 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6313 return SDValue();
6315 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6316 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6317 VMovVT, false, VMOVModImm);
6318 if (NewVal != SDValue()) {
6319 SDLoc DL(Op);
6320 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6321 NewVal);
6322 if (IsDouble)
6323 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6325 // It's a float: cast and extract a vector element.
6326 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6327 VecConstant);
6328 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6329 DAG.getConstant(0, DL, MVT::i32));
6332 // Finally, try a VMVN.i32
6333 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6334 false, VMVNModImm);
6335 if (NewVal != SDValue()) {
6336 SDLoc DL(Op);
6337 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6339 if (IsDouble)
6340 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6342 // It's a float: cast and extract a vector element.
6343 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6344 VecConstant);
6345 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6346 DAG.getConstant(0, DL, MVT::i32));
6349 return SDValue();
6352 // check if an VEXT instruction can handle the shuffle mask when the
6353 // vector sources of the shuffle are the same.
6354 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6355 unsigned NumElts = VT.getVectorNumElements();
6357 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6358 if (M[0] < 0)
6359 return false;
6361 Imm = M[0];
6363 // If this is a VEXT shuffle, the immediate value is the index of the first
6364 // element. The other shuffle indices must be the successive elements after
6365 // the first one.
6366 unsigned ExpectedElt = Imm;
6367 for (unsigned i = 1; i < NumElts; ++i) {
6368 // Increment the expected index. If it wraps around, just follow it
6369 // back to index zero and keep going.
6370 ++ExpectedElt;
6371 if (ExpectedElt == NumElts)
6372 ExpectedElt = 0;
6374 if (M[i] < 0) continue; // ignore UNDEF indices
6375 if (ExpectedElt != static_cast<unsigned>(M[i]))
6376 return false;
6379 return true;
6382 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6383 bool &ReverseVEXT, unsigned &Imm) {
6384 unsigned NumElts = VT.getVectorNumElements();
6385 ReverseVEXT = false;
6387 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6388 if (M[0] < 0)
6389 return false;
6391 Imm = M[0];
6393 // If this is a VEXT shuffle, the immediate value is the index of the first
6394 // element. The other shuffle indices must be the successive elements after
6395 // the first one.
6396 unsigned ExpectedElt = Imm;
6397 for (unsigned i = 1; i < NumElts; ++i) {
6398 // Increment the expected index. If it wraps around, it may still be
6399 // a VEXT but the source vectors must be swapped.
6400 ExpectedElt += 1;
6401 if (ExpectedElt == NumElts * 2) {
6402 ExpectedElt = 0;
6403 ReverseVEXT = true;
6406 if (M[i] < 0) continue; // ignore UNDEF indices
6407 if (ExpectedElt != static_cast<unsigned>(M[i]))
6408 return false;
6411 // Adjust the index value if the source operands will be swapped.
6412 if (ReverseVEXT)
6413 Imm -= NumElts;
6415 return true;
6418 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6419 /// instruction with the specified blocksize. (The order of the elements
6420 /// within each block of the vector is reversed.)
6421 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6422 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6423 "Only possible block sizes for VREV are: 16, 32, 64");
6425 unsigned EltSz = VT.getScalarSizeInBits();
6426 if (EltSz == 64)
6427 return false;
6429 unsigned NumElts = VT.getVectorNumElements();
6430 unsigned BlockElts = M[0] + 1;
6431 // If the first shuffle index is UNDEF, be optimistic.
6432 if (M[0] < 0)
6433 BlockElts = BlockSize / EltSz;
6435 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6436 return false;
6438 for (unsigned i = 0; i < NumElts; ++i) {
6439 if (M[i] < 0) continue; // ignore UNDEF indices
6440 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6441 return false;
6444 return true;
6447 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6448 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6449 // range, then 0 is placed into the resulting vector. So pretty much any mask
6450 // of 8 elements can work here.
6451 return VT == MVT::v8i8 && M.size() == 8;
6454 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6455 unsigned Index) {
6456 if (Mask.size() == Elements * 2)
6457 return Index / Elements;
6458 return Mask[Index] == 0 ? 0 : 1;
6461 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6462 // checking that pairs of elements in the shuffle mask represent the same index
6463 // in each vector, incrementing the expected index by 2 at each step.
6464 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6465 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6466 // v2={e,f,g,h}
6467 // WhichResult gives the offset for each element in the mask based on which
6468 // of the two results it belongs to.
6470 // The transpose can be represented either as:
6471 // result1 = shufflevector v1, v2, result1_shuffle_mask
6472 // result2 = shufflevector v1, v2, result2_shuffle_mask
6473 // where v1/v2 and the shuffle masks have the same number of elements
6474 // (here WhichResult (see below) indicates which result is being checked)
6476 // or as:
6477 // results = shufflevector v1, v2, shuffle_mask
6478 // where both results are returned in one vector and the shuffle mask has twice
6479 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6480 // want to check the low half and high half of the shuffle mask as if it were
6481 // the other case
6482 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6483 unsigned EltSz = VT.getScalarSizeInBits();
6484 if (EltSz == 64)
6485 return false;
6487 unsigned NumElts = VT.getVectorNumElements();
6488 if (M.size() != NumElts && M.size() != NumElts*2)
6489 return false;
6491 // If the mask is twice as long as the input vector then we need to check the
6492 // upper and lower parts of the mask with a matching value for WhichResult
6493 // FIXME: A mask with only even values will be rejected in case the first
6494 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6495 // M[0] is used to determine WhichResult
6496 for (unsigned i = 0; i < M.size(); i += NumElts) {
6497 WhichResult = SelectPairHalf(NumElts, M, i);
6498 for (unsigned j = 0; j < NumElts; j += 2) {
6499 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6500 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6501 return false;
6505 if (M.size() == NumElts*2)
6506 WhichResult = 0;
6508 return true;
6511 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6512 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6513 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6514 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6515 unsigned EltSz = VT.getScalarSizeInBits();
6516 if (EltSz == 64)
6517 return false;
6519 unsigned NumElts = VT.getVectorNumElements();
6520 if (M.size() != NumElts && M.size() != NumElts*2)
6521 return false;
6523 for (unsigned i = 0; i < M.size(); i += NumElts) {
6524 WhichResult = SelectPairHalf(NumElts, M, i);
6525 for (unsigned j = 0; j < NumElts; j += 2) {
6526 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6527 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6528 return false;
6532 if (M.size() == NumElts*2)
6533 WhichResult = 0;
6535 return true;
6538 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6539 // that the mask elements are either all even and in steps of size 2 or all odd
6540 // and in steps of size 2.
6541 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6542 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6543 // v2={e,f,g,h}
6544 // Requires similar checks to that of isVTRNMask with
6545 // respect the how results are returned.
6546 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6547 unsigned EltSz = VT.getScalarSizeInBits();
6548 if (EltSz == 64)
6549 return false;
6551 unsigned NumElts = VT.getVectorNumElements();
6552 if (M.size() != NumElts && M.size() != NumElts*2)
6553 return false;
6555 for (unsigned i = 0; i < M.size(); i += NumElts) {
6556 WhichResult = SelectPairHalf(NumElts, M, i);
6557 for (unsigned j = 0; j < NumElts; ++j) {
6558 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6559 return false;
6563 if (M.size() == NumElts*2)
6564 WhichResult = 0;
6566 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6567 if (VT.is64BitVector() && EltSz == 32)
6568 return false;
6570 return true;
6573 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6574 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6575 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6576 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6577 unsigned EltSz = VT.getScalarSizeInBits();
6578 if (EltSz == 64)
6579 return false;
6581 unsigned NumElts = VT.getVectorNumElements();
6582 if (M.size() != NumElts && M.size() != NumElts*2)
6583 return false;
6585 unsigned Half = NumElts / 2;
6586 for (unsigned i = 0; i < M.size(); i += NumElts) {
6587 WhichResult = SelectPairHalf(NumElts, M, i);
6588 for (unsigned j = 0; j < NumElts; j += Half) {
6589 unsigned Idx = WhichResult;
6590 for (unsigned k = 0; k < Half; ++k) {
6591 int MIdx = M[i + j + k];
6592 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6593 return false;
6594 Idx += 2;
6599 if (M.size() == NumElts*2)
6600 WhichResult = 0;
6602 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6603 if (VT.is64BitVector() && EltSz == 32)
6604 return false;
6606 return true;
6609 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6610 // that pairs of elements of the shufflemask represent the same index in each
6611 // vector incrementing sequentially through the vectors.
6612 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6613 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6614 // v2={e,f,g,h}
6615 // Requires similar checks to that of isVTRNMask with respect the how results
6616 // are returned.
6617 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6618 unsigned EltSz = VT.getScalarSizeInBits();
6619 if (EltSz == 64)
6620 return false;
6622 unsigned NumElts = VT.getVectorNumElements();
6623 if (M.size() != NumElts && M.size() != NumElts*2)
6624 return false;
6626 for (unsigned i = 0; i < M.size(); i += NumElts) {
6627 WhichResult = SelectPairHalf(NumElts, M, i);
6628 unsigned Idx = WhichResult * NumElts / 2;
6629 for (unsigned j = 0; j < NumElts; j += 2) {
6630 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6631 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6632 return false;
6633 Idx += 1;
6637 if (M.size() == NumElts*2)
6638 WhichResult = 0;
6640 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6641 if (VT.is64BitVector() && EltSz == 32)
6642 return false;
6644 return true;
6647 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6648 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6649 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6650 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6651 unsigned EltSz = VT.getScalarSizeInBits();
6652 if (EltSz == 64)
6653 return false;
6655 unsigned NumElts = VT.getVectorNumElements();
6656 if (M.size() != NumElts && M.size() != NumElts*2)
6657 return false;
6659 for (unsigned i = 0; i < M.size(); i += NumElts) {
6660 WhichResult = SelectPairHalf(NumElts, M, i);
6661 unsigned Idx = WhichResult * NumElts / 2;
6662 for (unsigned j = 0; j < NumElts; j += 2) {
6663 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6664 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6665 return false;
6666 Idx += 1;
6670 if (M.size() == NumElts*2)
6671 WhichResult = 0;
6673 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6674 if (VT.is64BitVector() && EltSz == 32)
6675 return false;
6677 return true;
6680 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6681 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6682 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6683 unsigned &WhichResult,
6684 bool &isV_UNDEF) {
6685 isV_UNDEF = false;
6686 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6687 return ARMISD::VTRN;
6688 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6689 return ARMISD::VUZP;
6690 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6691 return ARMISD::VZIP;
6693 isV_UNDEF = true;
6694 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6695 return ARMISD::VTRN;
6696 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6697 return ARMISD::VUZP;
6698 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6699 return ARMISD::VZIP;
6701 return 0;
6704 /// \return true if this is a reverse operation on an vector.
6705 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6706 unsigned NumElts = VT.getVectorNumElements();
6707 // Make sure the mask has the right size.
6708 if (NumElts != M.size())
6709 return false;
6711 // Look for <15, ..., 3, -1, 1, 0>.
6712 for (unsigned i = 0; i != NumElts; ++i)
6713 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6714 return false;
6716 return true;
6719 // If N is an integer constant that can be moved into a register in one
6720 // instruction, return an SDValue of such a constant (will become a MOV
6721 // instruction). Otherwise return null.
6722 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6723 const ARMSubtarget *ST, const SDLoc &dl) {
6724 uint64_t Val;
6725 if (!isa<ConstantSDNode>(N))
6726 return SDValue();
6727 Val = cast<ConstantSDNode>(N)->getZExtValue();
6729 if (ST->isThumb1Only()) {
6730 if (Val <= 255 || ~Val <= 255)
6731 return DAG.getConstant(Val, dl, MVT::i32);
6732 } else {
6733 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6734 return DAG.getConstant(Val, dl, MVT::i32);
6736 return SDValue();
6739 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6740 const ARMSubtarget *ST) {
6741 SDLoc dl(Op);
6742 EVT VT = Op.getValueType();
6744 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6746 unsigned NumElts = VT.getVectorNumElements();
6747 unsigned BoolMask;
6748 unsigned BitsPerBool;
6749 if (NumElts == 4) {
6750 BitsPerBool = 4;
6751 BoolMask = 0xf;
6752 } else if (NumElts == 8) {
6753 BitsPerBool = 2;
6754 BoolMask = 0x3;
6755 } else if (NumElts == 16) {
6756 BitsPerBool = 1;
6757 BoolMask = 0x1;
6758 } else
6759 return SDValue();
6761 // First create base with bits set where known
6762 unsigned Bits32 = 0;
6763 for (unsigned i = 0; i < NumElts; ++i) {
6764 SDValue V = Op.getOperand(i);
6765 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6766 continue;
6767 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6768 if (BitSet)
6769 Bits32 |= BoolMask << (i * BitsPerBool);
6772 // Add in unknown nodes
6773 // FIXME: Handle splats of the same value better.
6774 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6775 DAG.getConstant(Bits32, dl, MVT::i32));
6776 for (unsigned i = 0; i < NumElts; ++i) {
6777 SDValue V = Op.getOperand(i);
6778 if (isa<ConstantSDNode>(V) || V.isUndef())
6779 continue;
6780 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6781 DAG.getConstant(i, dl, MVT::i32));
6784 return Base;
6787 // If this is a case we can't handle, return null and let the default
6788 // expansion code take care of it.
6789 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6790 const ARMSubtarget *ST) const {
6791 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6792 SDLoc dl(Op);
6793 EVT VT = Op.getValueType();
6795 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6796 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6798 APInt SplatBits, SplatUndef;
6799 unsigned SplatBitSize;
6800 bool HasAnyUndefs;
6801 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6802 if (SplatUndef.isAllOnesValue())
6803 return DAG.getUNDEF(VT);
6805 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6806 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6807 // Check if an immediate VMOV works.
6808 EVT VmovVT;
6809 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6810 SplatUndef.getZExtValue(), SplatBitSize,
6811 DAG, dl, VmovVT, VT.is128BitVector(),
6812 VMOVModImm);
6814 if (Val.getNode()) {
6815 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6816 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6819 // Try an immediate VMVN.
6820 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6821 Val = isVMOVModifiedImm(
6822 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6823 DAG, dl, VmovVT, VT.is128BitVector(),
6824 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6825 if (Val.getNode()) {
6826 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6827 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6830 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6831 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6832 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6833 if (ImmVal != -1) {
6834 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6835 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6841 // Scan through the operands to see if only one value is used.
6843 // As an optimisation, even if more than one value is used it may be more
6844 // profitable to splat with one value then change some lanes.
6846 // Heuristically we decide to do this if the vector has a "dominant" value,
6847 // defined as splatted to more than half of the lanes.
6848 unsigned NumElts = VT.getVectorNumElements();
6849 bool isOnlyLowElement = true;
6850 bool usesOnlyOneValue = true;
6851 bool hasDominantValue = false;
6852 bool isConstant = true;
6854 // Map of the number of times a particular SDValue appears in the
6855 // element list.
6856 DenseMap<SDValue, unsigned> ValueCounts;
6857 SDValue Value;
6858 for (unsigned i = 0; i < NumElts; ++i) {
6859 SDValue V = Op.getOperand(i);
6860 if (V.isUndef())
6861 continue;
6862 if (i > 0)
6863 isOnlyLowElement = false;
6864 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6865 isConstant = false;
6867 ValueCounts.insert(std::make_pair(V, 0));
6868 unsigned &Count = ValueCounts[V];
6870 // Is this value dominant? (takes up more than half of the lanes)
6871 if (++Count > (NumElts / 2)) {
6872 hasDominantValue = true;
6873 Value = V;
6876 if (ValueCounts.size() != 1)
6877 usesOnlyOneValue = false;
6878 if (!Value.getNode() && !ValueCounts.empty())
6879 Value = ValueCounts.begin()->first;
6881 if (ValueCounts.empty())
6882 return DAG.getUNDEF(VT);
6884 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6885 // Keep going if we are hitting this case.
6886 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6887 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6889 unsigned EltSize = VT.getScalarSizeInBits();
6891 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
6892 // i32 and try again.
6893 if (hasDominantValue && EltSize <= 32) {
6894 if (!isConstant) {
6895 SDValue N;
6897 // If we are VDUPing a value that comes directly from a vector, that will
6898 // cause an unnecessary move to and from a GPR, where instead we could
6899 // just use VDUPLANE. We can only do this if the lane being extracted
6900 // is at a constant index, as the VDUP from lane instructions only have
6901 // constant-index forms.
6902 ConstantSDNode *constIndex;
6903 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6904 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6905 // We need to create a new undef vector to use for the VDUPLANE if the
6906 // size of the vector from which we get the value is different than the
6907 // size of the vector that we need to create. We will insert the element
6908 // such that the register coalescer will remove unnecessary copies.
6909 if (VT != Value->getOperand(0).getValueType()) {
6910 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6911 VT.getVectorNumElements();
6912 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6913 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6914 Value, DAG.getConstant(index, dl, MVT::i32)),
6915 DAG.getConstant(index, dl, MVT::i32));
6916 } else
6917 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6918 Value->getOperand(0), Value->getOperand(1));
6919 } else
6920 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6922 if (!usesOnlyOneValue) {
6923 // The dominant value was splatted as 'N', but we now have to insert
6924 // all differing elements.
6925 for (unsigned I = 0; I < NumElts; ++I) {
6926 if (Op.getOperand(I) == Value)
6927 continue;
6928 SmallVector<SDValue, 3> Ops;
6929 Ops.push_back(N);
6930 Ops.push_back(Op.getOperand(I));
6931 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6932 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6935 return N;
6937 if (VT.getVectorElementType().isFloatingPoint()) {
6938 SmallVector<SDValue, 8> Ops;
6939 MVT FVT = VT.getVectorElementType().getSimpleVT();
6940 assert(FVT == MVT::f32 || FVT == MVT::f16);
6941 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
6942 for (unsigned i = 0; i < NumElts; ++i)
6943 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
6944 Op.getOperand(i)));
6945 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
6946 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6947 Val = LowerBUILD_VECTOR(Val, DAG, ST);
6948 if (Val.getNode())
6949 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6951 if (usesOnlyOneValue) {
6952 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6953 if (isConstant && Val.getNode())
6954 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6958 // If all elements are constants and the case above didn't get hit, fall back
6959 // to the default expansion, which will generate a load from the constant
6960 // pool.
6961 if (isConstant)
6962 return SDValue();
6964 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6965 if (NumElts >= 4) {
6966 SDValue shuffle = ReconstructShuffle(Op, DAG);
6967 if (shuffle != SDValue())
6968 return shuffle;
6971 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6972 // If we haven't found an efficient lowering, try splitting a 128-bit vector
6973 // into two 64-bit vectors; we might discover a better way to lower it.
6974 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6975 EVT ExtVT = VT.getVectorElementType();
6976 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6977 SDValue Lower =
6978 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6979 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6980 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6981 SDValue Upper = DAG.getBuildVector(
6982 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6983 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6984 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6985 if (Lower && Upper)
6986 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6989 // Vectors with 32- or 64-bit elements can be built by directly assigning
6990 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
6991 // will be legalized.
6992 if (EltSize >= 32) {
6993 // Do the expansion with floating-point types, since that is what the VFP
6994 // registers are defined to use, and since i64 is not legal.
6995 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6996 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6997 SmallVector<SDValue, 8> Ops;
6998 for (unsigned i = 0; i < NumElts; ++i)
6999 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7000 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7001 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7004 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7005 // know the default expansion would otherwise fall back on something even
7006 // worse. For a vector with one or two non-undef values, that's
7007 // scalar_to_vector for the elements followed by a shuffle (provided the
7008 // shuffle is valid for the target) and materialization element by element
7009 // on the stack followed by a load for everything else.
7010 if (!isConstant && !usesOnlyOneValue) {
7011 SDValue Vec = DAG.getUNDEF(VT);
7012 for (unsigned i = 0 ; i < NumElts; ++i) {
7013 SDValue V = Op.getOperand(i);
7014 if (V.isUndef())
7015 continue;
7016 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7019 return Vec;
7022 return SDValue();
7025 // Gather data to see if the operation can be modelled as a
7026 // shuffle in combination with VEXTs.
7027 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7028 SelectionDAG &DAG) const {
7029 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7030 SDLoc dl(Op);
7031 EVT VT = Op.getValueType();
7032 unsigned NumElts = VT.getVectorNumElements();
7034 struct ShuffleSourceInfo {
7035 SDValue Vec;
7036 unsigned MinElt = std::numeric_limits<unsigned>::max();
7037 unsigned MaxElt = 0;
7039 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7040 // be compatible with the shuffle we intend to construct. As a result
7041 // ShuffleVec will be some sliding window into the original Vec.
7042 SDValue ShuffleVec;
7044 // Code should guarantee that element i in Vec starts at element "WindowBase
7045 // + i * WindowScale in ShuffleVec".
7046 int WindowBase = 0;
7047 int WindowScale = 1;
7049 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7051 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7054 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7055 // node.
7056 SmallVector<ShuffleSourceInfo, 2> Sources;
7057 for (unsigned i = 0; i < NumElts; ++i) {
7058 SDValue V = Op.getOperand(i);
7059 if (V.isUndef())
7060 continue;
7061 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7062 // A shuffle can only come from building a vector from various
7063 // elements of other vectors.
7064 return SDValue();
7065 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7066 // Furthermore, shuffles require a constant mask, whereas extractelts
7067 // accept variable indices.
7068 return SDValue();
7071 // Add this element source to the list if it's not already there.
7072 SDValue SourceVec = V.getOperand(0);
7073 auto Source = llvm::find(Sources, SourceVec);
7074 if (Source == Sources.end())
7075 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7077 // Update the minimum and maximum lane number seen.
7078 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7079 Source->MinElt = std::min(Source->MinElt, EltNo);
7080 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7083 // Currently only do something sane when at most two source vectors
7084 // are involved.
7085 if (Sources.size() > 2)
7086 return SDValue();
7088 // Find out the smallest element size among result and two sources, and use
7089 // it as element size to build the shuffle_vector.
7090 EVT SmallestEltTy = VT.getVectorElementType();
7091 for (auto &Source : Sources) {
7092 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7093 if (SrcEltTy.bitsLT(SmallestEltTy))
7094 SmallestEltTy = SrcEltTy;
7096 unsigned ResMultiplier =
7097 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7098 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7099 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7101 // If the source vector is too wide or too narrow, we may nevertheless be able
7102 // to construct a compatible shuffle either by concatenating it with UNDEF or
7103 // extracting a suitable range of elements.
7104 for (auto &Src : Sources) {
7105 EVT SrcVT = Src.ShuffleVec.getValueType();
7107 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7108 continue;
7110 // This stage of the search produces a source with the same element type as
7111 // the original, but with a total width matching the BUILD_VECTOR output.
7112 EVT EltVT = SrcVT.getVectorElementType();
7113 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7114 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7116 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7117 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7118 return SDValue();
7119 // We can pad out the smaller vector for free, so if it's part of a
7120 // shuffle...
7121 Src.ShuffleVec =
7122 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7123 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7124 continue;
7127 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7128 return SDValue();
7130 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7131 // Span too large for a VEXT to cope
7132 return SDValue();
7135 if (Src.MinElt >= NumSrcElts) {
7136 // The extraction can just take the second half
7137 Src.ShuffleVec =
7138 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7139 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7140 Src.WindowBase = -NumSrcElts;
7141 } else if (Src.MaxElt < NumSrcElts) {
7142 // The extraction can just take the first half
7143 Src.ShuffleVec =
7144 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7145 DAG.getConstant(0, dl, MVT::i32));
7146 } else {
7147 // An actual VEXT is needed
7148 SDValue VEXTSrc1 =
7149 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7150 DAG.getConstant(0, dl, MVT::i32));
7151 SDValue VEXTSrc2 =
7152 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7153 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7155 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7156 VEXTSrc2,
7157 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7158 Src.WindowBase = -Src.MinElt;
7162 // Another possible incompatibility occurs from the vector element types. We
7163 // can fix this by bitcasting the source vectors to the same type we intend
7164 // for the shuffle.
7165 for (auto &Src : Sources) {
7166 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7167 if (SrcEltTy == SmallestEltTy)
7168 continue;
7169 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7170 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7171 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7172 Src.WindowBase *= Src.WindowScale;
7175 // Final sanity check before we try to actually produce a shuffle.
7176 LLVM_DEBUG(for (auto Src
7177 : Sources)
7178 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7180 // The stars all align, our next step is to produce the mask for the shuffle.
7181 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7182 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7183 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7184 SDValue Entry = Op.getOperand(i);
7185 if (Entry.isUndef())
7186 continue;
7188 auto Src = llvm::find(Sources, Entry.getOperand(0));
7189 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7191 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7192 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7193 // segment.
7194 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7195 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7196 VT.getScalarSizeInBits());
7197 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7199 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7200 // starting at the appropriate offset.
7201 int *LaneMask = &Mask[i * ResMultiplier];
7203 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7204 ExtractBase += NumElts * (Src - Sources.begin());
7205 for (int j = 0; j < LanesDefined; ++j)
7206 LaneMask[j] = ExtractBase + j;
7209 // Final check before we try to produce nonsense...
7210 if (!isShuffleMaskLegal(Mask, ShuffleVT))
7211 return SDValue();
7213 // We can't handle more than two sources. This should have already
7214 // been checked before this point.
7215 assert(Sources.size() <= 2 && "Too many sources!");
7217 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7218 for (unsigned i = 0; i < Sources.size(); ++i)
7219 ShuffleOps[i] = Sources[i].ShuffleVec;
7221 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7222 ShuffleOps[1], Mask);
7223 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7226 enum ShuffleOpCodes {
7227 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7228 OP_VREV,
7229 OP_VDUP0,
7230 OP_VDUP1,
7231 OP_VDUP2,
7232 OP_VDUP3,
7233 OP_VEXT1,
7234 OP_VEXT2,
7235 OP_VEXT3,
7236 OP_VUZPL, // VUZP, left result
7237 OP_VUZPR, // VUZP, right result
7238 OP_VZIPL, // VZIP, left result
7239 OP_VZIPR, // VZIP, right result
7240 OP_VTRNL, // VTRN, left result
7241 OP_VTRNR // VTRN, right result
7244 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7245 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7246 switch (OpNum) {
7247 case OP_COPY:
7248 case OP_VREV:
7249 case OP_VDUP0:
7250 case OP_VDUP1:
7251 case OP_VDUP2:
7252 case OP_VDUP3:
7253 return true;
7255 return false;
7258 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7259 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7260 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7261 /// are assumed to be legal.
7262 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7263 if (VT.getVectorNumElements() == 4 &&
7264 (VT.is128BitVector() || VT.is64BitVector())) {
7265 unsigned PFIndexes[4];
7266 for (unsigned i = 0; i != 4; ++i) {
7267 if (M[i] < 0)
7268 PFIndexes[i] = 8;
7269 else
7270 PFIndexes[i] = M[i];
7273 // Compute the index in the perfect shuffle table.
7274 unsigned PFTableIndex =
7275 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7276 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7277 unsigned Cost = (PFEntry >> 30);
7279 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7280 return true;
7283 bool ReverseVEXT, isV_UNDEF;
7284 unsigned Imm, WhichResult;
7286 unsigned EltSize = VT.getScalarSizeInBits();
7287 if (EltSize >= 32 ||
7288 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7289 isVREVMask(M, VT, 64) ||
7290 isVREVMask(M, VT, 32) ||
7291 isVREVMask(M, VT, 16))
7292 return true;
7293 else if (Subtarget->hasNEON() &&
7294 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7295 isVTBLMask(M, VT) ||
7296 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7297 return true;
7298 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7299 isReverseMask(M, VT))
7300 return true;
7301 else
7302 return false;
7305 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7306 /// the specified operations to build the shuffle.
7307 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7308 SDValue RHS, SelectionDAG &DAG,
7309 const SDLoc &dl) {
7310 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7311 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7312 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7314 if (OpNum == OP_COPY) {
7315 if (LHSID == (1*9+2)*9+3) return LHS;
7316 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7317 return RHS;
7320 SDValue OpLHS, OpRHS;
7321 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7322 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7323 EVT VT = OpLHS.getValueType();
7325 switch (OpNum) {
7326 default: llvm_unreachable("Unknown shuffle opcode!");
7327 case OP_VREV:
7328 // VREV divides the vector in half and swaps within the half.
7329 if (VT.getVectorElementType() == MVT::i32 ||
7330 VT.getVectorElementType() == MVT::f32)
7331 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7332 // vrev <4 x i16> -> VREV32
7333 if (VT.getVectorElementType() == MVT::i16)
7334 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7335 // vrev <4 x i8> -> VREV16
7336 assert(VT.getVectorElementType() == MVT::i8);
7337 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7338 case OP_VDUP0:
7339 case OP_VDUP1:
7340 case OP_VDUP2:
7341 case OP_VDUP3:
7342 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7343 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7344 case OP_VEXT1:
7345 case OP_VEXT2:
7346 case OP_VEXT3:
7347 return DAG.getNode(ARMISD::VEXT, dl, VT,
7348 OpLHS, OpRHS,
7349 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7350 case OP_VUZPL:
7351 case OP_VUZPR:
7352 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7353 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7354 case OP_VZIPL:
7355 case OP_VZIPR:
7356 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7357 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7358 case OP_VTRNL:
7359 case OP_VTRNR:
7360 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7361 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7365 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7366 ArrayRef<int> ShuffleMask,
7367 SelectionDAG &DAG) {
7368 // Check to see if we can use the VTBL instruction.
7369 SDValue V1 = Op.getOperand(0);
7370 SDValue V2 = Op.getOperand(1);
7371 SDLoc DL(Op);
7373 SmallVector<SDValue, 8> VTBLMask;
7374 for (ArrayRef<int>::iterator
7375 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7376 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7378 if (V2.getNode()->isUndef())
7379 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7380 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7382 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7383 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7386 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7387 SelectionDAG &DAG) {
7388 SDLoc DL(Op);
7389 SDValue OpLHS = Op.getOperand(0);
7390 EVT VT = OpLHS.getValueType();
7392 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7393 "Expect an v8i16/v16i8 type");
7394 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7395 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7396 // extract the first 8 bytes into the top double word and the last 8 bytes
7397 // into the bottom double word. The v8i16 case is similar.
7398 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7399 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7400 DAG.getConstant(ExtractNum, DL, MVT::i32));
7403 static EVT getVectorTyFromPredicateVector(EVT VT) {
7404 switch (VT.getSimpleVT().SimpleTy) {
7405 case MVT::v4i1:
7406 return MVT::v4i32;
7407 case MVT::v8i1:
7408 return MVT::v8i16;
7409 case MVT::v16i1:
7410 return MVT::v16i8;
7411 default:
7412 llvm_unreachable("Unexpected vector predicate type");
7416 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7417 SelectionDAG &DAG) {
7418 // Converting from boolean predicates to integers involves creating a vector
7419 // of all ones or all zeroes and selecting the lanes based upon the real
7420 // predicate.
7421 SDValue AllOnes =
7422 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7423 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7425 SDValue AllZeroes =
7426 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7427 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7429 // Get full vector type from predicate type
7430 EVT NewVT = getVectorTyFromPredicateVector(VT);
7432 SDValue RecastV1;
7433 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7434 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7435 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7436 // since we know in hardware the sizes are really the same.
7437 if (VT != MVT::v16i1)
7438 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7439 else
7440 RecastV1 = Pred;
7442 // Select either all ones or zeroes depending upon the real predicate bits.
7443 SDValue PredAsVector =
7444 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7446 // Recast our new predicate-as-integer v16i8 vector into something
7447 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7448 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7451 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7452 const ARMSubtarget *ST) {
7453 EVT VT = Op.getValueType();
7454 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7455 ArrayRef<int> ShuffleMask = SVN->getMask();
7457 assert(ST->hasMVEIntegerOps() &&
7458 "No support for vector shuffle of boolean predicates");
7460 SDValue V1 = Op.getOperand(0);
7461 SDLoc dl(Op);
7462 if (isReverseMask(ShuffleMask, VT)) {
7463 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7464 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7465 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7466 DAG.getConstant(16, dl, MVT::i32));
7467 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7470 // Until we can come up with optimised cases for every single vector
7471 // shuffle in existence we have chosen the least painful strategy. This is
7472 // to essentially promote the boolean predicate to a 8-bit integer, where
7473 // each predicate represents a byte. Then we fall back on a normal integer
7474 // vector shuffle and convert the result back into a predicate vector. In
7475 // many cases the generated code might be even better than scalar code
7476 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7477 // fields in a register into 8 other arbitrary 2-bit fields!
7478 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7479 EVT NewVT = PredAsVector.getValueType();
7481 // Do the shuffle!
7482 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7483 DAG.getUNDEF(NewVT), ShuffleMask);
7485 // Now return the result of comparing the shuffled vector with zero,
7486 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7487 return DAG.getNode(ARMISD::VCNEZ, dl, VT, Shuffled);
7490 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7491 const ARMSubtarget *ST) {
7492 SDValue V1 = Op.getOperand(0);
7493 SDValue V2 = Op.getOperand(1);
7494 SDLoc dl(Op);
7495 EVT VT = Op.getValueType();
7496 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7497 unsigned EltSize = VT.getScalarSizeInBits();
7499 if (ST->hasMVEIntegerOps() && EltSize == 1)
7500 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7502 // Convert shuffles that are directly supported on NEON to target-specific
7503 // DAG nodes, instead of keeping them as shuffles and matching them again
7504 // during code selection. This is more efficient and avoids the possibility
7505 // of inconsistencies between legalization and selection.
7506 // FIXME: floating-point vectors should be canonicalized to integer vectors
7507 // of the same time so that they get CSEd properly.
7508 ArrayRef<int> ShuffleMask = SVN->getMask();
7510 if (EltSize <= 32) {
7511 if (SVN->isSplat()) {
7512 int Lane = SVN->getSplatIndex();
7513 // If this is undef splat, generate it via "just" vdup, if possible.
7514 if (Lane == -1) Lane = 0;
7516 // Test if V1 is a SCALAR_TO_VECTOR.
7517 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7518 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7520 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7521 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7522 // reaches it).
7523 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7524 !isa<ConstantSDNode>(V1.getOperand(0))) {
7525 bool IsScalarToVector = true;
7526 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7527 if (!V1.getOperand(i).isUndef()) {
7528 IsScalarToVector = false;
7529 break;
7531 if (IsScalarToVector)
7532 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7534 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7535 DAG.getConstant(Lane, dl, MVT::i32));
7538 bool ReverseVEXT = false;
7539 unsigned Imm = 0;
7540 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7541 if (ReverseVEXT)
7542 std::swap(V1, V2);
7543 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7544 DAG.getConstant(Imm, dl, MVT::i32));
7547 if (isVREVMask(ShuffleMask, VT, 64))
7548 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7549 if (isVREVMask(ShuffleMask, VT, 32))
7550 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7551 if (isVREVMask(ShuffleMask, VT, 16))
7552 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7554 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7555 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7556 DAG.getConstant(Imm, dl, MVT::i32));
7559 // Check for Neon shuffles that modify both input vectors in place.
7560 // If both results are used, i.e., if there are two shuffles with the same
7561 // source operands and with masks corresponding to both results of one of
7562 // these operations, DAG memoization will ensure that a single node is
7563 // used for both shuffles.
7564 unsigned WhichResult = 0;
7565 bool isV_UNDEF = false;
7566 if (ST->hasNEON()) {
7567 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7568 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7569 if (isV_UNDEF)
7570 V2 = V1;
7571 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7572 .getValue(WhichResult);
7576 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7577 // shuffles that produce a result larger than their operands with:
7578 // shuffle(concat(v1, undef), concat(v2, undef))
7579 // ->
7580 // shuffle(concat(v1, v2), undef)
7581 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7583 // This is useful in the general case, but there are special cases where
7584 // native shuffles produce larger results: the two-result ops.
7586 // Look through the concat when lowering them:
7587 // shuffle(concat(v1, v2), undef)
7588 // ->
7589 // concat(VZIP(v1, v2):0, :1)
7591 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7592 SDValue SubV1 = V1->getOperand(0);
7593 SDValue SubV2 = V1->getOperand(1);
7594 EVT SubVT = SubV1.getValueType();
7596 // We expect these to have been canonicalized to -1.
7597 assert(llvm::all_of(ShuffleMask, [&](int i) {
7598 return i < (int)VT.getVectorNumElements();
7599 }) && "Unexpected shuffle index into UNDEF operand!");
7601 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7602 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7603 if (isV_UNDEF)
7604 SubV2 = SubV1;
7605 assert((WhichResult == 0) &&
7606 "In-place shuffle of concat can only have one result!");
7607 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7608 SubV1, SubV2);
7609 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7610 Res.getValue(1));
7615 // If the shuffle is not directly supported and it has 4 elements, use
7616 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7617 unsigned NumElts = VT.getVectorNumElements();
7618 if (NumElts == 4) {
7619 unsigned PFIndexes[4];
7620 for (unsigned i = 0; i != 4; ++i) {
7621 if (ShuffleMask[i] < 0)
7622 PFIndexes[i] = 8;
7623 else
7624 PFIndexes[i] = ShuffleMask[i];
7627 // Compute the index in the perfect shuffle table.
7628 unsigned PFTableIndex =
7629 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7630 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7631 unsigned Cost = (PFEntry >> 30);
7633 if (Cost <= 4) {
7634 if (ST->hasNEON())
7635 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7636 else if (isLegalMVEShuffleOp(PFEntry)) {
7637 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7638 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7639 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7640 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7641 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7642 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7647 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7648 if (EltSize >= 32) {
7649 // Do the expansion with floating-point types, since that is what the VFP
7650 // registers are defined to use, and since i64 is not legal.
7651 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7652 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7653 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7654 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7655 SmallVector<SDValue, 8> Ops;
7656 for (unsigned i = 0; i < NumElts; ++i) {
7657 if (ShuffleMask[i] < 0)
7658 Ops.push_back(DAG.getUNDEF(EltVT));
7659 else
7660 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7661 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7662 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7663 dl, MVT::i32)));
7665 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7666 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7669 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7670 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7672 if (ST->hasNEON() && VT == MVT::v8i8)
7673 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7674 return NewOp;
7676 return SDValue();
7679 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7680 const ARMSubtarget *ST) {
7681 EVT VecVT = Op.getOperand(0).getValueType();
7682 SDLoc dl(Op);
7684 assert(ST->hasMVEIntegerOps() &&
7685 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7687 SDValue Conv =
7688 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7689 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7690 unsigned LaneWidth =
7691 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7692 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7693 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7694 Op.getOperand(1), DAG.getValueType(MVT::i1));
7695 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7696 DAG.getConstant(~Mask, dl, MVT::i32));
7697 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7700 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7701 SelectionDAG &DAG) const {
7702 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7703 SDValue Lane = Op.getOperand(2);
7704 if (!isa<ConstantSDNode>(Lane))
7705 return SDValue();
7707 SDValue Elt = Op.getOperand(1);
7708 EVT EltVT = Elt.getValueType();
7710 if (Subtarget->hasMVEIntegerOps() &&
7711 Op.getValueType().getScalarSizeInBits() == 1)
7712 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7714 if (getTypeAction(*DAG.getContext(), EltVT) ==
7715 TargetLowering::TypePromoteFloat) {
7716 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7717 // but the type system will try to do that if we don't intervene.
7718 // Reinterpret any such vector-element insertion as one with the
7719 // corresponding integer types.
7721 SDLoc dl(Op);
7723 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7724 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7725 TargetLowering::TypePromoteFloat);
7727 SDValue VecIn = Op.getOperand(0);
7728 EVT VecVT = VecIn.getValueType();
7729 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7730 VecVT.getVectorNumElements());
7732 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7733 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7734 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7735 IVecIn, IElt, Lane);
7736 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7739 return Op;
7742 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7743 const ARMSubtarget *ST) {
7744 EVT VecVT = Op.getOperand(0).getValueType();
7745 SDLoc dl(Op);
7747 assert(ST->hasMVEIntegerOps() &&
7748 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7750 SDValue Conv =
7751 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7752 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7753 unsigned LaneWidth =
7754 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7755 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7756 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7757 return Shift;
7760 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7761 const ARMSubtarget *ST) {
7762 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7763 SDValue Lane = Op.getOperand(1);
7764 if (!isa<ConstantSDNode>(Lane))
7765 return SDValue();
7767 SDValue Vec = Op.getOperand(0);
7768 EVT VT = Vec.getValueType();
7770 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7771 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7773 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7774 SDLoc dl(Op);
7775 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7778 return Op;
7781 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7782 const ARMSubtarget *ST) {
7783 SDValue V1 = Op.getOperand(0);
7784 SDValue V2 = Op.getOperand(1);
7785 SDLoc dl(Op);
7786 EVT VT = Op.getValueType();
7787 EVT Op1VT = V1.getValueType();
7788 EVT Op2VT = V2.getValueType();
7789 unsigned NumElts = VT.getVectorNumElements();
7791 assert(Op1VT == Op2VT && "Operand types don't match!");
7792 assert(VT.getScalarSizeInBits() == 1 &&
7793 "Unexpected custom CONCAT_VECTORS lowering");
7794 assert(ST->hasMVEIntegerOps() &&
7795 "CONCAT_VECTORS lowering only supported for MVE");
7797 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7798 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7800 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7801 // promoted to v8i16, etc.
7803 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7805 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7806 // to be the right size for the destination. For example, if Op1 is v4i1 then
7807 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7808 // which when promoted is v8i16. That means each i32 element from Op1 needs
7809 // truncating to i16 and inserting in the result.
7810 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7811 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7812 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7813 EVT NewVT = NewV.getValueType();
7814 EVT ConcatVT = ConVec.getValueType();
7815 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7816 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7817 DAG.getIntPtrConstant(i, dl));
7818 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7819 DAG.getConstant(j, dl, MVT::i32));
7821 return ConVec;
7823 unsigned j = 0;
7824 ConVec = ExractInto(NewV1, ConVec, j);
7825 ConVec = ExractInto(NewV2, ConVec, j);
7827 // Now return the result of comparing the subvector with zero,
7828 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7829 return DAG.getNode(ARMISD::VCNEZ, dl, VT, ConVec);
7832 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
7833 const ARMSubtarget *ST) {
7834 EVT VT = Op->getValueType(0);
7835 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7836 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
7838 // The only time a CONCAT_VECTORS operation can have legal types is when
7839 // two 64-bit vectors are concatenated to a 128-bit vector.
7840 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7841 "unexpected CONCAT_VECTORS");
7842 SDLoc dl(Op);
7843 SDValue Val = DAG.getUNDEF(MVT::v2f64);
7844 SDValue Op0 = Op.getOperand(0);
7845 SDValue Op1 = Op.getOperand(1);
7846 if (!Op0.isUndef())
7847 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7848 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7849 DAG.getIntPtrConstant(0, dl));
7850 if (!Op1.isUndef())
7851 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7852 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7853 DAG.getIntPtrConstant(1, dl));
7854 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7857 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
7858 const ARMSubtarget *ST) {
7859 SDValue V1 = Op.getOperand(0);
7860 SDValue V2 = Op.getOperand(1);
7861 SDLoc dl(Op);
7862 EVT VT = Op.getValueType();
7863 EVT Op1VT = V1.getValueType();
7864 unsigned NumElts = VT.getVectorNumElements();
7865 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
7867 assert(VT.getScalarSizeInBits() == 1 &&
7868 "Unexpected custom EXTRACT_SUBVECTOR lowering");
7869 assert(ST->hasMVEIntegerOps() &&
7870 "EXTRACT_SUBVECTOR lowering only supported for MVE");
7872 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7874 // We now have Op1 promoted to a vector of integers, where v8i1 gets
7875 // promoted to v8i16, etc.
7877 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7879 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
7880 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
7881 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
7882 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
7883 DAG.getIntPtrConstant(i, dl));
7884 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
7885 DAG.getConstant(j, dl, MVT::i32));
7888 // Now return the result of comparing the subvector with zero,
7889 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7890 return DAG.getNode(ARMISD::VCNEZ, dl, VT, SubVec);
7893 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7894 /// element has been zero/sign-extended, depending on the isSigned parameter,
7895 /// from an integer type half its size.
7896 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7897 bool isSigned) {
7898 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7899 EVT VT = N->getValueType(0);
7900 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7901 SDNode *BVN = N->getOperand(0).getNode();
7902 if (BVN->getValueType(0) != MVT::v4i32 ||
7903 BVN->getOpcode() != ISD::BUILD_VECTOR)
7904 return false;
7905 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7906 unsigned HiElt = 1 - LoElt;
7907 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7908 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7909 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7910 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7911 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7912 return false;
7913 if (isSigned) {
7914 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7915 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7916 return true;
7917 } else {
7918 if (Hi0->isNullValue() && Hi1->isNullValue())
7919 return true;
7921 return false;
7924 if (N->getOpcode() != ISD::BUILD_VECTOR)
7925 return false;
7927 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7928 SDNode *Elt = N->getOperand(i).getNode();
7929 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7930 unsigned EltSize = VT.getScalarSizeInBits();
7931 unsigned HalfSize = EltSize / 2;
7932 if (isSigned) {
7933 if (!isIntN(HalfSize, C->getSExtValue()))
7934 return false;
7935 } else {
7936 if (!isUIntN(HalfSize, C->getZExtValue()))
7937 return false;
7939 continue;
7941 return false;
7944 return true;
7947 /// isSignExtended - Check if a node is a vector value that is sign-extended
7948 /// or a constant BUILD_VECTOR with sign-extended elements.
7949 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7950 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7951 return true;
7952 if (isExtendedBUILD_VECTOR(N, DAG, true))
7953 return true;
7954 return false;
7957 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7958 /// or a constant BUILD_VECTOR with zero-extended elements.
7959 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7960 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7961 return true;
7962 if (isExtendedBUILD_VECTOR(N, DAG, false))
7963 return true;
7964 return false;
7967 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7968 if (OrigVT.getSizeInBits() >= 64)
7969 return OrigVT;
7971 assert(OrigVT.isSimple() && "Expecting a simple value type");
7973 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7974 switch (OrigSimpleTy) {
7975 default: llvm_unreachable("Unexpected Vector Type");
7976 case MVT::v2i8:
7977 case MVT::v2i16:
7978 return MVT::v2i32;
7979 case MVT::v4i8:
7980 return MVT::v4i16;
7984 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7985 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7986 /// We insert the required extension here to get the vector to fill a D register.
7987 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7988 const EVT &OrigTy,
7989 const EVT &ExtTy,
7990 unsigned ExtOpcode) {
7991 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7992 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7993 // 64-bits we need to insert a new extension so that it will be 64-bits.
7994 assert(ExtTy.is128BitVector() && "Unexpected extension size");
7995 if (OrigTy.getSizeInBits() >= 64)
7996 return N;
7998 // Must extend size to at least 64 bits to be used as an operand for VMULL.
7999 EVT NewVT = getExtensionTo64Bits(OrigTy);
8001 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8004 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8005 /// does not do any sign/zero extension. If the original vector is less
8006 /// than 64 bits, an appropriate extension will be added after the load to
8007 /// reach a total size of 64 bits. We have to add the extension separately
8008 /// because ARM does not have a sign/zero extending load for vectors.
8009 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8010 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8012 // The load already has the right type.
8013 if (ExtendedTy == LD->getMemoryVT())
8014 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8015 LD->getBasePtr(), LD->getPointerInfo(),
8016 LD->getAlignment(), LD->getMemOperand()->getFlags());
8018 // We need to create a zextload/sextload. We cannot just create a load
8019 // followed by a zext/zext node because LowerMUL is also run during normal
8020 // operation legalization where we can't create illegal types.
8021 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8022 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8023 LD->getMemoryVT(), LD->getAlignment(),
8024 LD->getMemOperand()->getFlags());
8027 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8028 /// extending load, or BUILD_VECTOR with extended elements, return the
8029 /// unextended value. The unextended vector should be 64 bits so that it can
8030 /// be used as an operand to a VMULL instruction. If the original vector size
8031 /// before extension is less than 64 bits we add a an extension to resize
8032 /// the vector to 64 bits.
8033 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8034 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8035 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8036 N->getOperand(0)->getValueType(0),
8037 N->getValueType(0),
8038 N->getOpcode());
8040 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8041 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8042 "Expected extending load");
8044 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8045 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8046 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8047 SDValue extLoad =
8048 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8049 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8051 return newLoad;
8054 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8055 // have been legalized as a BITCAST from v4i32.
8056 if (N->getOpcode() == ISD::BITCAST) {
8057 SDNode *BVN = N->getOperand(0).getNode();
8058 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8059 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8060 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8061 return DAG.getBuildVector(
8062 MVT::v2i32, SDLoc(N),
8063 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8065 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8066 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8067 EVT VT = N->getValueType(0);
8068 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8069 unsigned NumElts = VT.getVectorNumElements();
8070 MVT TruncVT = MVT::getIntegerVT(EltSize);
8071 SmallVector<SDValue, 8> Ops;
8072 SDLoc dl(N);
8073 for (unsigned i = 0; i != NumElts; ++i) {
8074 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8075 const APInt &CInt = C->getAPIntValue();
8076 // Element types smaller than 32 bits are not legal, so use i32 elements.
8077 // The values are implicitly truncated so sext vs. zext doesn't matter.
8078 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8080 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8083 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8084 unsigned Opcode = N->getOpcode();
8085 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8086 SDNode *N0 = N->getOperand(0).getNode();
8087 SDNode *N1 = N->getOperand(1).getNode();
8088 return N0->hasOneUse() && N1->hasOneUse() &&
8089 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8091 return false;
8094 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8095 unsigned Opcode = N->getOpcode();
8096 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8097 SDNode *N0 = N->getOperand(0).getNode();
8098 SDNode *N1 = N->getOperand(1).getNode();
8099 return N0->hasOneUse() && N1->hasOneUse() &&
8100 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8102 return false;
8105 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8106 // Multiplications are only custom-lowered for 128-bit vectors so that
8107 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8108 EVT VT = Op.getValueType();
8109 assert(VT.is128BitVector() && VT.isInteger() &&
8110 "unexpected type for custom-lowering ISD::MUL");
8111 SDNode *N0 = Op.getOperand(0).getNode();
8112 SDNode *N1 = Op.getOperand(1).getNode();
8113 unsigned NewOpc = 0;
8114 bool isMLA = false;
8115 bool isN0SExt = isSignExtended(N0, DAG);
8116 bool isN1SExt = isSignExtended(N1, DAG);
8117 if (isN0SExt && isN1SExt)
8118 NewOpc = ARMISD::VMULLs;
8119 else {
8120 bool isN0ZExt = isZeroExtended(N0, DAG);
8121 bool isN1ZExt = isZeroExtended(N1, DAG);
8122 if (isN0ZExt && isN1ZExt)
8123 NewOpc = ARMISD::VMULLu;
8124 else if (isN1SExt || isN1ZExt) {
8125 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8126 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8127 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8128 NewOpc = ARMISD::VMULLs;
8129 isMLA = true;
8130 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8131 NewOpc = ARMISD::VMULLu;
8132 isMLA = true;
8133 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8134 std::swap(N0, N1);
8135 NewOpc = ARMISD::VMULLu;
8136 isMLA = true;
8140 if (!NewOpc) {
8141 if (VT == MVT::v2i64)
8142 // Fall through to expand this. It is not legal.
8143 return SDValue();
8144 else
8145 // Other vector multiplications are legal.
8146 return Op;
8150 // Legalize to a VMULL instruction.
8151 SDLoc DL(Op);
8152 SDValue Op0;
8153 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8154 if (!isMLA) {
8155 Op0 = SkipExtensionForVMULL(N0, DAG);
8156 assert(Op0.getValueType().is64BitVector() &&
8157 Op1.getValueType().is64BitVector() &&
8158 "unexpected types for extended operands to VMULL");
8159 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8162 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8163 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8164 // vmull q0, d4, d6
8165 // vmlal q0, d5, d6
8166 // is faster than
8167 // vaddl q0, d4, d5
8168 // vmovl q1, d6
8169 // vmul q0, q0, q1
8170 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8171 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8172 EVT Op1VT = Op1.getValueType();
8173 return DAG.getNode(N0->getOpcode(), DL, VT,
8174 DAG.getNode(NewOpc, DL, VT,
8175 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8176 DAG.getNode(NewOpc, DL, VT,
8177 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8180 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8181 SelectionDAG &DAG) {
8182 // TODO: Should this propagate fast-math-flags?
8184 // Convert to float
8185 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8186 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8187 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8188 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8189 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8190 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8191 // Get reciprocal estimate.
8192 // float4 recip = vrecpeq_f32(yf);
8193 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8194 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8196 // Because char has a smaller range than uchar, we can actually get away
8197 // without any newton steps. This requires that we use a weird bias
8198 // of 0xb000, however (again, this has been exhaustively tested).
8199 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8200 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8201 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8202 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8203 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8204 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8205 // Convert back to short.
8206 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8207 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8208 return X;
8211 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8212 SelectionDAG &DAG) {
8213 // TODO: Should this propagate fast-math-flags?
8215 SDValue N2;
8216 // Convert to float.
8217 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8218 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8219 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8220 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8221 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8222 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8224 // Use reciprocal estimate and one refinement step.
8225 // float4 recip = vrecpeq_f32(yf);
8226 // recip *= vrecpsq_f32(yf, recip);
8227 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8228 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8229 N1);
8230 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8231 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8232 N1, N2);
8233 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8234 // Because short has a smaller range than ushort, we can actually get away
8235 // with only a single newton step. This requires that we use a weird bias
8236 // of 89, however (again, this has been exhaustively tested).
8237 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8238 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8239 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8240 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8241 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8242 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8243 // Convert back to integer and return.
8244 // return vmovn_s32(vcvt_s32_f32(result));
8245 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8246 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8247 return N0;
8250 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8251 const ARMSubtarget *ST) {
8252 EVT VT = Op.getValueType();
8253 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8254 "unexpected type for custom-lowering ISD::SDIV");
8256 SDLoc dl(Op);
8257 SDValue N0 = Op.getOperand(0);
8258 SDValue N1 = Op.getOperand(1);
8259 SDValue N2, N3;
8261 if (VT == MVT::v8i8) {
8262 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8263 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8265 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8266 DAG.getIntPtrConstant(4, dl));
8267 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8268 DAG.getIntPtrConstant(4, dl));
8269 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8270 DAG.getIntPtrConstant(0, dl));
8271 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8272 DAG.getIntPtrConstant(0, dl));
8274 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8275 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8277 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8278 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8280 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8281 return N0;
8283 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8286 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8287 const ARMSubtarget *ST) {
8288 // TODO: Should this propagate fast-math-flags?
8289 EVT VT = Op.getValueType();
8290 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8291 "unexpected type for custom-lowering ISD::UDIV");
8293 SDLoc dl(Op);
8294 SDValue N0 = Op.getOperand(0);
8295 SDValue N1 = Op.getOperand(1);
8296 SDValue N2, N3;
8298 if (VT == MVT::v8i8) {
8299 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8300 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8302 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8303 DAG.getIntPtrConstant(4, dl));
8304 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8305 DAG.getIntPtrConstant(4, dl));
8306 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8307 DAG.getIntPtrConstant(0, dl));
8308 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8309 DAG.getIntPtrConstant(0, dl));
8311 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8312 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8314 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8315 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8317 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8318 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8319 MVT::i32),
8320 N0);
8321 return N0;
8324 // v4i16 sdiv ... Convert to float.
8325 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8326 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8327 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8328 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8329 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8330 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8332 // Use reciprocal estimate and two refinement steps.
8333 // float4 recip = vrecpeq_f32(yf);
8334 // recip *= vrecpsq_f32(yf, recip);
8335 // recip *= vrecpsq_f32(yf, recip);
8336 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8337 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8338 BN1);
8339 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8340 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8341 BN1, N2);
8342 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8343 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8344 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8345 BN1, N2);
8346 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8347 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8348 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8349 // and that it will never cause us to return an answer too large).
8350 // float4 result = as_float4(as_int4(xf*recip) + 2);
8351 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8352 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8353 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8354 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8355 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8356 // Convert back to integer and return.
8357 // return vmovn_u32(vcvt_s32_f32(result));
8358 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8359 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8360 return N0;
8363 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8364 SDNode *N = Op.getNode();
8365 EVT VT = N->getValueType(0);
8366 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8368 SDValue Carry = Op.getOperand(2);
8370 SDLoc DL(Op);
8372 SDValue Result;
8373 if (Op.getOpcode() == ISD::ADDCARRY) {
8374 // This converts the boolean value carry into the carry flag.
8375 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8377 // Do the addition proper using the carry flag we wanted.
8378 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8379 Op.getOperand(1), Carry);
8381 // Now convert the carry flag into a boolean value.
8382 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8383 } else {
8384 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8385 // have to invert the carry first.
8386 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8387 DAG.getConstant(1, DL, MVT::i32), Carry);
8388 // This converts the boolean value carry into the carry flag.
8389 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8391 // Do the subtraction proper using the carry flag we wanted.
8392 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8393 Op.getOperand(1), Carry);
8395 // Now convert the carry flag into a boolean value.
8396 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8397 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8398 // by ISD::SUBCARRY, so compute 1 - C.
8399 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8400 DAG.getConstant(1, DL, MVT::i32), Carry);
8403 // Return both values.
8404 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8407 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8408 assert(Subtarget->isTargetDarwin());
8410 // For iOS, we want to call an alternative entry point: __sincos_stret,
8411 // return values are passed via sret.
8412 SDLoc dl(Op);
8413 SDValue Arg = Op.getOperand(0);
8414 EVT ArgVT = Arg.getValueType();
8415 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8416 auto PtrVT = getPointerTy(DAG.getDataLayout());
8418 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8421 // Pair of floats / doubles used to pass the result.
8422 Type *RetTy = StructType::get(ArgTy, ArgTy);
8423 auto &DL = DAG.getDataLayout();
8425 ArgListTy Args;
8426 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8427 SDValue SRet;
8428 if (ShouldUseSRet) {
8429 // Create stack object for sret.
8430 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8431 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8432 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8433 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8435 ArgListEntry Entry;
8436 Entry.Node = SRet;
8437 Entry.Ty = RetTy->getPointerTo();
8438 Entry.IsSExt = false;
8439 Entry.IsZExt = false;
8440 Entry.IsSRet = true;
8441 Args.push_back(Entry);
8442 RetTy = Type::getVoidTy(*DAG.getContext());
8445 ArgListEntry Entry;
8446 Entry.Node = Arg;
8447 Entry.Ty = ArgTy;
8448 Entry.IsSExt = false;
8449 Entry.IsZExt = false;
8450 Args.push_back(Entry);
8452 RTLIB::Libcall LC =
8453 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8454 const char *LibcallName = getLibcallName(LC);
8455 CallingConv::ID CC = getLibcallCallingConv(LC);
8456 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8458 TargetLowering::CallLoweringInfo CLI(DAG);
8459 CLI.setDebugLoc(dl)
8460 .setChain(DAG.getEntryNode())
8461 .setCallee(CC, RetTy, Callee, std::move(Args))
8462 .setDiscardResult(ShouldUseSRet);
8463 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8465 if (!ShouldUseSRet)
8466 return CallResult.first;
8468 SDValue LoadSin =
8469 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8471 // Address of cos field.
8472 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8473 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8474 SDValue LoadCos =
8475 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8477 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8478 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8479 LoadSin.getValue(0), LoadCos.getValue(0));
8482 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8483 bool Signed,
8484 SDValue &Chain) const {
8485 EVT VT = Op.getValueType();
8486 assert((VT == MVT::i32 || VT == MVT::i64) &&
8487 "unexpected type for custom lowering DIV");
8488 SDLoc dl(Op);
8490 const auto &DL = DAG.getDataLayout();
8491 const auto &TLI = DAG.getTargetLoweringInfo();
8493 const char *Name = nullptr;
8494 if (Signed)
8495 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8496 else
8497 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8499 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8501 ARMTargetLowering::ArgListTy Args;
8503 for (auto AI : {1, 0}) {
8504 ArgListEntry Arg;
8505 Arg.Node = Op.getOperand(AI);
8506 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8507 Args.push_back(Arg);
8510 CallLoweringInfo CLI(DAG);
8511 CLI.setDebugLoc(dl)
8512 .setChain(Chain)
8513 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8514 ES, std::move(Args));
8516 return LowerCallTo(CLI).first;
8519 // This is a code size optimisation: return the original SDIV node to
8520 // DAGCombiner when we don't want to expand SDIV into a sequence of
8521 // instructions, and an empty node otherwise which will cause the
8522 // SDIV to be expanded in DAGCombine.
8523 SDValue
8524 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8525 SelectionDAG &DAG,
8526 SmallVectorImpl<SDNode *> &Created) const {
8527 // TODO: Support SREM
8528 if (N->getOpcode() != ISD::SDIV)
8529 return SDValue();
8531 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8532 const bool MinSize = ST.hasMinSize();
8533 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8534 : ST.hasDivideInARMMode();
8536 // Don't touch vector types; rewriting this may lead to scalarizing
8537 // the int divs.
8538 if (N->getOperand(0).getValueType().isVector())
8539 return SDValue();
8541 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8542 // hwdiv support for this to be really profitable.
8543 if (!(MinSize && HasDivide))
8544 return SDValue();
8546 // ARM mode is a bit simpler than Thumb: we can handle large power
8547 // of 2 immediates with 1 mov instruction; no further checks required,
8548 // just return the sdiv node.
8549 if (!ST.isThumb())
8550 return SDValue(N, 0);
8552 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8553 // and thus lose the code size benefits of a MOVS that requires only 2.
8554 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8555 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8556 if (Divisor.sgt(128))
8557 return SDValue();
8559 return SDValue(N, 0);
8562 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8563 bool Signed) const {
8564 assert(Op.getValueType() == MVT::i32 &&
8565 "unexpected type for custom lowering DIV");
8566 SDLoc dl(Op);
8568 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8569 DAG.getEntryNode(), Op.getOperand(1));
8571 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8574 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8575 SDLoc DL(N);
8576 SDValue Op = N->getOperand(1);
8577 if (N->getValueType(0) == MVT::i32)
8578 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8579 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8580 DAG.getConstant(0, DL, MVT::i32));
8581 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8582 DAG.getConstant(1, DL, MVT::i32));
8583 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8584 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8587 void ARMTargetLowering::ExpandDIV_Windows(
8588 SDValue Op, SelectionDAG &DAG, bool Signed,
8589 SmallVectorImpl<SDValue> &Results) const {
8590 const auto &DL = DAG.getDataLayout();
8591 const auto &TLI = DAG.getTargetLoweringInfo();
8593 assert(Op.getValueType() == MVT::i64 &&
8594 "unexpected type for custom lowering DIV");
8595 SDLoc dl(Op);
8597 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8599 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8601 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8602 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8603 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8604 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8606 Results.push_back(Lower);
8607 Results.push_back(Upper);
8610 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8611 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8612 // Acquire/Release load/store is not legal for targets without a dmb or
8613 // equivalent available.
8614 return SDValue();
8616 // Monotonic load/store is legal for all targets.
8617 return Op;
8620 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8621 SmallVectorImpl<SDValue> &Results,
8622 SelectionDAG &DAG,
8623 const ARMSubtarget *Subtarget) {
8624 SDLoc DL(N);
8625 // Under Power Management extensions, the cycle-count is:
8626 // mrc p15, #0, <Rt>, c9, c13, #0
8627 SDValue Ops[] = { N->getOperand(0), // Chain
8628 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8629 DAG.getConstant(15, DL, MVT::i32),
8630 DAG.getConstant(0, DL, MVT::i32),
8631 DAG.getConstant(9, DL, MVT::i32),
8632 DAG.getConstant(13, DL, MVT::i32),
8633 DAG.getConstant(0, DL, MVT::i32)
8636 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8637 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8638 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8639 DAG.getConstant(0, DL, MVT::i32)));
8640 Results.push_back(Cycles32.getValue(1));
8643 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8644 SDLoc dl(V.getNode());
8645 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8646 SDValue VHi = DAG.getAnyExtOrTrunc(
8647 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8648 dl, MVT::i32);
8649 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8650 if (isBigEndian)
8651 std::swap (VLo, VHi);
8652 SDValue RegClass =
8653 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8654 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8655 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8656 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8657 return SDValue(
8658 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8661 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8662 SmallVectorImpl<SDValue> & Results,
8663 SelectionDAG &DAG) {
8664 assert(N->getValueType(0) == MVT::i64 &&
8665 "AtomicCmpSwap on types less than 64 should be legal");
8666 SDValue Ops[] = {N->getOperand(1),
8667 createGPRPairNode(DAG, N->getOperand(2)),
8668 createGPRPairNode(DAG, N->getOperand(3)),
8669 N->getOperand(0)};
8670 SDNode *CmpSwap = DAG.getMachineNode(
8671 ARM::CMP_SWAP_64, SDLoc(N),
8672 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8674 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8675 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8677 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8679 Results.push_back(
8680 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8681 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8682 Results.push_back(
8683 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8684 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8685 Results.push_back(SDValue(CmpSwap, 2));
8688 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8689 SelectionDAG &DAG) {
8690 const auto &TLI = DAG.getTargetLoweringInfo();
8692 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8693 "Custom lowering is MSVCRT specific!");
8695 SDLoc dl(Op);
8696 SDValue Val = Op.getOperand(0);
8697 MVT Ty = Val->getSimpleValueType(0);
8698 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8699 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8700 TLI.getPointerTy(DAG.getDataLayout()));
8702 TargetLowering::ArgListTy Args;
8703 TargetLowering::ArgListEntry Entry;
8705 Entry.Node = Val;
8706 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8707 Entry.IsZExt = true;
8708 Args.push_back(Entry);
8710 Entry.Node = Exponent;
8711 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8712 Entry.IsZExt = true;
8713 Args.push_back(Entry);
8715 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8717 // In the in-chain to the call is the entry node If we are emitting a
8718 // tailcall, the chain will be mutated if the node has a non-entry input
8719 // chain.
8720 SDValue InChain = DAG.getEntryNode();
8721 SDValue TCChain = InChain;
8723 const Function &F = DAG.getMachineFunction().getFunction();
8724 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8725 F.getReturnType() == LCRTy;
8726 if (IsTC)
8727 InChain = TCChain;
8729 TargetLowering::CallLoweringInfo CLI(DAG);
8730 CLI.setDebugLoc(dl)
8731 .setChain(InChain)
8732 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8733 .setTailCall(IsTC);
8734 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8736 // Return the chain (the DAG root) if it is a tail call
8737 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8740 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8741 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8742 switch (Op.getOpcode()) {
8743 default: llvm_unreachable("Don't know how to custom lower this!");
8744 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8745 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8746 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8747 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8748 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8749 case ISD::SELECT: return LowerSELECT(Op, DAG);
8750 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8751 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8752 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8753 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8754 case ISD::VASTART: return LowerVASTART(Op, DAG);
8755 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8756 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8757 case ISD::SINT_TO_FP:
8758 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8759 case ISD::FP_TO_SINT:
8760 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8761 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8762 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8763 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8764 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8765 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8766 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8767 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8768 Subtarget);
8769 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8770 case ISD::SHL:
8771 case ISD::SRL:
8772 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8773 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8774 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8775 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8776 case ISD::SRL_PARTS:
8777 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8778 case ISD::CTTZ:
8779 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8780 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8781 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8782 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8783 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8784 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8785 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8786 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8787 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8788 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8789 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8790 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8791 case ISD::MUL: return LowerMUL(Op, DAG);
8792 case ISD::SDIV:
8793 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8794 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8795 return LowerSDIV(Op, DAG, Subtarget);
8796 case ISD::UDIV:
8797 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8798 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8799 return LowerUDIV(Op, DAG, Subtarget);
8800 case ISD::ADDCARRY:
8801 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8802 case ISD::SADDO:
8803 case ISD::SSUBO:
8804 return LowerSignedALUO(Op, DAG);
8805 case ISD::UADDO:
8806 case ISD::USUBO:
8807 return LowerUnsignedALUO(Op, DAG);
8808 case ISD::ATOMIC_LOAD:
8809 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8810 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8811 case ISD::SDIVREM:
8812 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8813 case ISD::DYNAMIC_STACKALLOC:
8814 if (Subtarget->isTargetWindows())
8815 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8816 llvm_unreachable("Don't know how to custom lower this!");
8817 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8818 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8819 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8820 case ARMISD::WIN__DBZCHK: return SDValue();
8824 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8825 SelectionDAG &DAG) {
8826 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8827 unsigned Opc = 0;
8828 if (IntNo == Intrinsic::arm_smlald)
8829 Opc = ARMISD::SMLALD;
8830 else if (IntNo == Intrinsic::arm_smlaldx)
8831 Opc = ARMISD::SMLALDX;
8832 else if (IntNo == Intrinsic::arm_smlsld)
8833 Opc = ARMISD::SMLSLD;
8834 else if (IntNo == Intrinsic::arm_smlsldx)
8835 Opc = ARMISD::SMLSLDX;
8836 else
8837 return;
8839 SDLoc dl(N);
8840 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8841 N->getOperand(3),
8842 DAG.getConstant(0, dl, MVT::i32));
8843 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8844 N->getOperand(3),
8845 DAG.getConstant(1, dl, MVT::i32));
8847 SDValue LongMul = DAG.getNode(Opc, dl,
8848 DAG.getVTList(MVT::i32, MVT::i32),
8849 N->getOperand(1), N->getOperand(2),
8850 Lo, Hi);
8851 Results.push_back(LongMul.getValue(0));
8852 Results.push_back(LongMul.getValue(1));
8855 /// ReplaceNodeResults - Replace the results of node with an illegal result
8856 /// type with new values built out of custom code.
8857 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8858 SmallVectorImpl<SDValue> &Results,
8859 SelectionDAG &DAG) const {
8860 SDValue Res;
8861 switch (N->getOpcode()) {
8862 default:
8863 llvm_unreachable("Don't know how to custom expand this!");
8864 case ISD::READ_REGISTER:
8865 ExpandREAD_REGISTER(N, Results, DAG);
8866 break;
8867 case ISD::BITCAST:
8868 Res = ExpandBITCAST(N, DAG, Subtarget);
8869 break;
8870 case ISD::SRL:
8871 case ISD::SRA:
8872 case ISD::SHL:
8873 Res = Expand64BitShift(N, DAG, Subtarget);
8874 break;
8875 case ISD::SREM:
8876 case ISD::UREM:
8877 Res = LowerREM(N, DAG);
8878 break;
8879 case ISD::SDIVREM:
8880 case ISD::UDIVREM:
8881 Res = LowerDivRem(SDValue(N, 0), DAG);
8882 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8883 Results.push_back(Res.getValue(0));
8884 Results.push_back(Res.getValue(1));
8885 return;
8886 case ISD::READCYCLECOUNTER:
8887 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8888 return;
8889 case ISD::UDIV:
8890 case ISD::SDIV:
8891 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8892 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8893 Results);
8894 case ISD::ATOMIC_CMP_SWAP:
8895 ReplaceCMP_SWAP_64Results(N, Results, DAG);
8896 return;
8897 case ISD::INTRINSIC_WO_CHAIN:
8898 return ReplaceLongIntrinsic(N, Results, DAG);
8899 case ISD::ABS:
8900 lowerABS(N, Results, DAG);
8901 return ;
8904 if (Res.getNode())
8905 Results.push_back(Res);
8908 //===----------------------------------------------------------------------===//
8909 // ARM Scheduler Hooks
8910 //===----------------------------------------------------------------------===//
8912 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8913 /// registers the function context.
8914 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8915 MachineBasicBlock *MBB,
8916 MachineBasicBlock *DispatchBB,
8917 int FI) const {
8918 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8919 "ROPI/RWPI not currently supported with SjLj");
8920 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8921 DebugLoc dl = MI.getDebugLoc();
8922 MachineFunction *MF = MBB->getParent();
8923 MachineRegisterInfo *MRI = &MF->getRegInfo();
8924 MachineConstantPool *MCP = MF->getConstantPool();
8925 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8926 const Function &F = MF->getFunction();
8928 bool isThumb = Subtarget->isThumb();
8929 bool isThumb2 = Subtarget->isThumb2();
8931 unsigned PCLabelId = AFI->createPICLabelUId();
8932 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8933 ARMConstantPoolValue *CPV =
8934 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8935 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8937 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8938 : &ARM::GPRRegClass;
8940 // Grab constant pool and fixed stack memory operands.
8941 MachineMemOperand *CPMMO =
8942 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8943 MachineMemOperand::MOLoad, 4, 4);
8945 MachineMemOperand *FIMMOSt =
8946 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8947 MachineMemOperand::MOStore, 4, 4);
8949 // Load the address of the dispatch MBB into the jump buffer.
8950 if (isThumb2) {
8951 // Incoming value: jbuf
8952 // ldr.n r5, LCPI1_1
8953 // orr r5, r5, #1
8954 // add r5, pc
8955 // str r5, [$jbuf, #+4] ; &jbuf[1]
8956 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8957 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8958 .addConstantPoolIndex(CPI)
8959 .addMemOperand(CPMMO)
8960 .add(predOps(ARMCC::AL));
8961 // Set the low bit because of thumb mode.
8962 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8963 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8964 .addReg(NewVReg1, RegState::Kill)
8965 .addImm(0x01)
8966 .add(predOps(ARMCC::AL))
8967 .add(condCodeOp());
8968 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8969 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8970 .addReg(NewVReg2, RegState::Kill)
8971 .addImm(PCLabelId);
8972 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8973 .addReg(NewVReg3, RegState::Kill)
8974 .addFrameIndex(FI)
8975 .addImm(36) // &jbuf[1] :: pc
8976 .addMemOperand(FIMMOSt)
8977 .add(predOps(ARMCC::AL));
8978 } else if (isThumb) {
8979 // Incoming value: jbuf
8980 // ldr.n r1, LCPI1_4
8981 // add r1, pc
8982 // mov r2, #1
8983 // orrs r1, r2
8984 // add r2, $jbuf, #+4 ; &jbuf[1]
8985 // str r1, [r2]
8986 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8987 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8988 .addConstantPoolIndex(CPI)
8989 .addMemOperand(CPMMO)
8990 .add(predOps(ARMCC::AL));
8991 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8992 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8993 .addReg(NewVReg1, RegState::Kill)
8994 .addImm(PCLabelId);
8995 // Set the low bit because of thumb mode.
8996 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8997 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8998 .addReg(ARM::CPSR, RegState::Define)
8999 .addImm(1)
9000 .add(predOps(ARMCC::AL));
9001 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9002 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9003 .addReg(ARM::CPSR, RegState::Define)
9004 .addReg(NewVReg2, RegState::Kill)
9005 .addReg(NewVReg3, RegState::Kill)
9006 .add(predOps(ARMCC::AL));
9007 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
9008 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9009 .addFrameIndex(FI)
9010 .addImm(36); // &jbuf[1] :: pc
9011 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9012 .addReg(NewVReg4, RegState::Kill)
9013 .addReg(NewVReg5, RegState::Kill)
9014 .addImm(0)
9015 .addMemOperand(FIMMOSt)
9016 .add(predOps(ARMCC::AL));
9017 } else {
9018 // Incoming value: jbuf
9019 // ldr r1, LCPI1_1
9020 // add r1, pc, r1
9021 // str r1, [$jbuf, #+4] ; &jbuf[1]
9022 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9023 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9024 .addConstantPoolIndex(CPI)
9025 .addImm(0)
9026 .addMemOperand(CPMMO)
9027 .add(predOps(ARMCC::AL));
9028 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
9029 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9030 .addReg(NewVReg1, RegState::Kill)
9031 .addImm(PCLabelId)
9032 .add(predOps(ARMCC::AL));
9033 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9034 .addReg(NewVReg2, RegState::Kill)
9035 .addFrameIndex(FI)
9036 .addImm(36) // &jbuf[1] :: pc
9037 .addMemOperand(FIMMOSt)
9038 .add(predOps(ARMCC::AL));
9042 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9043 MachineBasicBlock *MBB) const {
9044 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9045 DebugLoc dl = MI.getDebugLoc();
9046 MachineFunction *MF = MBB->getParent();
9047 MachineRegisterInfo *MRI = &MF->getRegInfo();
9048 MachineFrameInfo &MFI = MF->getFrameInfo();
9049 int FI = MFI.getFunctionContextIndex();
9051 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9052 : &ARM::GPRnopcRegClass;
9054 // Get a mapping of the call site numbers to all of the landing pads they're
9055 // associated with.
9056 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9057 unsigned MaxCSNum = 0;
9058 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9059 ++BB) {
9060 if (!BB->isEHPad()) continue;
9062 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9063 // pad.
9064 for (MachineBasicBlock::iterator
9065 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9066 if (!II->isEHLabel()) continue;
9068 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9069 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9071 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9072 for (SmallVectorImpl<unsigned>::iterator
9073 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9074 CSI != CSE; ++CSI) {
9075 CallSiteNumToLPad[*CSI].push_back(&*BB);
9076 MaxCSNum = std::max(MaxCSNum, *CSI);
9078 break;
9082 // Get an ordered list of the machine basic blocks for the jump table.
9083 std::vector<MachineBasicBlock*> LPadList;
9084 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9085 LPadList.reserve(CallSiteNumToLPad.size());
9086 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9087 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9088 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9089 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9090 LPadList.push_back(*II);
9091 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9095 assert(!LPadList.empty() &&
9096 "No landing pad destinations for the dispatch jump table!");
9098 // Create the jump table and associated information.
9099 MachineJumpTableInfo *JTI =
9100 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9101 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9103 // Create the MBBs for the dispatch code.
9105 // Shove the dispatch's address into the return slot in the function context.
9106 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9107 DispatchBB->setIsEHPad();
9109 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9110 unsigned trap_opcode;
9111 if (Subtarget->isThumb())
9112 trap_opcode = ARM::tTRAP;
9113 else
9114 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9116 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9117 DispatchBB->addSuccessor(TrapBB);
9119 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9120 DispatchBB->addSuccessor(DispContBB);
9122 // Insert and MBBs.
9123 MF->insert(MF->end(), DispatchBB);
9124 MF->insert(MF->end(), DispContBB);
9125 MF->insert(MF->end(), TrapBB);
9127 // Insert code into the entry block that creates and registers the function
9128 // context.
9129 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9131 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9132 MachinePointerInfo::getFixedStack(*MF, FI),
9133 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9135 MachineInstrBuilder MIB;
9136 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9138 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9139 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9141 // Add a register mask with no preserved registers. This results in all
9142 // registers being marked as clobbered. This can't work if the dispatch block
9143 // is in a Thumb1 function and is linked with ARM code which uses the FP
9144 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9145 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9147 bool IsPositionIndependent = isPositionIndependent();
9148 unsigned NumLPads = LPadList.size();
9149 if (Subtarget->isThumb2()) {
9150 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9151 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9152 .addFrameIndex(FI)
9153 .addImm(4)
9154 .addMemOperand(FIMMOLd)
9155 .add(predOps(ARMCC::AL));
9157 if (NumLPads < 256) {
9158 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9159 .addReg(NewVReg1)
9160 .addImm(LPadList.size())
9161 .add(predOps(ARMCC::AL));
9162 } else {
9163 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9164 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9165 .addImm(NumLPads & 0xFFFF)
9166 .add(predOps(ARMCC::AL));
9168 unsigned VReg2 = VReg1;
9169 if ((NumLPads & 0xFFFF0000) != 0) {
9170 VReg2 = MRI->createVirtualRegister(TRC);
9171 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9172 .addReg(VReg1)
9173 .addImm(NumLPads >> 16)
9174 .add(predOps(ARMCC::AL));
9177 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9178 .addReg(NewVReg1)
9179 .addReg(VReg2)
9180 .add(predOps(ARMCC::AL));
9183 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9184 .addMBB(TrapBB)
9185 .addImm(ARMCC::HI)
9186 .addReg(ARM::CPSR);
9188 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9189 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9190 .addJumpTableIndex(MJTI)
9191 .add(predOps(ARMCC::AL));
9193 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9194 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9195 .addReg(NewVReg3, RegState::Kill)
9196 .addReg(NewVReg1)
9197 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9198 .add(predOps(ARMCC::AL))
9199 .add(condCodeOp());
9201 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9202 .addReg(NewVReg4, RegState::Kill)
9203 .addReg(NewVReg1)
9204 .addJumpTableIndex(MJTI);
9205 } else if (Subtarget->isThumb()) {
9206 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9207 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9208 .addFrameIndex(FI)
9209 .addImm(1)
9210 .addMemOperand(FIMMOLd)
9211 .add(predOps(ARMCC::AL));
9213 if (NumLPads < 256) {
9214 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9215 .addReg(NewVReg1)
9216 .addImm(NumLPads)
9217 .add(predOps(ARMCC::AL));
9218 } else {
9219 MachineConstantPool *ConstantPool = MF->getConstantPool();
9220 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9221 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9223 // MachineConstantPool wants an explicit alignment.
9224 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9225 if (Align == 0)
9226 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9227 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9229 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9230 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9231 .addReg(VReg1, RegState::Define)
9232 .addConstantPoolIndex(Idx)
9233 .add(predOps(ARMCC::AL));
9234 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9235 .addReg(NewVReg1)
9236 .addReg(VReg1)
9237 .add(predOps(ARMCC::AL));
9240 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9241 .addMBB(TrapBB)
9242 .addImm(ARMCC::HI)
9243 .addReg(ARM::CPSR);
9245 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
9246 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9247 .addReg(ARM::CPSR, RegState::Define)
9248 .addReg(NewVReg1)
9249 .addImm(2)
9250 .add(predOps(ARMCC::AL));
9252 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9253 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9254 .addJumpTableIndex(MJTI)
9255 .add(predOps(ARMCC::AL));
9257 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9258 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9259 .addReg(ARM::CPSR, RegState::Define)
9260 .addReg(NewVReg2, RegState::Kill)
9261 .addReg(NewVReg3)
9262 .add(predOps(ARMCC::AL));
9264 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9265 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9267 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
9268 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9269 .addReg(NewVReg4, RegState::Kill)
9270 .addImm(0)
9271 .addMemOperand(JTMMOLd)
9272 .add(predOps(ARMCC::AL));
9274 unsigned NewVReg6 = NewVReg5;
9275 if (IsPositionIndependent) {
9276 NewVReg6 = MRI->createVirtualRegister(TRC);
9277 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9278 .addReg(ARM::CPSR, RegState::Define)
9279 .addReg(NewVReg5, RegState::Kill)
9280 .addReg(NewVReg3)
9281 .add(predOps(ARMCC::AL));
9284 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9285 .addReg(NewVReg6, RegState::Kill)
9286 .addJumpTableIndex(MJTI);
9287 } else {
9288 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9289 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9290 .addFrameIndex(FI)
9291 .addImm(4)
9292 .addMemOperand(FIMMOLd)
9293 .add(predOps(ARMCC::AL));
9295 if (NumLPads < 256) {
9296 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9297 .addReg(NewVReg1)
9298 .addImm(NumLPads)
9299 .add(predOps(ARMCC::AL));
9300 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9301 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9302 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9303 .addImm(NumLPads & 0xFFFF)
9304 .add(predOps(ARMCC::AL));
9306 unsigned VReg2 = VReg1;
9307 if ((NumLPads & 0xFFFF0000) != 0) {
9308 VReg2 = MRI->createVirtualRegister(TRC);
9309 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9310 .addReg(VReg1)
9311 .addImm(NumLPads >> 16)
9312 .add(predOps(ARMCC::AL));
9315 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9316 .addReg(NewVReg1)
9317 .addReg(VReg2)
9318 .add(predOps(ARMCC::AL));
9319 } else {
9320 MachineConstantPool *ConstantPool = MF->getConstantPool();
9321 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9322 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9324 // MachineConstantPool wants an explicit alignment.
9325 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9326 if (Align == 0)
9327 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9328 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9330 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9331 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9332 .addReg(VReg1, RegState::Define)
9333 .addConstantPoolIndex(Idx)
9334 .addImm(0)
9335 .add(predOps(ARMCC::AL));
9336 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9337 .addReg(NewVReg1)
9338 .addReg(VReg1, RegState::Kill)
9339 .add(predOps(ARMCC::AL));
9342 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9343 .addMBB(TrapBB)
9344 .addImm(ARMCC::HI)
9345 .addReg(ARM::CPSR);
9347 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9348 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9349 .addReg(NewVReg1)
9350 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9351 .add(predOps(ARMCC::AL))
9352 .add(condCodeOp());
9353 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9354 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9355 .addJumpTableIndex(MJTI)
9356 .add(predOps(ARMCC::AL));
9358 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9359 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9360 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
9361 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9362 .addReg(NewVReg3, RegState::Kill)
9363 .addReg(NewVReg4)
9364 .addImm(0)
9365 .addMemOperand(JTMMOLd)
9366 .add(predOps(ARMCC::AL));
9368 if (IsPositionIndependent) {
9369 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9370 .addReg(NewVReg5, RegState::Kill)
9371 .addReg(NewVReg4)
9372 .addJumpTableIndex(MJTI);
9373 } else {
9374 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9375 .addReg(NewVReg5, RegState::Kill)
9376 .addJumpTableIndex(MJTI);
9380 // Add the jump table entries as successors to the MBB.
9381 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9382 for (std::vector<MachineBasicBlock*>::iterator
9383 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9384 MachineBasicBlock *CurMBB = *I;
9385 if (SeenMBBs.insert(CurMBB).second)
9386 DispContBB->addSuccessor(CurMBB);
9389 // N.B. the order the invoke BBs are processed in doesn't matter here.
9390 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9391 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9392 for (MachineBasicBlock *BB : InvokeBBs) {
9394 // Remove the landing pad successor from the invoke block and replace it
9395 // with the new dispatch block.
9396 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9397 BB->succ_end());
9398 while (!Successors.empty()) {
9399 MachineBasicBlock *SMBB = Successors.pop_back_val();
9400 if (SMBB->isEHPad()) {
9401 BB->removeSuccessor(SMBB);
9402 MBBLPads.push_back(SMBB);
9406 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9407 BB->normalizeSuccProbs();
9409 // Find the invoke call and mark all of the callee-saved registers as
9410 // 'implicit defined' so that they're spilled. This prevents code from
9411 // moving instructions to before the EH block, where they will never be
9412 // executed.
9413 for (MachineBasicBlock::reverse_iterator
9414 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9415 if (!II->isCall()) continue;
9417 DenseMap<unsigned, bool> DefRegs;
9418 for (MachineInstr::mop_iterator
9419 OI = II->operands_begin(), OE = II->operands_end();
9420 OI != OE; ++OI) {
9421 if (!OI->isReg()) continue;
9422 DefRegs[OI->getReg()] = true;
9425 MachineInstrBuilder MIB(*MF, &*II);
9427 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9428 unsigned Reg = SavedRegs[i];
9429 if (Subtarget->isThumb2() &&
9430 !ARM::tGPRRegClass.contains(Reg) &&
9431 !ARM::hGPRRegClass.contains(Reg))
9432 continue;
9433 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9434 continue;
9435 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9436 continue;
9437 if (!DefRegs[Reg])
9438 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9441 break;
9445 // Mark all former landing pads as non-landing pads. The dispatch is the only
9446 // landing pad now.
9447 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9448 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9449 (*I)->setIsEHPad(false);
9451 // The instruction is gone now.
9452 MI.eraseFromParent();
9455 static
9456 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9457 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9458 E = MBB->succ_end(); I != E; ++I)
9459 if (*I != Succ)
9460 return *I;
9461 llvm_unreachable("Expecting a BB with two successors!");
9464 /// Return the load opcode for a given load size. If load size >= 8,
9465 /// neon opcode will be returned.
9466 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9467 if (LdSize >= 8)
9468 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9469 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9470 if (IsThumb1)
9471 return LdSize == 4 ? ARM::tLDRi
9472 : LdSize == 2 ? ARM::tLDRHi
9473 : LdSize == 1 ? ARM::tLDRBi : 0;
9474 if (IsThumb2)
9475 return LdSize == 4 ? ARM::t2LDR_POST
9476 : LdSize == 2 ? ARM::t2LDRH_POST
9477 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9478 return LdSize == 4 ? ARM::LDR_POST_IMM
9479 : LdSize == 2 ? ARM::LDRH_POST
9480 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9483 /// Return the store opcode for a given store size. If store size >= 8,
9484 /// neon opcode will be returned.
9485 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9486 if (StSize >= 8)
9487 return StSize == 16 ? ARM::VST1q32wb_fixed
9488 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9489 if (IsThumb1)
9490 return StSize == 4 ? ARM::tSTRi
9491 : StSize == 2 ? ARM::tSTRHi
9492 : StSize == 1 ? ARM::tSTRBi : 0;
9493 if (IsThumb2)
9494 return StSize == 4 ? ARM::t2STR_POST
9495 : StSize == 2 ? ARM::t2STRH_POST
9496 : StSize == 1 ? ARM::t2STRB_POST : 0;
9497 return StSize == 4 ? ARM::STR_POST_IMM
9498 : StSize == 2 ? ARM::STRH_POST
9499 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9502 /// Emit a post-increment load operation with given size. The instructions
9503 /// will be added to BB at Pos.
9504 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9505 const TargetInstrInfo *TII, const DebugLoc &dl,
9506 unsigned LdSize, unsigned Data, unsigned AddrIn,
9507 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9508 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9509 assert(LdOpc != 0 && "Should have a load opcode");
9510 if (LdSize >= 8) {
9511 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9512 .addReg(AddrOut, RegState::Define)
9513 .addReg(AddrIn)
9514 .addImm(0)
9515 .add(predOps(ARMCC::AL));
9516 } else if (IsThumb1) {
9517 // load + update AddrIn
9518 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9519 .addReg(AddrIn)
9520 .addImm(0)
9521 .add(predOps(ARMCC::AL));
9522 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9523 .add(t1CondCodeOp())
9524 .addReg(AddrIn)
9525 .addImm(LdSize)
9526 .add(predOps(ARMCC::AL));
9527 } else if (IsThumb2) {
9528 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9529 .addReg(AddrOut, RegState::Define)
9530 .addReg(AddrIn)
9531 .addImm(LdSize)
9532 .add(predOps(ARMCC::AL));
9533 } else { // arm
9534 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9535 .addReg(AddrOut, RegState::Define)
9536 .addReg(AddrIn)
9537 .addReg(0)
9538 .addImm(LdSize)
9539 .add(predOps(ARMCC::AL));
9543 /// Emit a post-increment store operation with given size. The instructions
9544 /// will be added to BB at Pos.
9545 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9546 const TargetInstrInfo *TII, const DebugLoc &dl,
9547 unsigned StSize, unsigned Data, unsigned AddrIn,
9548 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9549 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9550 assert(StOpc != 0 && "Should have a store opcode");
9551 if (StSize >= 8) {
9552 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9553 .addReg(AddrIn)
9554 .addImm(0)
9555 .addReg(Data)
9556 .add(predOps(ARMCC::AL));
9557 } else if (IsThumb1) {
9558 // store + update AddrIn
9559 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9560 .addReg(Data)
9561 .addReg(AddrIn)
9562 .addImm(0)
9563 .add(predOps(ARMCC::AL));
9564 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9565 .add(t1CondCodeOp())
9566 .addReg(AddrIn)
9567 .addImm(StSize)
9568 .add(predOps(ARMCC::AL));
9569 } else if (IsThumb2) {
9570 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9571 .addReg(Data)
9572 .addReg(AddrIn)
9573 .addImm(StSize)
9574 .add(predOps(ARMCC::AL));
9575 } else { // arm
9576 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9577 .addReg(Data)
9578 .addReg(AddrIn)
9579 .addReg(0)
9580 .addImm(StSize)
9581 .add(predOps(ARMCC::AL));
9585 MachineBasicBlock *
9586 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9587 MachineBasicBlock *BB) const {
9588 // This pseudo instruction has 3 operands: dst, src, size
9589 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9590 // Otherwise, we will generate unrolled scalar copies.
9591 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9592 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9593 MachineFunction::iterator It = ++BB->getIterator();
9595 unsigned dest = MI.getOperand(0).getReg();
9596 unsigned src = MI.getOperand(1).getReg();
9597 unsigned SizeVal = MI.getOperand(2).getImm();
9598 unsigned Align = MI.getOperand(3).getImm();
9599 DebugLoc dl = MI.getDebugLoc();
9601 MachineFunction *MF = BB->getParent();
9602 MachineRegisterInfo &MRI = MF->getRegInfo();
9603 unsigned UnitSize = 0;
9604 const TargetRegisterClass *TRC = nullptr;
9605 const TargetRegisterClass *VecTRC = nullptr;
9607 bool IsThumb1 = Subtarget->isThumb1Only();
9608 bool IsThumb2 = Subtarget->isThumb2();
9609 bool IsThumb = Subtarget->isThumb();
9611 if (Align & 1) {
9612 UnitSize = 1;
9613 } else if (Align & 2) {
9614 UnitSize = 2;
9615 } else {
9616 // Check whether we can use NEON instructions.
9617 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9618 Subtarget->hasNEON()) {
9619 if ((Align % 16 == 0) && SizeVal >= 16)
9620 UnitSize = 16;
9621 else if ((Align % 8 == 0) && SizeVal >= 8)
9622 UnitSize = 8;
9624 // Can't use NEON instructions.
9625 if (UnitSize == 0)
9626 UnitSize = 4;
9629 // Select the correct opcode and register class for unit size load/store
9630 bool IsNeon = UnitSize >= 8;
9631 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9632 if (IsNeon)
9633 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9634 : UnitSize == 8 ? &ARM::DPRRegClass
9635 : nullptr;
9637 unsigned BytesLeft = SizeVal % UnitSize;
9638 unsigned LoopSize = SizeVal - BytesLeft;
9640 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9641 // Use LDR and STR to copy.
9642 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9643 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9644 unsigned srcIn = src;
9645 unsigned destIn = dest;
9646 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9647 unsigned srcOut = MRI.createVirtualRegister(TRC);
9648 unsigned destOut = MRI.createVirtualRegister(TRC);
9649 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9650 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9651 IsThumb1, IsThumb2);
9652 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9653 IsThumb1, IsThumb2);
9654 srcIn = srcOut;
9655 destIn = destOut;
9658 // Handle the leftover bytes with LDRB and STRB.
9659 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9660 // [destOut] = STRB_POST(scratch, destIn, 1)
9661 for (unsigned i = 0; i < BytesLeft; i++) {
9662 unsigned srcOut = MRI.createVirtualRegister(TRC);
9663 unsigned destOut = MRI.createVirtualRegister(TRC);
9664 unsigned scratch = MRI.createVirtualRegister(TRC);
9665 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9666 IsThumb1, IsThumb2);
9667 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9668 IsThumb1, IsThumb2);
9669 srcIn = srcOut;
9670 destIn = destOut;
9672 MI.eraseFromParent(); // The instruction is gone now.
9673 return BB;
9676 // Expand the pseudo op to a loop.
9677 // thisMBB:
9678 // ...
9679 // movw varEnd, # --> with thumb2
9680 // movt varEnd, #
9681 // ldrcp varEnd, idx --> without thumb2
9682 // fallthrough --> loopMBB
9683 // loopMBB:
9684 // PHI varPhi, varEnd, varLoop
9685 // PHI srcPhi, src, srcLoop
9686 // PHI destPhi, dst, destLoop
9687 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9688 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9689 // subs varLoop, varPhi, #UnitSize
9690 // bne loopMBB
9691 // fallthrough --> exitMBB
9692 // exitMBB:
9693 // epilogue to handle left-over bytes
9694 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9695 // [destOut] = STRB_POST(scratch, destLoop, 1)
9696 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9697 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9698 MF->insert(It, loopMBB);
9699 MF->insert(It, exitMBB);
9701 // Transfer the remainder of BB and its successor edges to exitMBB.
9702 exitMBB->splice(exitMBB->begin(), BB,
9703 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9704 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9706 // Load an immediate to varEnd.
9707 unsigned varEnd = MRI.createVirtualRegister(TRC);
9708 if (Subtarget->useMovt()) {
9709 unsigned Vtmp = varEnd;
9710 if ((LoopSize & 0xFFFF0000) != 0)
9711 Vtmp = MRI.createVirtualRegister(TRC);
9712 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9713 .addImm(LoopSize & 0xFFFF)
9714 .add(predOps(ARMCC::AL));
9716 if ((LoopSize & 0xFFFF0000) != 0)
9717 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9718 .addReg(Vtmp)
9719 .addImm(LoopSize >> 16)
9720 .add(predOps(ARMCC::AL));
9721 } else {
9722 MachineConstantPool *ConstantPool = MF->getConstantPool();
9723 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9724 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9726 // MachineConstantPool wants an explicit alignment.
9727 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9728 if (Align == 0)
9729 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9730 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9731 MachineMemOperand *CPMMO =
9732 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9733 MachineMemOperand::MOLoad, 4, 4);
9735 if (IsThumb)
9736 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9737 .addReg(varEnd, RegState::Define)
9738 .addConstantPoolIndex(Idx)
9739 .add(predOps(ARMCC::AL))
9740 .addMemOperand(CPMMO);
9741 else
9742 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9743 .addReg(varEnd, RegState::Define)
9744 .addConstantPoolIndex(Idx)
9745 .addImm(0)
9746 .add(predOps(ARMCC::AL))
9747 .addMemOperand(CPMMO);
9749 BB->addSuccessor(loopMBB);
9751 // Generate the loop body:
9752 // varPhi = PHI(varLoop, varEnd)
9753 // srcPhi = PHI(srcLoop, src)
9754 // destPhi = PHI(destLoop, dst)
9755 MachineBasicBlock *entryBB = BB;
9756 BB = loopMBB;
9757 unsigned varLoop = MRI.createVirtualRegister(TRC);
9758 unsigned varPhi = MRI.createVirtualRegister(TRC);
9759 unsigned srcLoop = MRI.createVirtualRegister(TRC);
9760 unsigned srcPhi = MRI.createVirtualRegister(TRC);
9761 unsigned destLoop = MRI.createVirtualRegister(TRC);
9762 unsigned destPhi = MRI.createVirtualRegister(TRC);
9764 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9765 .addReg(varLoop).addMBB(loopMBB)
9766 .addReg(varEnd).addMBB(entryBB);
9767 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9768 .addReg(srcLoop).addMBB(loopMBB)
9769 .addReg(src).addMBB(entryBB);
9770 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9771 .addReg(destLoop).addMBB(loopMBB)
9772 .addReg(dest).addMBB(entryBB);
9774 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9775 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9776 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9777 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9778 IsThumb1, IsThumb2);
9779 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9780 IsThumb1, IsThumb2);
9782 // Decrement loop variable by UnitSize.
9783 if (IsThumb1) {
9784 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9785 .add(t1CondCodeOp())
9786 .addReg(varPhi)
9787 .addImm(UnitSize)
9788 .add(predOps(ARMCC::AL));
9789 } else {
9790 MachineInstrBuilder MIB =
9791 BuildMI(*BB, BB->end(), dl,
9792 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9793 MIB.addReg(varPhi)
9794 .addImm(UnitSize)
9795 .add(predOps(ARMCC::AL))
9796 .add(condCodeOp());
9797 MIB->getOperand(5).setReg(ARM::CPSR);
9798 MIB->getOperand(5).setIsDef(true);
9800 BuildMI(*BB, BB->end(), dl,
9801 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9802 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9804 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9805 BB->addSuccessor(loopMBB);
9806 BB->addSuccessor(exitMBB);
9808 // Add epilogue to handle BytesLeft.
9809 BB = exitMBB;
9810 auto StartOfExit = exitMBB->begin();
9812 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9813 // [destOut] = STRB_POST(scratch, destLoop, 1)
9814 unsigned srcIn = srcLoop;
9815 unsigned destIn = destLoop;
9816 for (unsigned i = 0; i < BytesLeft; i++) {
9817 unsigned srcOut = MRI.createVirtualRegister(TRC);
9818 unsigned destOut = MRI.createVirtualRegister(TRC);
9819 unsigned scratch = MRI.createVirtualRegister(TRC);
9820 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9821 IsThumb1, IsThumb2);
9822 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9823 IsThumb1, IsThumb2);
9824 srcIn = srcOut;
9825 destIn = destOut;
9828 MI.eraseFromParent(); // The instruction is gone now.
9829 return BB;
9832 MachineBasicBlock *
9833 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9834 MachineBasicBlock *MBB) const {
9835 const TargetMachine &TM = getTargetMachine();
9836 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9837 DebugLoc DL = MI.getDebugLoc();
9839 assert(Subtarget->isTargetWindows() &&
9840 "__chkstk is only supported on Windows");
9841 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9843 // __chkstk takes the number of words to allocate on the stack in R4, and
9844 // returns the stack adjustment in number of bytes in R4. This will not
9845 // clober any other registers (other than the obvious lr).
9847 // Although, technically, IP should be considered a register which may be
9848 // clobbered, the call itself will not touch it. Windows on ARM is a pure
9849 // thumb-2 environment, so there is no interworking required. As a result, we
9850 // do not expect a veneer to be emitted by the linker, clobbering IP.
9852 // Each module receives its own copy of __chkstk, so no import thunk is
9853 // required, again, ensuring that IP is not clobbered.
9855 // Finally, although some linkers may theoretically provide a trampoline for
9856 // out of range calls (which is quite common due to a 32M range limitation of
9857 // branches for Thumb), we can generate the long-call version via
9858 // -mcmodel=large, alleviating the need for the trampoline which may clobber
9859 // IP.
9861 switch (TM.getCodeModel()) {
9862 case CodeModel::Tiny:
9863 llvm_unreachable("Tiny code model not available on ARM.");
9864 case CodeModel::Small:
9865 case CodeModel::Medium:
9866 case CodeModel::Kernel:
9867 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9868 .add(predOps(ARMCC::AL))
9869 .addExternalSymbol("__chkstk")
9870 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9871 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9872 .addReg(ARM::R12,
9873 RegState::Implicit | RegState::Define | RegState::Dead)
9874 .addReg(ARM::CPSR,
9875 RegState::Implicit | RegState::Define | RegState::Dead);
9876 break;
9877 case CodeModel::Large: {
9878 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9879 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9881 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9882 .addExternalSymbol("__chkstk");
9883 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9884 .add(predOps(ARMCC::AL))
9885 .addReg(Reg, RegState::Kill)
9886 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9887 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9888 .addReg(ARM::R12,
9889 RegState::Implicit | RegState::Define | RegState::Dead)
9890 .addReg(ARM::CPSR,
9891 RegState::Implicit | RegState::Define | RegState::Dead);
9892 break;
9896 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9897 .addReg(ARM::SP, RegState::Kill)
9898 .addReg(ARM::R4, RegState::Kill)
9899 .setMIFlags(MachineInstr::FrameSetup)
9900 .add(predOps(ARMCC::AL))
9901 .add(condCodeOp());
9903 MI.eraseFromParent();
9904 return MBB;
9907 MachineBasicBlock *
9908 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9909 MachineBasicBlock *MBB) const {
9910 DebugLoc DL = MI.getDebugLoc();
9911 MachineFunction *MF = MBB->getParent();
9912 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9914 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9915 MF->insert(++MBB->getIterator(), ContBB);
9916 ContBB->splice(ContBB->begin(), MBB,
9917 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9918 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9919 MBB->addSuccessor(ContBB);
9921 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9922 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9923 MF->push_back(TrapBB);
9924 MBB->addSuccessor(TrapBB);
9926 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9927 .addReg(MI.getOperand(0).getReg())
9928 .addImm(0)
9929 .add(predOps(ARMCC::AL));
9930 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9931 .addMBB(TrapBB)
9932 .addImm(ARMCC::EQ)
9933 .addReg(ARM::CPSR);
9935 MI.eraseFromParent();
9936 return ContBB;
9939 // The CPSR operand of SelectItr might be missing a kill marker
9940 // because there were multiple uses of CPSR, and ISel didn't know
9941 // which to mark. Figure out whether SelectItr should have had a
9942 // kill marker, and set it if it should. Returns the correct kill
9943 // marker value.
9944 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9945 MachineBasicBlock* BB,
9946 const TargetRegisterInfo* TRI) {
9947 // Scan forward through BB for a use/def of CPSR.
9948 MachineBasicBlock::iterator miI(std::next(SelectItr));
9949 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9950 const MachineInstr& mi = *miI;
9951 if (mi.readsRegister(ARM::CPSR))
9952 return false;
9953 if (mi.definesRegister(ARM::CPSR))
9954 break; // Should have kill-flag - update below.
9957 // If we hit the end of the block, check whether CPSR is live into a
9958 // successor.
9959 if (miI == BB->end()) {
9960 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9961 sEnd = BB->succ_end();
9962 sItr != sEnd; ++sItr) {
9963 MachineBasicBlock* succ = *sItr;
9964 if (succ->isLiveIn(ARM::CPSR))
9965 return false;
9969 // We found a def, or hit the end of the basic block and CPSR wasn't live
9970 // out. SelectMI should have a kill flag on CPSR.
9971 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9972 return true;
9975 MachineBasicBlock *
9976 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9977 MachineBasicBlock *BB) const {
9978 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9979 DebugLoc dl = MI.getDebugLoc();
9980 bool isThumb2 = Subtarget->isThumb2();
9981 switch (MI.getOpcode()) {
9982 default: {
9983 MI.print(errs());
9984 llvm_unreachable("Unexpected instr type to insert");
9987 // Thumb1 post-indexed loads are really just single-register LDMs.
9988 case ARM::tLDR_postidx: {
9989 MachineOperand Def(MI.getOperand(1));
9990 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9991 .add(Def) // Rn_wb
9992 .add(MI.getOperand(2)) // Rn
9993 .add(MI.getOperand(3)) // PredImm
9994 .add(MI.getOperand(4)) // PredReg
9995 .add(MI.getOperand(0)) // Rt
9996 .cloneMemRefs(MI);
9997 MI.eraseFromParent();
9998 return BB;
10001 // The Thumb2 pre-indexed stores have the same MI operands, they just
10002 // define them differently in the .td files from the isel patterns, so
10003 // they need pseudos.
10004 case ARM::t2STR_preidx:
10005 MI.setDesc(TII->get(ARM::t2STR_PRE));
10006 return BB;
10007 case ARM::t2STRB_preidx:
10008 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10009 return BB;
10010 case ARM::t2STRH_preidx:
10011 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10012 return BB;
10014 case ARM::STRi_preidx:
10015 case ARM::STRBi_preidx: {
10016 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10017 : ARM::STRB_PRE_IMM;
10018 // Decode the offset.
10019 unsigned Offset = MI.getOperand(4).getImm();
10020 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10021 Offset = ARM_AM::getAM2Offset(Offset);
10022 if (isSub)
10023 Offset = -Offset;
10025 MachineMemOperand *MMO = *MI.memoperands_begin();
10026 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10027 .add(MI.getOperand(0)) // Rn_wb
10028 .add(MI.getOperand(1)) // Rt
10029 .add(MI.getOperand(2)) // Rn
10030 .addImm(Offset) // offset (skip GPR==zero_reg)
10031 .add(MI.getOperand(5)) // pred
10032 .add(MI.getOperand(6))
10033 .addMemOperand(MMO);
10034 MI.eraseFromParent();
10035 return BB;
10037 case ARM::STRr_preidx:
10038 case ARM::STRBr_preidx:
10039 case ARM::STRH_preidx: {
10040 unsigned NewOpc;
10041 switch (MI.getOpcode()) {
10042 default: llvm_unreachable("unexpected opcode!");
10043 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10044 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10045 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10047 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10048 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10049 MIB.add(MI.getOperand(i));
10050 MI.eraseFromParent();
10051 return BB;
10054 case ARM::tMOVCCr_pseudo: {
10055 // To "insert" a SELECT_CC instruction, we actually have to insert the
10056 // diamond control-flow pattern. The incoming instruction knows the
10057 // destination vreg to set, the condition code register to branch on, the
10058 // true/false values to select between, and a branch opcode to use.
10059 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10060 MachineFunction::iterator It = ++BB->getIterator();
10062 // thisMBB:
10063 // ...
10064 // TrueVal = ...
10065 // cmpTY ccX, r1, r2
10066 // bCC copy1MBB
10067 // fallthrough --> copy0MBB
10068 MachineBasicBlock *thisMBB = BB;
10069 MachineFunction *F = BB->getParent();
10070 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10071 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10072 F->insert(It, copy0MBB);
10073 F->insert(It, sinkMBB);
10075 // Check whether CPSR is live past the tMOVCCr_pseudo.
10076 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10077 if (!MI.killsRegister(ARM::CPSR) &&
10078 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10079 copy0MBB->addLiveIn(ARM::CPSR);
10080 sinkMBB->addLiveIn(ARM::CPSR);
10083 // Transfer the remainder of BB and its successor edges to sinkMBB.
10084 sinkMBB->splice(sinkMBB->begin(), BB,
10085 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10086 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10088 BB->addSuccessor(copy0MBB);
10089 BB->addSuccessor(sinkMBB);
10091 BuildMI(BB, dl, TII->get(ARM::tBcc))
10092 .addMBB(sinkMBB)
10093 .addImm(MI.getOperand(3).getImm())
10094 .addReg(MI.getOperand(4).getReg());
10096 // copy0MBB:
10097 // %FalseValue = ...
10098 // # fallthrough to sinkMBB
10099 BB = copy0MBB;
10101 // Update machine-CFG edges
10102 BB->addSuccessor(sinkMBB);
10104 // sinkMBB:
10105 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10106 // ...
10107 BB = sinkMBB;
10108 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10109 .addReg(MI.getOperand(1).getReg())
10110 .addMBB(copy0MBB)
10111 .addReg(MI.getOperand(2).getReg())
10112 .addMBB(thisMBB);
10114 MI.eraseFromParent(); // The pseudo instruction is gone now.
10115 return BB;
10118 case ARM::BCCi64:
10119 case ARM::BCCZi64: {
10120 // If there is an unconditional branch to the other successor, remove it.
10121 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10123 // Compare both parts that make up the double comparison separately for
10124 // equality.
10125 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10127 unsigned LHS1 = MI.getOperand(1).getReg();
10128 unsigned LHS2 = MI.getOperand(2).getReg();
10129 if (RHSisZero) {
10130 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10131 .addReg(LHS1)
10132 .addImm(0)
10133 .add(predOps(ARMCC::AL));
10134 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10135 .addReg(LHS2).addImm(0)
10136 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10137 } else {
10138 unsigned RHS1 = MI.getOperand(3).getReg();
10139 unsigned RHS2 = MI.getOperand(4).getReg();
10140 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10141 .addReg(LHS1)
10142 .addReg(RHS1)
10143 .add(predOps(ARMCC::AL));
10144 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10145 .addReg(LHS2).addReg(RHS2)
10146 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10149 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10150 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10151 if (MI.getOperand(0).getImm() == ARMCC::NE)
10152 std::swap(destMBB, exitMBB);
10154 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10155 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10156 if (isThumb2)
10157 BuildMI(BB, dl, TII->get(ARM::t2B))
10158 .addMBB(exitMBB)
10159 .add(predOps(ARMCC::AL));
10160 else
10161 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10163 MI.eraseFromParent(); // The pseudo instruction is gone now.
10164 return BB;
10167 case ARM::Int_eh_sjlj_setjmp:
10168 case ARM::Int_eh_sjlj_setjmp_nofp:
10169 case ARM::tInt_eh_sjlj_setjmp:
10170 case ARM::t2Int_eh_sjlj_setjmp:
10171 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10172 return BB;
10174 case ARM::Int_eh_sjlj_setup_dispatch:
10175 EmitSjLjDispatchBlock(MI, BB);
10176 return BB;
10178 case ARM::ABS:
10179 case ARM::t2ABS: {
10180 // To insert an ABS instruction, we have to insert the
10181 // diamond control-flow pattern. The incoming instruction knows the
10182 // source vreg to test against 0, the destination vreg to set,
10183 // the condition code register to branch on, the
10184 // true/false values to select between, and a branch opcode to use.
10185 // It transforms
10186 // V1 = ABS V0
10187 // into
10188 // V2 = MOVS V0
10189 // BCC (branch to SinkBB if V0 >= 0)
10190 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10191 // SinkBB: V1 = PHI(V2, V3)
10192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10193 MachineFunction::iterator BBI = ++BB->getIterator();
10194 MachineFunction *Fn = BB->getParent();
10195 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10196 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10197 Fn->insert(BBI, RSBBB);
10198 Fn->insert(BBI, SinkBB);
10200 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
10201 unsigned int ABSDstReg = MI.getOperand(0).getReg();
10202 bool ABSSrcKIll = MI.getOperand(1).isKill();
10203 bool isThumb2 = Subtarget->isThumb2();
10204 MachineRegisterInfo &MRI = Fn->getRegInfo();
10205 // In Thumb mode S must not be specified if source register is the SP or
10206 // PC and if destination register is the SP, so restrict register class
10207 unsigned NewRsbDstReg =
10208 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10210 // Transfer the remainder of BB and its successor edges to sinkMBB.
10211 SinkBB->splice(SinkBB->begin(), BB,
10212 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10213 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10215 BB->addSuccessor(RSBBB);
10216 BB->addSuccessor(SinkBB);
10218 // fall through to SinkMBB
10219 RSBBB->addSuccessor(SinkBB);
10221 // insert a cmp at the end of BB
10222 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10223 .addReg(ABSSrcReg)
10224 .addImm(0)
10225 .add(predOps(ARMCC::AL));
10227 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10228 BuildMI(BB, dl,
10229 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10230 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10232 // insert rsbri in RSBBB
10233 // Note: BCC and rsbri will be converted into predicated rsbmi
10234 // by if-conversion pass
10235 BuildMI(*RSBBB, RSBBB->begin(), dl,
10236 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10237 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10238 .addImm(0)
10239 .add(predOps(ARMCC::AL))
10240 .add(condCodeOp());
10242 // insert PHI in SinkBB,
10243 // reuse ABSDstReg to not change uses of ABS instruction
10244 BuildMI(*SinkBB, SinkBB->begin(), dl,
10245 TII->get(ARM::PHI), ABSDstReg)
10246 .addReg(NewRsbDstReg).addMBB(RSBBB)
10247 .addReg(ABSSrcReg).addMBB(BB);
10249 // remove ABS instruction
10250 MI.eraseFromParent();
10252 // return last added BB
10253 return SinkBB;
10255 case ARM::COPY_STRUCT_BYVAL_I32:
10256 ++NumLoopByVals;
10257 return EmitStructByval(MI, BB);
10258 case ARM::WIN__CHKSTK:
10259 return EmitLowered__chkstk(MI, BB);
10260 case ARM::WIN__DBZCHK:
10261 return EmitLowered__dbzchk(MI, BB);
10265 /// Attaches vregs to MEMCPY that it will use as scratch registers
10266 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10267 /// instead of as a custom inserter because we need the use list from the SDNode.
10268 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10269 MachineInstr &MI, const SDNode *Node) {
10270 bool isThumb1 = Subtarget->isThumb1Only();
10272 DebugLoc DL = MI.getDebugLoc();
10273 MachineFunction *MF = MI.getParent()->getParent();
10274 MachineRegisterInfo &MRI = MF->getRegInfo();
10275 MachineInstrBuilder MIB(*MF, MI);
10277 // If the new dst/src is unused mark it as dead.
10278 if (!Node->hasAnyUseOfValue(0)) {
10279 MI.getOperand(0).setIsDead(true);
10281 if (!Node->hasAnyUseOfValue(1)) {
10282 MI.getOperand(1).setIsDead(true);
10285 // The MEMCPY both defines and kills the scratch registers.
10286 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10287 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10288 : &ARM::GPRRegClass);
10289 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10293 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10294 SDNode *Node) const {
10295 if (MI.getOpcode() == ARM::MEMCPY) {
10296 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10297 return;
10300 const MCInstrDesc *MCID = &MI.getDesc();
10301 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10302 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10303 // operand is still set to noreg. If needed, set the optional operand's
10304 // register to CPSR, and remove the redundant implicit def.
10306 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10308 // Rename pseudo opcodes.
10309 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10310 unsigned ccOutIdx;
10311 if (NewOpc) {
10312 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10313 MCID = &TII->get(NewOpc);
10315 assert(MCID->getNumOperands() ==
10316 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10317 && "converted opcode should be the same except for cc_out"
10318 " (and, on Thumb1, pred)");
10320 MI.setDesc(*MCID);
10322 // Add the optional cc_out operand
10323 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10325 // On Thumb1, move all input operands to the end, then add the predicate
10326 if (Subtarget->isThumb1Only()) {
10327 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10328 MI.addOperand(MI.getOperand(1));
10329 MI.RemoveOperand(1);
10332 // Restore the ties
10333 for (unsigned i = MI.getNumOperands(); i--;) {
10334 const MachineOperand& op = MI.getOperand(i);
10335 if (op.isReg() && op.isUse()) {
10336 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10337 if (DefIdx != -1)
10338 MI.tieOperands(DefIdx, i);
10342 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10343 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10344 ccOutIdx = 1;
10345 } else
10346 ccOutIdx = MCID->getNumOperands() - 1;
10347 } else
10348 ccOutIdx = MCID->getNumOperands() - 1;
10350 // Any ARM instruction that sets the 's' bit should specify an optional
10351 // "cc_out" operand in the last operand position.
10352 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10353 assert(!NewOpc && "Optional cc_out operand required");
10354 return;
10356 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10357 // since we already have an optional CPSR def.
10358 bool definesCPSR = false;
10359 bool deadCPSR = false;
10360 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10361 ++i) {
10362 const MachineOperand &MO = MI.getOperand(i);
10363 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10364 definesCPSR = true;
10365 if (MO.isDead())
10366 deadCPSR = true;
10367 MI.RemoveOperand(i);
10368 break;
10371 if (!definesCPSR) {
10372 assert(!NewOpc && "Optional cc_out operand required");
10373 return;
10375 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10376 if (deadCPSR) {
10377 assert(!MI.getOperand(ccOutIdx).getReg() &&
10378 "expect uninitialized optional cc_out operand");
10379 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10380 if (!Subtarget->isThumb1Only())
10381 return;
10384 // If this instruction was defined with an optional CPSR def and its dag node
10385 // had a live implicit CPSR def, then activate the optional CPSR def.
10386 MachineOperand &MO = MI.getOperand(ccOutIdx);
10387 MO.setReg(ARM::CPSR);
10388 MO.setIsDef(true);
10391 //===----------------------------------------------------------------------===//
10392 // ARM Optimization Hooks
10393 //===----------------------------------------------------------------------===//
10395 // Helper function that checks if N is a null or all ones constant.
10396 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10397 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10400 // Return true if N is conditionally 0 or all ones.
10401 // Detects these expressions where cc is an i1 value:
10403 // (select cc 0, y) [AllOnes=0]
10404 // (select cc y, 0) [AllOnes=0]
10405 // (zext cc) [AllOnes=0]
10406 // (sext cc) [AllOnes=0/1]
10407 // (select cc -1, y) [AllOnes=1]
10408 // (select cc y, -1) [AllOnes=1]
10410 // Invert is set when N is the null/all ones constant when CC is false.
10411 // OtherOp is set to the alternative value of N.
10412 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10413 SDValue &CC, bool &Invert,
10414 SDValue &OtherOp,
10415 SelectionDAG &DAG) {
10416 switch (N->getOpcode()) {
10417 default: return false;
10418 case ISD::SELECT: {
10419 CC = N->getOperand(0);
10420 SDValue N1 = N->getOperand(1);
10421 SDValue N2 = N->getOperand(2);
10422 if (isZeroOrAllOnes(N1, AllOnes)) {
10423 Invert = false;
10424 OtherOp = N2;
10425 return true;
10427 if (isZeroOrAllOnes(N2, AllOnes)) {
10428 Invert = true;
10429 OtherOp = N1;
10430 return true;
10432 return false;
10434 case ISD::ZERO_EXTEND:
10435 // (zext cc) can never be the all ones value.
10436 if (AllOnes)
10437 return false;
10438 LLVM_FALLTHROUGH;
10439 case ISD::SIGN_EXTEND: {
10440 SDLoc dl(N);
10441 EVT VT = N->getValueType(0);
10442 CC = N->getOperand(0);
10443 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10444 return false;
10445 Invert = !AllOnes;
10446 if (AllOnes)
10447 // When looking for an AllOnes constant, N is an sext, and the 'other'
10448 // value is 0.
10449 OtherOp = DAG.getConstant(0, dl, VT);
10450 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10451 // When looking for a 0 constant, N can be zext or sext.
10452 OtherOp = DAG.getConstant(1, dl, VT);
10453 else
10454 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10455 VT);
10456 return true;
10461 // Combine a constant select operand into its use:
10463 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10464 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10465 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10466 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10467 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10469 // The transform is rejected if the select doesn't have a constant operand that
10470 // is null, or all ones when AllOnes is set.
10472 // Also recognize sext/zext from i1:
10474 // (add (zext cc), x) -> (select cc (add x, 1), x)
10475 // (add (sext cc), x) -> (select cc (add x, -1), x)
10477 // These transformations eventually create predicated instructions.
10479 // @param N The node to transform.
10480 // @param Slct The N operand that is a select.
10481 // @param OtherOp The other N operand (x above).
10482 // @param DCI Context.
10483 // @param AllOnes Require the select constant to be all ones instead of null.
10484 // @returns The new node, or SDValue() on failure.
10485 static
10486 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10487 TargetLowering::DAGCombinerInfo &DCI,
10488 bool AllOnes = false) {
10489 SelectionDAG &DAG = DCI.DAG;
10490 EVT VT = N->getValueType(0);
10491 SDValue NonConstantVal;
10492 SDValue CCOp;
10493 bool SwapSelectOps;
10494 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10495 NonConstantVal, DAG))
10496 return SDValue();
10498 // Slct is now know to be the desired identity constant when CC is true.
10499 SDValue TrueVal = OtherOp;
10500 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10501 OtherOp, NonConstantVal);
10502 // Unless SwapSelectOps says CC should be false.
10503 if (SwapSelectOps)
10504 std::swap(TrueVal, FalseVal);
10506 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10507 CCOp, TrueVal, FalseVal);
10510 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10511 static
10512 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10513 TargetLowering::DAGCombinerInfo &DCI) {
10514 SDValue N0 = N->getOperand(0);
10515 SDValue N1 = N->getOperand(1);
10516 if (N0.getNode()->hasOneUse())
10517 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10518 return Result;
10519 if (N1.getNode()->hasOneUse())
10520 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10521 return Result;
10522 return SDValue();
10525 static bool IsVUZPShuffleNode(SDNode *N) {
10526 // VUZP shuffle node.
10527 if (N->getOpcode() == ARMISD::VUZP)
10528 return true;
10530 // "VUZP" on i32 is an alias for VTRN.
10531 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10532 return true;
10534 return false;
10537 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10538 TargetLowering::DAGCombinerInfo &DCI,
10539 const ARMSubtarget *Subtarget) {
10540 // Look for ADD(VUZP.0, VUZP.1).
10541 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10542 N0 == N1)
10543 return SDValue();
10545 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10546 if (!N->getValueType(0).is64BitVector())
10547 return SDValue();
10549 // Generate vpadd.
10550 SelectionDAG &DAG = DCI.DAG;
10551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10552 SDLoc dl(N);
10553 SDNode *Unzip = N0.getNode();
10554 EVT VT = N->getValueType(0);
10556 SmallVector<SDValue, 8> Ops;
10557 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10558 TLI.getPointerTy(DAG.getDataLayout())));
10559 Ops.push_back(Unzip->getOperand(0));
10560 Ops.push_back(Unzip->getOperand(1));
10562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10565 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10566 TargetLowering::DAGCombinerInfo &DCI,
10567 const ARMSubtarget *Subtarget) {
10568 // Check for two extended operands.
10569 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10570 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10571 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10572 N1.getOpcode() == ISD::ZERO_EXTEND))
10573 return SDValue();
10575 SDValue N00 = N0.getOperand(0);
10576 SDValue N10 = N1.getOperand(0);
10578 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10579 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10580 N00 == N10)
10581 return SDValue();
10583 // We only recognize Q register paddl here; this can't be reached until
10584 // after type legalization.
10585 if (!N00.getValueType().is64BitVector() ||
10586 !N0.getValueType().is128BitVector())
10587 return SDValue();
10589 // Generate vpaddl.
10590 SelectionDAG &DAG = DCI.DAG;
10591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10592 SDLoc dl(N);
10593 EVT VT = N->getValueType(0);
10595 SmallVector<SDValue, 8> Ops;
10596 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10597 unsigned Opcode;
10598 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10599 Opcode = Intrinsic::arm_neon_vpaddls;
10600 else
10601 Opcode = Intrinsic::arm_neon_vpaddlu;
10602 Ops.push_back(DAG.getConstant(Opcode, dl,
10603 TLI.getPointerTy(DAG.getDataLayout())));
10604 EVT ElemTy = N00.getValueType().getVectorElementType();
10605 unsigned NumElts = VT.getVectorNumElements();
10606 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10607 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10608 N00.getOperand(0), N00.getOperand(1));
10609 Ops.push_back(Concat);
10611 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10614 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10615 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10616 // much easier to match.
10617 static SDValue
10618 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10619 TargetLowering::DAGCombinerInfo &DCI,
10620 const ARMSubtarget *Subtarget) {
10621 // Only perform optimization if after legalize, and if NEON is available. We
10622 // also expected both operands to be BUILD_VECTORs.
10623 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10624 || N0.getOpcode() != ISD::BUILD_VECTOR
10625 || N1.getOpcode() != ISD::BUILD_VECTOR)
10626 return SDValue();
10628 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10629 EVT VT = N->getValueType(0);
10630 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10631 return SDValue();
10633 // Check that the vector operands are of the right form.
10634 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10635 // operands, where N is the size of the formed vector.
10636 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10637 // index such that we have a pair wise add pattern.
10639 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10640 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10641 return SDValue();
10642 SDValue Vec = N0->getOperand(0)->getOperand(0);
10643 SDNode *V = Vec.getNode();
10644 unsigned nextIndex = 0;
10646 // For each operands to the ADD which are BUILD_VECTORs,
10647 // check to see if each of their operands are an EXTRACT_VECTOR with
10648 // the same vector and appropriate index.
10649 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10650 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10651 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10653 SDValue ExtVec0 = N0->getOperand(i);
10654 SDValue ExtVec1 = N1->getOperand(i);
10656 // First operand is the vector, verify its the same.
10657 if (V != ExtVec0->getOperand(0).getNode() ||
10658 V != ExtVec1->getOperand(0).getNode())
10659 return SDValue();
10661 // Second is the constant, verify its correct.
10662 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10663 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10665 // For the constant, we want to see all the even or all the odd.
10666 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10667 || C1->getZExtValue() != nextIndex+1)
10668 return SDValue();
10670 // Increment index.
10671 nextIndex+=2;
10672 } else
10673 return SDValue();
10676 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10677 // we're using the entire input vector, otherwise there's a size/legality
10678 // mismatch somewhere.
10679 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10680 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10681 return SDValue();
10683 // Create VPADDL node.
10684 SelectionDAG &DAG = DCI.DAG;
10685 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10687 SDLoc dl(N);
10689 // Build operand list.
10690 SmallVector<SDValue, 8> Ops;
10691 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10692 TLI.getPointerTy(DAG.getDataLayout())));
10694 // Input is the vector.
10695 Ops.push_back(Vec);
10697 // Get widened type and narrowed type.
10698 MVT widenType;
10699 unsigned numElem = VT.getVectorNumElements();
10701 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10702 switch (inputLaneType.getSimpleVT().SimpleTy) {
10703 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10704 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10705 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10706 default:
10707 llvm_unreachable("Invalid vector element type for padd optimization.");
10710 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10711 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10712 return DAG.getNode(ExtOp, dl, VT, tmp);
10715 static SDValue findMUL_LOHI(SDValue V) {
10716 if (V->getOpcode() == ISD::UMUL_LOHI ||
10717 V->getOpcode() == ISD::SMUL_LOHI)
10718 return V;
10719 return SDValue();
10722 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10723 TargetLowering::DAGCombinerInfo &DCI,
10724 const ARMSubtarget *Subtarget) {
10725 if (Subtarget->isThumb()) {
10726 if (!Subtarget->hasDSP())
10727 return SDValue();
10728 } else if (!Subtarget->hasV5TEOps())
10729 return SDValue();
10731 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10732 // accumulates the product into a 64-bit value. The 16-bit values will
10733 // be sign extended somehow or SRA'd into 32-bit values
10734 // (addc (adde (mul 16bit, 16bit), lo), hi)
10735 SDValue Mul = AddcNode->getOperand(0);
10736 SDValue Lo = AddcNode->getOperand(1);
10737 if (Mul.getOpcode() != ISD::MUL) {
10738 Lo = AddcNode->getOperand(0);
10739 Mul = AddcNode->getOperand(1);
10740 if (Mul.getOpcode() != ISD::MUL)
10741 return SDValue();
10744 SDValue SRA = AddeNode->getOperand(0);
10745 SDValue Hi = AddeNode->getOperand(1);
10746 if (SRA.getOpcode() != ISD::SRA) {
10747 SRA = AddeNode->getOperand(1);
10748 Hi = AddeNode->getOperand(0);
10749 if (SRA.getOpcode() != ISD::SRA)
10750 return SDValue();
10752 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10753 if (Const->getZExtValue() != 31)
10754 return SDValue();
10755 } else
10756 return SDValue();
10758 if (SRA.getOperand(0) != Mul)
10759 return SDValue();
10761 SelectionDAG &DAG = DCI.DAG;
10762 SDLoc dl(AddcNode);
10763 unsigned Opcode = 0;
10764 SDValue Op0;
10765 SDValue Op1;
10767 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10768 Opcode = ARMISD::SMLALBB;
10769 Op0 = Mul.getOperand(0);
10770 Op1 = Mul.getOperand(1);
10771 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10772 Opcode = ARMISD::SMLALBT;
10773 Op0 = Mul.getOperand(0);
10774 Op1 = Mul.getOperand(1).getOperand(0);
10775 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10776 Opcode = ARMISD::SMLALTB;
10777 Op0 = Mul.getOperand(0).getOperand(0);
10778 Op1 = Mul.getOperand(1);
10779 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10780 Opcode = ARMISD::SMLALTT;
10781 Op0 = Mul->getOperand(0).getOperand(0);
10782 Op1 = Mul->getOperand(1).getOperand(0);
10785 if (!Op0 || !Op1)
10786 return SDValue();
10788 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10789 Op0, Op1, Lo, Hi);
10790 // Replace the ADDs' nodes uses by the MLA node's values.
10791 SDValue HiMLALResult(SMLAL.getNode(), 1);
10792 SDValue LoMLALResult(SMLAL.getNode(), 0);
10794 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10795 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10797 // Return original node to notify the driver to stop replacing.
10798 SDValue resNode(AddcNode, 0);
10799 return resNode;
10802 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10803 TargetLowering::DAGCombinerInfo &DCI,
10804 const ARMSubtarget *Subtarget) {
10805 // Look for multiply add opportunities.
10806 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10807 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10808 // a glue link from the first add to the second add.
10809 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10810 // a S/UMLAL instruction.
10811 // UMUL_LOHI
10812 // / :lo \ :hi
10813 // V \ [no multiline comment]
10814 // loAdd -> ADDC |
10815 // \ :carry /
10816 // V V
10817 // ADDE <- hiAdd
10819 // In the special case where only the higher part of a signed result is used
10820 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10821 // a constant with the exact value of 0x80000000, we recognize we are dealing
10822 // with a "rounded multiply and add" (or subtract) and transform it into
10823 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10825 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10826 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10827 "Expect an ADDE or SUBE");
10829 assert(AddeSubeNode->getNumOperands() == 3 &&
10830 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10831 "ADDE node has the wrong inputs");
10833 // Check that we are chained to the right ADDC or SUBC node.
10834 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10835 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10836 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10837 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10838 AddcSubcNode->getOpcode() != ARMISD::SUBC))
10839 return SDValue();
10841 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10842 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10844 // Check if the two operands are from the same mul_lohi node.
10845 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10846 return SDValue();
10848 assert(AddcSubcNode->getNumValues() == 2 &&
10849 AddcSubcNode->getValueType(0) == MVT::i32 &&
10850 "Expect ADDC with two result values. First: i32");
10852 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10853 // maybe a SMLAL which multiplies two 16-bit values.
10854 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10855 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10856 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10857 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10858 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10859 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10861 // Check for the triangle shape.
10862 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10863 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10865 // Make sure that the ADDE/SUBE operands are not coming from the same node.
10866 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10867 return SDValue();
10869 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10870 bool IsLeftOperandMUL = false;
10871 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10872 if (MULOp == SDValue())
10873 MULOp = findMUL_LOHI(AddeSubeOp1);
10874 else
10875 IsLeftOperandMUL = true;
10876 if (MULOp == SDValue())
10877 return SDValue();
10879 // Figure out the right opcode.
10880 unsigned Opc = MULOp->getOpcode();
10881 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10883 // Figure out the high and low input values to the MLAL node.
10884 SDValue *HiAddSub = nullptr;
10885 SDValue *LoMul = nullptr;
10886 SDValue *LowAddSub = nullptr;
10888 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10889 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10890 return SDValue();
10892 if (IsLeftOperandMUL)
10893 HiAddSub = &AddeSubeOp1;
10894 else
10895 HiAddSub = &AddeSubeOp0;
10897 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10898 // whose low result is fed to the ADDC/SUBC we are checking.
10900 if (AddcSubcOp0 == MULOp.getValue(0)) {
10901 LoMul = &AddcSubcOp0;
10902 LowAddSub = &AddcSubcOp1;
10904 if (AddcSubcOp1 == MULOp.getValue(0)) {
10905 LoMul = &AddcSubcOp1;
10906 LowAddSub = &AddcSubcOp0;
10909 if (!LoMul)
10910 return SDValue();
10912 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10913 // the replacement below will create a cycle.
10914 if (AddcSubcNode == HiAddSub->getNode() ||
10915 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10916 return SDValue();
10918 // Create the merged node.
10919 SelectionDAG &DAG = DCI.DAG;
10921 // Start building operand list.
10922 SmallVector<SDValue, 8> Ops;
10923 Ops.push_back(LoMul->getOperand(0));
10924 Ops.push_back(LoMul->getOperand(1));
10926 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
10927 // the case, we must be doing signed multiplication and only use the higher
10928 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10929 // addition or subtraction with the value of 0x800000.
10930 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10931 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10932 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10933 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10934 0x80000000) {
10935 Ops.push_back(*HiAddSub);
10936 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10937 FinalOpc = ARMISD::SMMLSR;
10938 } else {
10939 FinalOpc = ARMISD::SMMLAR;
10941 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10942 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10944 return SDValue(AddeSubeNode, 0);
10945 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10946 // SMMLS is generated during instruction selection and the rest of this
10947 // function can not handle the case where AddcSubcNode is a SUBC.
10948 return SDValue();
10950 // Finish building the operand list for {U/S}MLAL
10951 Ops.push_back(*LowAddSub);
10952 Ops.push_back(*HiAddSub);
10954 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10955 DAG.getVTList(MVT::i32, MVT::i32), Ops);
10957 // Replace the ADDs' nodes uses by the MLA node's values.
10958 SDValue HiMLALResult(MLALNode.getNode(), 1);
10959 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10961 SDValue LoMLALResult(MLALNode.getNode(), 0);
10962 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10964 // Return original node to notify the driver to stop replacing.
10965 return SDValue(AddeSubeNode, 0);
10968 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10969 TargetLowering::DAGCombinerInfo &DCI,
10970 const ARMSubtarget *Subtarget) {
10971 // UMAAL is similar to UMLAL except that it adds two unsigned values.
10972 // While trying to combine for the other MLAL nodes, first search for the
10973 // chance to use UMAAL. Check if Addc uses a node which has already
10974 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10975 // as the addend, and it's handled in PerformUMLALCombine.
10977 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10978 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10980 // Check that we have a glued ADDC node.
10981 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10982 if (AddcNode->getOpcode() != ARMISD::ADDC)
10983 return SDValue();
10985 // Find the converted UMAAL or quit if it doesn't exist.
10986 SDNode *UmlalNode = nullptr;
10987 SDValue AddHi;
10988 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10989 UmlalNode = AddcNode->getOperand(0).getNode();
10990 AddHi = AddcNode->getOperand(1);
10991 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10992 UmlalNode = AddcNode->getOperand(1).getNode();
10993 AddHi = AddcNode->getOperand(0);
10994 } else {
10995 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10998 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10999 // the ADDC as well as Zero.
11000 if (!isNullConstant(UmlalNode->getOperand(3)))
11001 return SDValue();
11003 if ((isNullConstant(AddeNode->getOperand(0)) &&
11004 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11005 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11006 isNullConstant(AddeNode->getOperand(1)))) {
11007 SelectionDAG &DAG = DCI.DAG;
11008 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11009 UmlalNode->getOperand(2), AddHi };
11010 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11011 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11013 // Replace the ADDs' nodes uses by the UMAAL node's values.
11014 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11015 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11017 // Return original node to notify the driver to stop replacing.
11018 return SDValue(AddeNode, 0);
11020 return SDValue();
11023 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11024 const ARMSubtarget *Subtarget) {
11025 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11026 return SDValue();
11028 // Check that we have a pair of ADDC and ADDE as operands.
11029 // Both addends of the ADDE must be zero.
11030 SDNode* AddcNode = N->getOperand(2).getNode();
11031 SDNode* AddeNode = N->getOperand(3).getNode();
11032 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11033 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11034 isNullConstant(AddeNode->getOperand(0)) &&
11035 isNullConstant(AddeNode->getOperand(1)) &&
11036 (AddeNode->getOperand(2).getNode() == AddcNode))
11037 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11038 DAG.getVTList(MVT::i32, MVT::i32),
11039 {N->getOperand(0), N->getOperand(1),
11040 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11041 else
11042 return SDValue();
11045 static SDValue PerformAddcSubcCombine(SDNode *N,
11046 TargetLowering::DAGCombinerInfo &DCI,
11047 const ARMSubtarget *Subtarget) {
11048 SelectionDAG &DAG(DCI.DAG);
11050 if (N->getOpcode() == ARMISD::SUBC) {
11051 // (SUBC (ADDE 0, 0, C), 1) -> C
11052 SDValue LHS = N->getOperand(0);
11053 SDValue RHS = N->getOperand(1);
11054 if (LHS->getOpcode() == ARMISD::ADDE &&
11055 isNullConstant(LHS->getOperand(0)) &&
11056 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11057 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11061 if (Subtarget->isThumb1Only()) {
11062 SDValue RHS = N->getOperand(1);
11063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11064 int32_t imm = C->getSExtValue();
11065 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11066 SDLoc DL(N);
11067 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11068 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11069 : ARMISD::ADDC;
11070 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11075 return SDValue();
11078 static SDValue PerformAddeSubeCombine(SDNode *N,
11079 TargetLowering::DAGCombinerInfo &DCI,
11080 const ARMSubtarget *Subtarget) {
11081 if (Subtarget->isThumb1Only()) {
11082 SelectionDAG &DAG = DCI.DAG;
11083 SDValue RHS = N->getOperand(1);
11084 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11085 int64_t imm = C->getSExtValue();
11086 if (imm < 0) {
11087 SDLoc DL(N);
11089 // The with-carry-in form matches bitwise not instead of the negation.
11090 // Effectively, the inverse interpretation of the carry flag already
11091 // accounts for part of the negation.
11092 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11094 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11095 : ARMISD::ADDE;
11096 return DAG.getNode(Opcode, DL, N->getVTList(),
11097 N->getOperand(0), RHS, N->getOperand(2));
11100 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11101 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11103 return SDValue();
11106 static SDValue PerformABSCombine(SDNode *N,
11107 TargetLowering::DAGCombinerInfo &DCI,
11108 const ARMSubtarget *Subtarget) {
11109 SDValue res;
11110 SelectionDAG &DAG = DCI.DAG;
11111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11113 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11114 return SDValue();
11116 if (!TLI.expandABS(N, res, DAG))
11117 return SDValue();
11119 return res;
11122 /// PerformADDECombine - Target-specific dag combine transform from
11123 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11124 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11125 static SDValue PerformADDECombine(SDNode *N,
11126 TargetLowering::DAGCombinerInfo &DCI,
11127 const ARMSubtarget *Subtarget) {
11128 // Only ARM and Thumb2 support UMLAL/SMLAL.
11129 if (Subtarget->isThumb1Only())
11130 return PerformAddeSubeCombine(N, DCI, Subtarget);
11132 // Only perform the checks after legalize when the pattern is available.
11133 if (DCI.isBeforeLegalize()) return SDValue();
11135 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11138 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11139 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11140 /// called with the default operands, and if that fails, with commuted
11141 /// operands.
11142 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11143 TargetLowering::DAGCombinerInfo &DCI,
11144 const ARMSubtarget *Subtarget){
11145 // Attempt to create vpadd for this add.
11146 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11147 return Result;
11149 // Attempt to create vpaddl for this add.
11150 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11151 return Result;
11152 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11153 Subtarget))
11154 return Result;
11156 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11157 if (N0.getNode()->hasOneUse())
11158 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11159 return Result;
11160 return SDValue();
11163 bool
11164 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11165 CombineLevel Level) const {
11166 if (Level == BeforeLegalizeTypes)
11167 return true;
11169 if (N->getOpcode() != ISD::SHL)
11170 return true;
11172 if (Subtarget->isThumb1Only()) {
11173 // Avoid making expensive immediates by commuting shifts. (This logic
11174 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11175 // for free.)
11176 if (N->getOpcode() != ISD::SHL)
11177 return true;
11178 SDValue N1 = N->getOperand(0);
11179 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11180 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11181 return true;
11182 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11183 if (Const->getAPIntValue().ult(256))
11184 return false;
11185 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11186 Const->getAPIntValue().sgt(-256))
11187 return false;
11189 return true;
11192 // Turn off commute-with-shift transform after legalization, so it doesn't
11193 // conflict with PerformSHLSimplify. (We could try to detect when
11194 // PerformSHLSimplify would trigger more precisely, but it isn't
11195 // really necessary.)
11196 return false;
11199 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11200 const SDNode *N, CombineLevel Level) const {
11201 if (!Subtarget->isThumb1Only())
11202 return true;
11204 if (Level == BeforeLegalizeTypes)
11205 return true;
11207 return false;
11210 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11211 if (!Subtarget->hasNEON()) {
11212 if (Subtarget->isThumb1Only())
11213 return VT.getScalarSizeInBits() <= 32;
11214 return true;
11216 return VT.isScalarInteger();
11219 static SDValue PerformSHLSimplify(SDNode *N,
11220 TargetLowering::DAGCombinerInfo &DCI,
11221 const ARMSubtarget *ST) {
11222 // Allow the generic combiner to identify potential bswaps.
11223 if (DCI.isBeforeLegalize())
11224 return SDValue();
11226 // DAG combiner will fold:
11227 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11228 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11229 // Other code patterns that can be also be modified have the following form:
11230 // b + ((a << 1) | 510)
11231 // b + ((a << 1) & 510)
11232 // b + ((a << 1) ^ 510)
11233 // b + ((a << 1) + 510)
11235 // Many instructions can perform the shift for free, but it requires both
11236 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11237 // instruction will needed. So, unfold back to the original pattern if:
11238 // - if c1 and c2 are small enough that they don't require mov imms.
11239 // - the user(s) of the node can perform an shl
11241 // No shifted operands for 16-bit instructions.
11242 if (ST->isThumb() && ST->isThumb1Only())
11243 return SDValue();
11245 // Check that all the users could perform the shl themselves.
11246 for (auto U : N->uses()) {
11247 switch(U->getOpcode()) {
11248 default:
11249 return SDValue();
11250 case ISD::SUB:
11251 case ISD::ADD:
11252 case ISD::AND:
11253 case ISD::OR:
11254 case ISD::XOR:
11255 case ISD::SETCC:
11256 case ARMISD::CMP:
11257 // Check that the user isn't already using a constant because there
11258 // aren't any instructions that support an immediate operand and a
11259 // shifted operand.
11260 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11261 isa<ConstantSDNode>(U->getOperand(1)))
11262 return SDValue();
11264 // Check that it's not already using a shift.
11265 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11266 U->getOperand(1).getOpcode() == ISD::SHL)
11267 return SDValue();
11268 break;
11272 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11273 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11274 return SDValue();
11276 if (N->getOperand(0).getOpcode() != ISD::SHL)
11277 return SDValue();
11279 SDValue SHL = N->getOperand(0);
11281 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11282 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11283 if (!C1ShlC2 || !C2)
11284 return SDValue();
11286 APInt C2Int = C2->getAPIntValue();
11287 APInt C1Int = C1ShlC2->getAPIntValue();
11289 // Check that performing a lshr will not lose any information.
11290 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11291 C2Int.getBitWidth() - C2->getZExtValue());
11292 if ((C1Int & Mask) != C1Int)
11293 return SDValue();
11295 // Shift the first constant.
11296 C1Int.lshrInPlace(C2Int);
11298 // The immediates are encoded as an 8-bit value that can be rotated.
11299 auto LargeImm = [](const APInt &Imm) {
11300 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11301 return Imm.getBitWidth() - Zeros > 8;
11304 if (LargeImm(C1Int) || LargeImm(C2Int))
11305 return SDValue();
11307 SelectionDAG &DAG = DCI.DAG;
11308 SDLoc dl(N);
11309 SDValue X = SHL.getOperand(0);
11310 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11311 DAG.getConstant(C1Int, dl, MVT::i32));
11312 // Shift left to compensate for the lshr of C1Int.
11313 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11315 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11316 SHL.dump(); N->dump());
11317 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11318 return Res;
11322 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11324 static SDValue PerformADDCombine(SDNode *N,
11325 TargetLowering::DAGCombinerInfo &DCI,
11326 const ARMSubtarget *Subtarget) {
11327 SDValue N0 = N->getOperand(0);
11328 SDValue N1 = N->getOperand(1);
11330 // Only works one way, because it needs an immediate operand.
11331 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11332 return Result;
11334 // First try with the default operand order.
11335 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11336 return Result;
11338 // If that didn't work, try again with the operands commuted.
11339 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11342 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11344 static SDValue PerformSUBCombine(SDNode *N,
11345 TargetLowering::DAGCombinerInfo &DCI) {
11346 SDValue N0 = N->getOperand(0);
11347 SDValue N1 = N->getOperand(1);
11349 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11350 if (N1.getNode()->hasOneUse())
11351 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11352 return Result;
11354 return SDValue();
11357 /// PerformVMULCombine
11358 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11359 /// special multiplier accumulator forwarding.
11360 /// vmul d3, d0, d2
11361 /// vmla d3, d1, d2
11362 /// is faster than
11363 /// vadd d3, d0, d1
11364 /// vmul d3, d3, d2
11365 // However, for (A + B) * (A + B),
11366 // vadd d2, d0, d1
11367 // vmul d3, d0, d2
11368 // vmla d3, d1, d2
11369 // is slower than
11370 // vadd d2, d0, d1
11371 // vmul d3, d2, d2
11372 static SDValue PerformVMULCombine(SDNode *N,
11373 TargetLowering::DAGCombinerInfo &DCI,
11374 const ARMSubtarget *Subtarget) {
11375 if (!Subtarget->hasVMLxForwarding())
11376 return SDValue();
11378 SelectionDAG &DAG = DCI.DAG;
11379 SDValue N0 = N->getOperand(0);
11380 SDValue N1 = N->getOperand(1);
11381 unsigned Opcode = N0.getOpcode();
11382 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11383 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11384 Opcode = N1.getOpcode();
11385 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11386 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11387 return SDValue();
11388 std::swap(N0, N1);
11391 if (N0 == N1)
11392 return SDValue();
11394 EVT VT = N->getValueType(0);
11395 SDLoc DL(N);
11396 SDValue N00 = N0->getOperand(0);
11397 SDValue N01 = N0->getOperand(1);
11398 return DAG.getNode(Opcode, DL, VT,
11399 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11400 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11403 static SDValue PerformMULCombine(SDNode *N,
11404 TargetLowering::DAGCombinerInfo &DCI,
11405 const ARMSubtarget *Subtarget) {
11406 SelectionDAG &DAG = DCI.DAG;
11408 if (Subtarget->isThumb1Only())
11409 return SDValue();
11411 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11412 return SDValue();
11414 EVT VT = N->getValueType(0);
11415 if (VT.is64BitVector() || VT.is128BitVector())
11416 return PerformVMULCombine(N, DCI, Subtarget);
11417 if (VT != MVT::i32)
11418 return SDValue();
11420 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11421 if (!C)
11422 return SDValue();
11424 int64_t MulAmt = C->getSExtValue();
11425 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11427 ShiftAmt = ShiftAmt & (32 - 1);
11428 SDValue V = N->getOperand(0);
11429 SDLoc DL(N);
11431 SDValue Res;
11432 MulAmt >>= ShiftAmt;
11434 if (MulAmt >= 0) {
11435 if (isPowerOf2_32(MulAmt - 1)) {
11436 // (mul x, 2^N + 1) => (add (shl x, N), x)
11437 Res = DAG.getNode(ISD::ADD, DL, VT,
11439 DAG.getNode(ISD::SHL, DL, VT,
11441 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11442 MVT::i32)));
11443 } else if (isPowerOf2_32(MulAmt + 1)) {
11444 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11445 Res = DAG.getNode(ISD::SUB, DL, VT,
11446 DAG.getNode(ISD::SHL, DL, VT,
11448 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11449 MVT::i32)),
11451 } else
11452 return SDValue();
11453 } else {
11454 uint64_t MulAmtAbs = -MulAmt;
11455 if (isPowerOf2_32(MulAmtAbs + 1)) {
11456 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11457 Res = DAG.getNode(ISD::SUB, DL, VT,
11459 DAG.getNode(ISD::SHL, DL, VT,
11461 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11462 MVT::i32)));
11463 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11464 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11465 Res = DAG.getNode(ISD::ADD, DL, VT,
11467 DAG.getNode(ISD::SHL, DL, VT,
11469 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11470 MVT::i32)));
11471 Res = DAG.getNode(ISD::SUB, DL, VT,
11472 DAG.getConstant(0, DL, MVT::i32), Res);
11473 } else
11474 return SDValue();
11477 if (ShiftAmt != 0)
11478 Res = DAG.getNode(ISD::SHL, DL, VT,
11479 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11481 // Do not add new nodes to DAG combiner worklist.
11482 DCI.CombineTo(N, Res, false);
11483 return SDValue();
11486 static SDValue CombineANDShift(SDNode *N,
11487 TargetLowering::DAGCombinerInfo &DCI,
11488 const ARMSubtarget *Subtarget) {
11489 // Allow DAGCombine to pattern-match before we touch the canonical form.
11490 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11491 return SDValue();
11493 if (N->getValueType(0) != MVT::i32)
11494 return SDValue();
11496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11497 if (!N1C)
11498 return SDValue();
11500 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11501 // Don't transform uxtb/uxth.
11502 if (C1 == 255 || C1 == 65535)
11503 return SDValue();
11505 SDNode *N0 = N->getOperand(0).getNode();
11506 if (!N0->hasOneUse())
11507 return SDValue();
11509 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11510 return SDValue();
11512 bool LeftShift = N0->getOpcode() == ISD::SHL;
11514 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11515 if (!N01C)
11516 return SDValue();
11518 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11519 if (!C2 || C2 >= 32)
11520 return SDValue();
11522 // Clear irrelevant bits in the mask.
11523 if (LeftShift)
11524 C1 &= (-1U << C2);
11525 else
11526 C1 &= (-1U >> C2);
11528 SelectionDAG &DAG = DCI.DAG;
11529 SDLoc DL(N);
11531 // We have a pattern of the form "(and (shl x, c2) c1)" or
11532 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11533 // transform to a pair of shifts, to save materializing c1.
11535 // First pattern: right shift, then mask off leading bits.
11536 // FIXME: Use demanded bits?
11537 if (!LeftShift && isMask_32(C1)) {
11538 uint32_t C3 = countLeadingZeros(C1);
11539 if (C2 < C3) {
11540 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11541 DAG.getConstant(C3 - C2, DL, MVT::i32));
11542 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11543 DAG.getConstant(C3, DL, MVT::i32));
11547 // First pattern, reversed: left shift, then mask off trailing bits.
11548 if (LeftShift && isMask_32(~C1)) {
11549 uint32_t C3 = countTrailingZeros(C1);
11550 if (C2 < C3) {
11551 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11552 DAG.getConstant(C3 - C2, DL, MVT::i32));
11553 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11554 DAG.getConstant(C3, DL, MVT::i32));
11558 // Second pattern: left shift, then mask off leading bits.
11559 // FIXME: Use demanded bits?
11560 if (LeftShift && isShiftedMask_32(C1)) {
11561 uint32_t Trailing = countTrailingZeros(C1);
11562 uint32_t C3 = countLeadingZeros(C1);
11563 if (Trailing == C2 && C2 + C3 < 32) {
11564 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11565 DAG.getConstant(C2 + C3, DL, MVT::i32));
11566 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11567 DAG.getConstant(C3, DL, MVT::i32));
11571 // Second pattern, reversed: right shift, then mask off trailing bits.
11572 // FIXME: Handle other patterns of known/demanded bits.
11573 if (!LeftShift && isShiftedMask_32(C1)) {
11574 uint32_t Leading = countLeadingZeros(C1);
11575 uint32_t C3 = countTrailingZeros(C1);
11576 if (Leading == C2 && C2 + C3 < 32) {
11577 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11578 DAG.getConstant(C2 + C3, DL, MVT::i32));
11579 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11580 DAG.getConstant(C3, DL, MVT::i32));
11584 // FIXME: Transform "(and (shl x, c2) c1)" ->
11585 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11586 // c1.
11587 return SDValue();
11590 static SDValue PerformANDCombine(SDNode *N,
11591 TargetLowering::DAGCombinerInfo &DCI,
11592 const ARMSubtarget *Subtarget) {
11593 // Attempt to use immediate-form VBIC
11594 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11595 SDLoc dl(N);
11596 EVT VT = N->getValueType(0);
11597 SelectionDAG &DAG = DCI.DAG;
11599 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11600 return SDValue();
11602 APInt SplatBits, SplatUndef;
11603 unsigned SplatBitSize;
11604 bool HasAnyUndefs;
11605 if (BVN && Subtarget->hasNEON() &&
11606 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11607 if (SplatBitSize <= 64) {
11608 EVT VbicVT;
11609 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11610 SplatUndef.getZExtValue(), SplatBitSize,
11611 DAG, dl, VbicVT, VT.is128BitVector(),
11612 OtherModImm);
11613 if (Val.getNode()) {
11614 SDValue Input =
11615 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11616 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11617 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11622 if (!Subtarget->isThumb1Only()) {
11623 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11624 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11625 return Result;
11627 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11628 return Result;
11631 if (Subtarget->isThumb1Only())
11632 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11633 return Result;
11635 return SDValue();
11638 // Try combining OR nodes to SMULWB, SMULWT.
11639 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11640 TargetLowering::DAGCombinerInfo &DCI,
11641 const ARMSubtarget *Subtarget) {
11642 if (!Subtarget->hasV6Ops() ||
11643 (Subtarget->isThumb() &&
11644 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11645 return SDValue();
11647 SDValue SRL = OR->getOperand(0);
11648 SDValue SHL = OR->getOperand(1);
11650 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11651 SRL = OR->getOperand(1);
11652 SHL = OR->getOperand(0);
11654 if (!isSRL16(SRL) || !isSHL16(SHL))
11655 return SDValue();
11657 // The first operands to the shifts need to be the two results from the
11658 // same smul_lohi node.
11659 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11660 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11661 return SDValue();
11663 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11664 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11665 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11666 return SDValue();
11668 // Now we have:
11669 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11670 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11671 // For SMUWB the 16-bit value will signed extended somehow.
11672 // For SMULWT only the SRA is required.
11673 // Check both sides of SMUL_LOHI
11674 SDValue OpS16 = SMULLOHI->getOperand(0);
11675 SDValue OpS32 = SMULLOHI->getOperand(1);
11677 SelectionDAG &DAG = DCI.DAG;
11678 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11679 OpS16 = OpS32;
11680 OpS32 = SMULLOHI->getOperand(0);
11683 SDLoc dl(OR);
11684 unsigned Opcode = 0;
11685 if (isS16(OpS16, DAG))
11686 Opcode = ARMISD::SMULWB;
11687 else if (isSRA16(OpS16)) {
11688 Opcode = ARMISD::SMULWT;
11689 OpS16 = OpS16->getOperand(0);
11691 else
11692 return SDValue();
11694 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11695 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11696 return SDValue(OR, 0);
11699 static SDValue PerformORCombineToBFI(SDNode *N,
11700 TargetLowering::DAGCombinerInfo &DCI,
11701 const ARMSubtarget *Subtarget) {
11702 // BFI is only available on V6T2+
11703 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11704 return SDValue();
11706 EVT VT = N->getValueType(0);
11707 SDValue N0 = N->getOperand(0);
11708 SDValue N1 = N->getOperand(1);
11709 SelectionDAG &DAG = DCI.DAG;
11710 SDLoc DL(N);
11711 // 1) or (and A, mask), val => ARMbfi A, val, mask
11712 // iff (val & mask) == val
11714 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11715 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11716 // && mask == ~mask2
11717 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11718 // && ~mask == mask2
11719 // (i.e., copy a bitfield value into another bitfield of the same width)
11721 if (VT != MVT::i32)
11722 return SDValue();
11724 SDValue N00 = N0.getOperand(0);
11726 // The value and the mask need to be constants so we can verify this is
11727 // actually a bitfield set. If the mask is 0xffff, we can do better
11728 // via a movt instruction, so don't use BFI in that case.
11729 SDValue MaskOp = N0.getOperand(1);
11730 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11731 if (!MaskC)
11732 return SDValue();
11733 unsigned Mask = MaskC->getZExtValue();
11734 if (Mask == 0xffff)
11735 return SDValue();
11736 SDValue Res;
11737 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11738 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11739 if (N1C) {
11740 unsigned Val = N1C->getZExtValue();
11741 if ((Val & ~Mask) != Val)
11742 return SDValue();
11744 if (ARM::isBitFieldInvertedMask(Mask)) {
11745 Val >>= countTrailingZeros(~Mask);
11747 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11748 DAG.getConstant(Val, DL, MVT::i32),
11749 DAG.getConstant(Mask, DL, MVT::i32));
11751 DCI.CombineTo(N, Res, false);
11752 // Return value from the original node to inform the combiner than N is
11753 // now dead.
11754 return SDValue(N, 0);
11756 } else if (N1.getOpcode() == ISD::AND) {
11757 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11758 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11759 if (!N11C)
11760 return SDValue();
11761 unsigned Mask2 = N11C->getZExtValue();
11763 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11764 // as is to match.
11765 if (ARM::isBitFieldInvertedMask(Mask) &&
11766 (Mask == ~Mask2)) {
11767 // The pack halfword instruction works better for masks that fit it,
11768 // so use that when it's available.
11769 if (Subtarget->hasDSP() &&
11770 (Mask == 0xffff || Mask == 0xffff0000))
11771 return SDValue();
11772 // 2a
11773 unsigned amt = countTrailingZeros(Mask2);
11774 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11775 DAG.getConstant(amt, DL, MVT::i32));
11776 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11777 DAG.getConstant(Mask, DL, MVT::i32));
11778 DCI.CombineTo(N, Res, false);
11779 // Return value from the original node to inform the combiner than N is
11780 // now dead.
11781 return SDValue(N, 0);
11782 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11783 (~Mask == Mask2)) {
11784 // The pack halfword instruction works better for masks that fit it,
11785 // so use that when it's available.
11786 if (Subtarget->hasDSP() &&
11787 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11788 return SDValue();
11789 // 2b
11790 unsigned lsb = countTrailingZeros(Mask);
11791 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11792 DAG.getConstant(lsb, DL, MVT::i32));
11793 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11794 DAG.getConstant(Mask2, DL, MVT::i32));
11795 DCI.CombineTo(N, Res, false);
11796 // Return value from the original node to inform the combiner than N is
11797 // now dead.
11798 return SDValue(N, 0);
11802 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11803 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11804 ARM::isBitFieldInvertedMask(~Mask)) {
11805 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11806 // where lsb(mask) == #shamt and masked bits of B are known zero.
11807 SDValue ShAmt = N00.getOperand(1);
11808 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11809 unsigned LSB = countTrailingZeros(Mask);
11810 if (ShAmtC != LSB)
11811 return SDValue();
11813 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11814 DAG.getConstant(~Mask, DL, MVT::i32));
11816 DCI.CombineTo(N, Res, false);
11817 // Return value from the original node to inform the combiner than N is
11818 // now dead.
11819 return SDValue(N, 0);
11822 return SDValue();
11825 static SDValue PerformORCombine_i1(SDNode *N,
11826 TargetLowering::DAGCombinerInfo &DCI,
11827 const ARMSubtarget *Subtarget) {
11828 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
11829 // together with predicates
11830 struct Codes {
11831 unsigned Opcode;
11832 unsigned Opposite;
11833 } InvertCodes[] = {
11834 {ARMISD::VCEQ, ARMISD::VCNE},
11835 {ARMISD::VCEQZ, ARMISD::VCNEZ},
11836 {ARMISD::VCGE, ARMISD::VCLT},
11837 {ARMISD::VCGEZ, ARMISD::VCLTZ},
11838 {ARMISD::VCGT, ARMISD::VCLE},
11839 {ARMISD::VCGTZ, ARMISD::VCLEZ},
11842 EVT VT = N->getValueType(0);
11843 SDValue N0 = N->getOperand(0);
11844 SDValue N1 = N->getOperand(1);
11846 unsigned Opposite0 = 0;
11847 unsigned Opposite1 = 0;
11848 for (auto Code : InvertCodes) {
11849 if (N0->getOpcode() == Code.Opcode)
11850 Opposite0 = Code.Opposite;
11851 if (N0->getOpcode() == Code.Opposite)
11852 Opposite0 = Code.Opcode;
11853 if (N1->getOpcode() == Code.Opcode)
11854 Opposite1 = Code.Opposite;
11855 if (N1->getOpcode() == Code.Opposite)
11856 Opposite1 = Code.Opcode;
11859 if (!Opposite0 || !Opposite1)
11860 return SDValue();
11862 SmallVector<SDValue, 4> Ops0;
11863 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i)
11864 Ops0.push_back(N0->getOperand(i));
11865 SmallVector<SDValue, 4> Ops1;
11866 for (unsigned i = 0, e = N1->getNumOperands(); i != e; ++i)
11867 Ops1.push_back(N1->getOperand(i));
11869 SDValue NewN0 = DCI.DAG.getNode(Opposite0, SDLoc(N0), VT, Ops0);
11870 SDValue NewN1 = DCI.DAG.getNode(Opposite1, SDLoc(N1), VT, Ops1);
11871 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
11872 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
11873 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
11876 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11877 static SDValue PerformORCombine(SDNode *N,
11878 TargetLowering::DAGCombinerInfo &DCI,
11879 const ARMSubtarget *Subtarget) {
11880 // Attempt to use immediate-form VORR
11881 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11882 SDLoc dl(N);
11883 EVT VT = N->getValueType(0);
11884 SelectionDAG &DAG = DCI.DAG;
11886 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11887 return SDValue();
11889 APInt SplatBits, SplatUndef;
11890 unsigned SplatBitSize;
11891 bool HasAnyUndefs;
11892 if (BVN && Subtarget->hasNEON() &&
11893 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11894 if (SplatBitSize <= 64) {
11895 EVT VorrVT;
11896 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
11897 SplatUndef.getZExtValue(), SplatBitSize,
11898 DAG, dl, VorrVT, VT.is128BitVector(),
11899 OtherModImm);
11900 if (Val.getNode()) {
11901 SDValue Input =
11902 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11903 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11904 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11909 if (!Subtarget->isThumb1Only()) {
11910 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11911 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11912 return Result;
11913 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11914 return Result;
11917 SDValue N0 = N->getOperand(0);
11918 SDValue N1 = N->getOperand(1);
11920 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11921 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11922 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11924 // The code below optimizes (or (and X, Y), Z).
11925 // The AND operand needs to have a single user to make these optimizations
11926 // profitable.
11927 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11928 return SDValue();
11930 APInt SplatUndef;
11931 unsigned SplatBitSize;
11932 bool HasAnyUndefs;
11934 APInt SplatBits0, SplatBits1;
11935 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11936 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11937 // Ensure that the second operand of both ands are constants
11938 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11939 HasAnyUndefs) && !HasAnyUndefs) {
11940 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11941 HasAnyUndefs) && !HasAnyUndefs) {
11942 // Ensure that the bit width of the constants are the same and that
11943 // the splat arguments are logical inverses as per the pattern we
11944 // are trying to simplify.
11945 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11946 SplatBits0 == ~SplatBits1) {
11947 // Canonicalize the vector type to make instruction selection
11948 // simpler.
11949 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11950 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11951 N0->getOperand(1),
11952 N0->getOperand(0),
11953 N1->getOperand(0));
11954 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11960 if (Subtarget->hasMVEIntegerOps() &&
11961 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
11962 return PerformORCombine_i1(N, DCI, Subtarget);
11964 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11965 // reasonable.
11966 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11967 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11968 return Res;
11971 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11972 return Result;
11974 return SDValue();
11977 static SDValue PerformXORCombine(SDNode *N,
11978 TargetLowering::DAGCombinerInfo &DCI,
11979 const ARMSubtarget *Subtarget) {
11980 EVT VT = N->getValueType(0);
11981 SelectionDAG &DAG = DCI.DAG;
11983 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11984 return SDValue();
11986 if (!Subtarget->isThumb1Only()) {
11987 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11988 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11989 return Result;
11991 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11992 return Result;
11995 return SDValue();
11998 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11999 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12000 // their position in "to" (Rd).
12001 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12002 assert(N->getOpcode() == ARMISD::BFI);
12004 SDValue From = N->getOperand(1);
12005 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12006 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12008 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12009 // #C in the base of the SHR.
12010 if (From->getOpcode() == ISD::SRL &&
12011 isa<ConstantSDNode>(From->getOperand(1))) {
12012 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12013 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12014 FromMask <<= Shift.getLimitedValue(31);
12015 From = From->getOperand(0);
12018 return From;
12021 // If A and B contain one contiguous set of bits, does A | B == A . B?
12023 // Neither A nor B must be zero.
12024 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12025 unsigned LastActiveBitInA = A.countTrailingZeros();
12026 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12027 return LastActiveBitInA - 1 == FirstActiveBitInB;
12030 static SDValue FindBFIToCombineWith(SDNode *N) {
12031 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12032 // if one exists.
12033 APInt ToMask, FromMask;
12034 SDValue From = ParseBFI(N, ToMask, FromMask);
12035 SDValue To = N->getOperand(0);
12037 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12038 // aren't compatible, but not if they set the same bit in their destination as
12039 // we do (or that of any BFI we're going to combine with).
12040 SDValue V = To;
12041 APInt CombinedToMask = ToMask;
12042 while (V.getOpcode() == ARMISD::BFI) {
12043 APInt NewToMask, NewFromMask;
12044 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12045 if (NewFrom != From) {
12046 // This BFI has a different base. Keep going.
12047 CombinedToMask |= NewToMask;
12048 V = V.getOperand(0);
12049 continue;
12052 // Do the written bits conflict with any we've seen so far?
12053 if ((NewToMask & CombinedToMask).getBoolValue())
12054 // Conflicting bits - bail out because going further is unsafe.
12055 return SDValue();
12057 // Are the new bits contiguous when combined with the old bits?
12058 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12059 BitsProperlyConcatenate(FromMask, NewFromMask))
12060 return V;
12061 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12062 BitsProperlyConcatenate(NewFromMask, FromMask))
12063 return V;
12065 // We've seen a write to some bits, so track it.
12066 CombinedToMask |= NewToMask;
12067 // Keep going...
12068 V = V.getOperand(0);
12071 return SDValue();
12074 static SDValue PerformBFICombine(SDNode *N,
12075 TargetLowering::DAGCombinerInfo &DCI) {
12076 SDValue N1 = N->getOperand(1);
12077 if (N1.getOpcode() == ISD::AND) {
12078 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12079 // the bits being cleared by the AND are not demanded by the BFI.
12080 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12081 if (!N11C)
12082 return SDValue();
12083 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12084 unsigned LSB = countTrailingZeros(~InvMask);
12085 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12086 assert(Width <
12087 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12088 "undefined behavior");
12089 unsigned Mask = (1u << Width) - 1;
12090 unsigned Mask2 = N11C->getZExtValue();
12091 if ((Mask & (~Mask2)) == 0)
12092 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12093 N->getOperand(0), N1.getOperand(0),
12094 N->getOperand(2));
12095 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12096 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12097 // Keep track of any consecutive bits set that all come from the same base
12098 // value. We can combine these together into a single BFI.
12099 SDValue CombineBFI = FindBFIToCombineWith(N);
12100 if (CombineBFI == SDValue())
12101 return SDValue();
12103 // We've found a BFI.
12104 APInt ToMask1, FromMask1;
12105 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12107 APInt ToMask2, FromMask2;
12108 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12109 assert(From1 == From2);
12110 (void)From2;
12112 // First, unlink CombineBFI.
12113 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12114 // Then create a new BFI, combining the two together.
12115 APInt NewFromMask = FromMask1 | FromMask2;
12116 APInt NewToMask = ToMask1 | ToMask2;
12118 EVT VT = N->getValueType(0);
12119 SDLoc dl(N);
12121 if (NewFromMask[0] == 0)
12122 From1 = DCI.DAG.getNode(
12123 ISD::SRL, dl, VT, From1,
12124 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12125 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12126 DCI.DAG.getConstant(~NewToMask, dl, VT));
12128 return SDValue();
12131 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12132 /// ARMISD::VMOVRRD.
12133 static SDValue PerformVMOVRRDCombine(SDNode *N,
12134 TargetLowering::DAGCombinerInfo &DCI,
12135 const ARMSubtarget *Subtarget) {
12136 // vmovrrd(vmovdrr x, y) -> x,y
12137 SDValue InDouble = N->getOperand(0);
12138 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12139 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12141 // vmovrrd(load f64) -> (load i32), (load i32)
12142 SDNode *InNode = InDouble.getNode();
12143 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12144 InNode->getValueType(0) == MVT::f64 &&
12145 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12146 !cast<LoadSDNode>(InNode)->isVolatile()) {
12147 // TODO: Should this be done for non-FrameIndex operands?
12148 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12150 SelectionDAG &DAG = DCI.DAG;
12151 SDLoc DL(LD);
12152 SDValue BasePtr = LD->getBasePtr();
12153 SDValue NewLD1 =
12154 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12155 LD->getAlignment(), LD->getMemOperand()->getFlags());
12157 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12158 DAG.getConstant(4, DL, MVT::i32));
12160 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12161 LD->getPointerInfo().getWithOffset(4),
12162 std::min(4U, LD->getAlignment()),
12163 LD->getMemOperand()->getFlags());
12165 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12166 if (DCI.DAG.getDataLayout().isBigEndian())
12167 std::swap (NewLD1, NewLD2);
12168 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12169 return Result;
12172 return SDValue();
12175 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12176 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12177 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12178 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12179 SDValue Op0 = N->getOperand(0);
12180 SDValue Op1 = N->getOperand(1);
12181 if (Op0.getOpcode() == ISD::BITCAST)
12182 Op0 = Op0.getOperand(0);
12183 if (Op1.getOpcode() == ISD::BITCAST)
12184 Op1 = Op1.getOperand(0);
12185 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12186 Op0.getNode() == Op1.getNode() &&
12187 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12188 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12189 N->getValueType(0), Op0.getOperand(0));
12190 return SDValue();
12193 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12194 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12195 /// i64 vector to have f64 elements, since the value can then be loaded
12196 /// directly into a VFP register.
12197 static bool hasNormalLoadOperand(SDNode *N) {
12198 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12199 for (unsigned i = 0; i < NumElts; ++i) {
12200 SDNode *Elt = N->getOperand(i).getNode();
12201 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12202 return true;
12204 return false;
12207 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12208 /// ISD::BUILD_VECTOR.
12209 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12210 TargetLowering::DAGCombinerInfo &DCI,
12211 const ARMSubtarget *Subtarget) {
12212 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12213 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12214 // into a pair of GPRs, which is fine when the value is used as a scalar,
12215 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12216 SelectionDAG &DAG = DCI.DAG;
12217 if (N->getNumOperands() == 2)
12218 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12219 return RV;
12221 // Load i64 elements as f64 values so that type legalization does not split
12222 // them up into i32 values.
12223 EVT VT = N->getValueType(0);
12224 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12225 return SDValue();
12226 SDLoc dl(N);
12227 SmallVector<SDValue, 8> Ops;
12228 unsigned NumElts = VT.getVectorNumElements();
12229 for (unsigned i = 0; i < NumElts; ++i) {
12230 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12231 Ops.push_back(V);
12232 // Make the DAGCombiner fold the bitcast.
12233 DCI.AddToWorklist(V.getNode());
12235 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12236 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12237 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12240 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12241 static SDValue
12242 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12243 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12244 // At that time, we may have inserted bitcasts from integer to float.
12245 // If these bitcasts have survived DAGCombine, change the lowering of this
12246 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12247 // force to use floating point types.
12249 // Make sure we can change the type of the vector.
12250 // This is possible iff:
12251 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12252 // 1.1. Vector is used only once.
12253 // 1.2. Use is a bit convert to an integer type.
12254 // 2. The size of its operands are 32-bits (64-bits are not legal).
12255 EVT VT = N->getValueType(0);
12256 EVT EltVT = VT.getVectorElementType();
12258 // Check 1.1. and 2.
12259 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12260 return SDValue();
12262 // By construction, the input type must be float.
12263 assert(EltVT == MVT::f32 && "Unexpected type!");
12265 // Check 1.2.
12266 SDNode *Use = *N->use_begin();
12267 if (Use->getOpcode() != ISD::BITCAST ||
12268 Use->getValueType(0).isFloatingPoint())
12269 return SDValue();
12271 // Check profitability.
12272 // Model is, if more than half of the relevant operands are bitcast from
12273 // i32, turn the build_vector into a sequence of insert_vector_elt.
12274 // Relevant operands are everything that is not statically
12275 // (i.e., at compile time) bitcasted.
12276 unsigned NumOfBitCastedElts = 0;
12277 unsigned NumElts = VT.getVectorNumElements();
12278 unsigned NumOfRelevantElts = NumElts;
12279 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12280 SDValue Elt = N->getOperand(Idx);
12281 if (Elt->getOpcode() == ISD::BITCAST) {
12282 // Assume only bit cast to i32 will go away.
12283 if (Elt->getOperand(0).getValueType() == MVT::i32)
12284 ++NumOfBitCastedElts;
12285 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12286 // Constants are statically casted, thus do not count them as
12287 // relevant operands.
12288 --NumOfRelevantElts;
12291 // Check if more than half of the elements require a non-free bitcast.
12292 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12293 return SDValue();
12295 SelectionDAG &DAG = DCI.DAG;
12296 // Create the new vector type.
12297 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12298 // Check if the type is legal.
12299 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12300 if (!TLI.isTypeLegal(VecVT))
12301 return SDValue();
12303 // Combine:
12304 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12305 // => BITCAST INSERT_VECTOR_ELT
12306 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12307 // (BITCAST EN), N.
12308 SDValue Vec = DAG.getUNDEF(VecVT);
12309 SDLoc dl(N);
12310 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12311 SDValue V = N->getOperand(Idx);
12312 if (V.isUndef())
12313 continue;
12314 if (V.getOpcode() == ISD::BITCAST &&
12315 V->getOperand(0).getValueType() == MVT::i32)
12316 // Fold obvious case.
12317 V = V.getOperand(0);
12318 else {
12319 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12320 // Make the DAGCombiner fold the bitcasts.
12321 DCI.AddToWorklist(V.getNode());
12323 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12324 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12326 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12327 // Make the DAGCombiner fold the bitcasts.
12328 DCI.AddToWorklist(Vec.getNode());
12329 return Vec;
12332 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12333 /// ISD::INSERT_VECTOR_ELT.
12334 static SDValue PerformInsertEltCombine(SDNode *N,
12335 TargetLowering::DAGCombinerInfo &DCI) {
12336 // Bitcast an i64 load inserted into a vector to f64.
12337 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12338 EVT VT = N->getValueType(0);
12339 SDNode *Elt = N->getOperand(1).getNode();
12340 if (VT.getVectorElementType() != MVT::i64 ||
12341 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12342 return SDValue();
12344 SelectionDAG &DAG = DCI.DAG;
12345 SDLoc dl(N);
12346 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12347 VT.getVectorNumElements());
12348 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12349 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12350 // Make the DAGCombiner fold the bitcasts.
12351 DCI.AddToWorklist(Vec.getNode());
12352 DCI.AddToWorklist(V.getNode());
12353 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12354 Vec, V, N->getOperand(2));
12355 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12358 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12359 /// ISD::VECTOR_SHUFFLE.
12360 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12361 // The LLVM shufflevector instruction does not require the shuffle mask
12362 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12363 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12364 // operands do not match the mask length, they are extended by concatenating
12365 // them with undef vectors. That is probably the right thing for other
12366 // targets, but for NEON it is better to concatenate two double-register
12367 // size vector operands into a single quad-register size vector. Do that
12368 // transformation here:
12369 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12370 // shuffle(concat(v1, v2), undef)
12371 SDValue Op0 = N->getOperand(0);
12372 SDValue Op1 = N->getOperand(1);
12373 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12374 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12375 Op0.getNumOperands() != 2 ||
12376 Op1.getNumOperands() != 2)
12377 return SDValue();
12378 SDValue Concat0Op1 = Op0.getOperand(1);
12379 SDValue Concat1Op1 = Op1.getOperand(1);
12380 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12381 return SDValue();
12382 // Skip the transformation if any of the types are illegal.
12383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12384 EVT VT = N->getValueType(0);
12385 if (!TLI.isTypeLegal(VT) ||
12386 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12387 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12388 return SDValue();
12390 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12391 Op0.getOperand(0), Op1.getOperand(0));
12392 // Translate the shuffle mask.
12393 SmallVector<int, 16> NewMask;
12394 unsigned NumElts = VT.getVectorNumElements();
12395 unsigned HalfElts = NumElts/2;
12396 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12397 for (unsigned n = 0; n < NumElts; ++n) {
12398 int MaskElt = SVN->getMaskElt(n);
12399 int NewElt = -1;
12400 if (MaskElt < (int)HalfElts)
12401 NewElt = MaskElt;
12402 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12403 NewElt = HalfElts + MaskElt - NumElts;
12404 NewMask.push_back(NewElt);
12406 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12407 DAG.getUNDEF(VT), NewMask);
12410 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12411 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12412 /// base address updates.
12413 /// For generic load/stores, the memory type is assumed to be a vector.
12414 /// The caller is assumed to have checked legality.
12415 static SDValue CombineBaseUpdate(SDNode *N,
12416 TargetLowering::DAGCombinerInfo &DCI) {
12417 SelectionDAG &DAG = DCI.DAG;
12418 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12419 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12420 const bool isStore = N->getOpcode() == ISD::STORE;
12421 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12422 SDValue Addr = N->getOperand(AddrOpIdx);
12423 MemSDNode *MemN = cast<MemSDNode>(N);
12424 SDLoc dl(N);
12426 // Search for a use of the address operand that is an increment.
12427 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12428 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12429 SDNode *User = *UI;
12430 if (User->getOpcode() != ISD::ADD ||
12431 UI.getUse().getResNo() != Addr.getResNo())
12432 continue;
12434 // Check that the add is independent of the load/store. Otherwise, folding
12435 // it would create a cycle. We can avoid searching through Addr as it's a
12436 // predecessor to both.
12437 SmallPtrSet<const SDNode *, 32> Visited;
12438 SmallVector<const SDNode *, 16> Worklist;
12439 Visited.insert(Addr.getNode());
12440 Worklist.push_back(N);
12441 Worklist.push_back(User);
12442 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12443 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12444 continue;
12446 // Find the new opcode for the updating load/store.
12447 bool isLoadOp = true;
12448 bool isLaneOp = false;
12449 unsigned NewOpc = 0;
12450 unsigned NumVecs = 0;
12451 if (isIntrinsic) {
12452 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12453 switch (IntNo) {
12454 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12455 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12456 NumVecs = 1; break;
12457 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12458 NumVecs = 2; break;
12459 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12460 NumVecs = 3; break;
12461 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12462 NumVecs = 4; break;
12463 case Intrinsic::arm_neon_vld2dup:
12464 case Intrinsic::arm_neon_vld3dup:
12465 case Intrinsic::arm_neon_vld4dup:
12466 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12467 // combining base updates for such intrinsics.
12468 continue;
12469 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12470 NumVecs = 2; isLaneOp = true; break;
12471 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12472 NumVecs = 3; isLaneOp = true; break;
12473 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12474 NumVecs = 4; isLaneOp = true; break;
12475 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12476 NumVecs = 1; isLoadOp = false; break;
12477 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12478 NumVecs = 2; isLoadOp = false; break;
12479 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12480 NumVecs = 3; isLoadOp = false; break;
12481 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12482 NumVecs = 4; isLoadOp = false; break;
12483 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12484 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12485 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12486 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12487 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12488 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12490 } else {
12491 isLaneOp = true;
12492 switch (N->getOpcode()) {
12493 default: llvm_unreachable("unexpected opcode for Neon base update");
12494 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12495 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12496 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12497 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12498 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12499 NumVecs = 1; isLaneOp = false; break;
12500 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12501 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12505 // Find the size of memory referenced by the load/store.
12506 EVT VecTy;
12507 if (isLoadOp) {
12508 VecTy = N->getValueType(0);
12509 } else if (isIntrinsic) {
12510 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12511 } else {
12512 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12513 VecTy = N->getOperand(1).getValueType();
12516 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12517 if (isLaneOp)
12518 NumBytes /= VecTy.getVectorNumElements();
12520 // If the increment is a constant, it must match the memory ref size.
12521 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12522 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12523 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12524 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12525 // separate instructions that make it harder to use a non-constant update.
12526 continue;
12529 // OK, we found an ADD we can fold into the base update.
12530 // Now, create a _UPD node, taking care of not breaking alignment.
12532 EVT AlignedVecTy = VecTy;
12533 unsigned Alignment = MemN->getAlignment();
12535 // If this is a less-than-standard-aligned load/store, change the type to
12536 // match the standard alignment.
12537 // The alignment is overlooked when selecting _UPD variants; and it's
12538 // easier to introduce bitcasts here than fix that.
12539 // There are 3 ways to get to this base-update combine:
12540 // - intrinsics: they are assumed to be properly aligned (to the standard
12541 // alignment of the memory type), so we don't need to do anything.
12542 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12543 // intrinsics, so, likewise, there's nothing to do.
12544 // - generic load/store instructions: the alignment is specified as an
12545 // explicit operand, rather than implicitly as the standard alignment
12546 // of the memory type (like the intrisics). We need to change the
12547 // memory type to match the explicit alignment. That way, we don't
12548 // generate non-standard-aligned ARMISD::VLDx nodes.
12549 if (isa<LSBaseSDNode>(N)) {
12550 if (Alignment == 0)
12551 Alignment = 1;
12552 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12553 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12554 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12555 assert(!isLaneOp && "Unexpected generic load/store lane.");
12556 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12557 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12559 // Don't set an explicit alignment on regular load/stores that we want
12560 // to transform to VLD/VST 1_UPD nodes.
12561 // This matches the behavior of regular load/stores, which only get an
12562 // explicit alignment if the MMO alignment is larger than the standard
12563 // alignment of the memory type.
12564 // Intrinsics, however, always get an explicit alignment, set to the
12565 // alignment of the MMO.
12566 Alignment = 1;
12569 // Create the new updating load/store node.
12570 // First, create an SDVTList for the new updating node's results.
12571 EVT Tys[6];
12572 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12573 unsigned n;
12574 for (n = 0; n < NumResultVecs; ++n)
12575 Tys[n] = AlignedVecTy;
12576 Tys[n++] = MVT::i32;
12577 Tys[n] = MVT::Other;
12578 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12580 // Then, gather the new node's operands.
12581 SmallVector<SDValue, 8> Ops;
12582 Ops.push_back(N->getOperand(0)); // incoming chain
12583 Ops.push_back(N->getOperand(AddrOpIdx));
12584 Ops.push_back(Inc);
12586 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12587 // Try to match the intrinsic's signature
12588 Ops.push_back(StN->getValue());
12589 } else {
12590 // Loads (and of course intrinsics) match the intrinsics' signature,
12591 // so just add all but the alignment operand.
12592 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12593 Ops.push_back(N->getOperand(i));
12596 // For all node types, the alignment operand is always the last one.
12597 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12599 // If this is a non-standard-aligned STORE, the penultimate operand is the
12600 // stored value. Bitcast it to the aligned type.
12601 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12602 SDValue &StVal = Ops[Ops.size()-2];
12603 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12606 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12607 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12608 MemN->getMemOperand());
12610 // Update the uses.
12611 SmallVector<SDValue, 5> NewResults;
12612 for (unsigned i = 0; i < NumResultVecs; ++i)
12613 NewResults.push_back(SDValue(UpdN.getNode(), i));
12615 // If this is an non-standard-aligned LOAD, the first result is the loaded
12616 // value. Bitcast it to the expected result type.
12617 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12618 SDValue &LdVal = NewResults[0];
12619 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12622 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12623 DCI.CombineTo(N, NewResults);
12624 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12626 break;
12628 return SDValue();
12631 static SDValue PerformVLDCombine(SDNode *N,
12632 TargetLowering::DAGCombinerInfo &DCI) {
12633 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12634 return SDValue();
12636 return CombineBaseUpdate(N, DCI);
12639 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12640 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12641 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12642 /// return true.
12643 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12644 SelectionDAG &DAG = DCI.DAG;
12645 EVT VT = N->getValueType(0);
12646 // vldN-dup instructions only support 64-bit vectors for N > 1.
12647 if (!VT.is64BitVector())
12648 return false;
12650 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12651 SDNode *VLD = N->getOperand(0).getNode();
12652 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12653 return false;
12654 unsigned NumVecs = 0;
12655 unsigned NewOpc = 0;
12656 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12657 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12658 NumVecs = 2;
12659 NewOpc = ARMISD::VLD2DUP;
12660 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12661 NumVecs = 3;
12662 NewOpc = ARMISD::VLD3DUP;
12663 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12664 NumVecs = 4;
12665 NewOpc = ARMISD::VLD4DUP;
12666 } else {
12667 return false;
12670 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12671 // numbers match the load.
12672 unsigned VLDLaneNo =
12673 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12674 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12675 UI != UE; ++UI) {
12676 // Ignore uses of the chain result.
12677 if (UI.getUse().getResNo() == NumVecs)
12678 continue;
12679 SDNode *User = *UI;
12680 if (User->getOpcode() != ARMISD::VDUPLANE ||
12681 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12682 return false;
12685 // Create the vldN-dup node.
12686 EVT Tys[5];
12687 unsigned n;
12688 for (n = 0; n < NumVecs; ++n)
12689 Tys[n] = VT;
12690 Tys[n] = MVT::Other;
12691 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12692 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12693 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12694 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12695 Ops, VLDMemInt->getMemoryVT(),
12696 VLDMemInt->getMemOperand());
12698 // Update the uses.
12699 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12700 UI != UE; ++UI) {
12701 unsigned ResNo = UI.getUse().getResNo();
12702 // Ignore uses of the chain result.
12703 if (ResNo == NumVecs)
12704 continue;
12705 SDNode *User = *UI;
12706 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12709 // Now the vldN-lane intrinsic is dead except for its chain result.
12710 // Update uses of the chain.
12711 std::vector<SDValue> VLDDupResults;
12712 for (unsigned n = 0; n < NumVecs; ++n)
12713 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12714 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12715 DCI.CombineTo(VLD, VLDDupResults);
12717 return true;
12720 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12721 /// ARMISD::VDUPLANE.
12722 static SDValue PerformVDUPLANECombine(SDNode *N,
12723 TargetLowering::DAGCombinerInfo &DCI) {
12724 SDValue Op = N->getOperand(0);
12726 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12727 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12728 if (CombineVLDDUP(N, DCI))
12729 return SDValue(N, 0);
12731 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12732 // redundant. Ignore bit_converts for now; element sizes are checked below.
12733 while (Op.getOpcode() == ISD::BITCAST)
12734 Op = Op.getOperand(0);
12735 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12736 return SDValue();
12738 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12739 unsigned EltSize = Op.getScalarValueSizeInBits();
12740 // The canonical VMOV for a zero vector uses a 32-bit element size.
12741 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12742 unsigned EltBits;
12743 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12744 EltSize = 8;
12745 EVT VT = N->getValueType(0);
12746 if (EltSize > VT.getScalarSizeInBits())
12747 return SDValue();
12749 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12752 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12753 static SDValue PerformVDUPCombine(SDNode *N,
12754 TargetLowering::DAGCombinerInfo &DCI,
12755 const ARMSubtarget *Subtarget) {
12756 SelectionDAG &DAG = DCI.DAG;
12757 SDValue Op = N->getOperand(0);
12759 if (!Subtarget->hasNEON())
12760 return SDValue();
12762 // Match VDUP(LOAD) -> VLD1DUP.
12763 // We match this pattern here rather than waiting for isel because the
12764 // transform is only legal for unindexed loads.
12765 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12766 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12767 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12768 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12769 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12770 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12771 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12772 Ops, LD->getMemoryVT(),
12773 LD->getMemOperand());
12774 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12775 return VLDDup;
12778 return SDValue();
12781 static SDValue PerformLOADCombine(SDNode *N,
12782 TargetLowering::DAGCombinerInfo &DCI) {
12783 EVT VT = N->getValueType(0);
12785 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12786 if (ISD::isNormalLoad(N) && VT.isVector() &&
12787 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12788 return CombineBaseUpdate(N, DCI);
12790 return SDValue();
12793 /// PerformSTORECombine - Target-specific dag combine xforms for
12794 /// ISD::STORE.
12795 static SDValue PerformSTORECombine(SDNode *N,
12796 TargetLowering::DAGCombinerInfo &DCI) {
12797 StoreSDNode *St = cast<StoreSDNode>(N);
12798 if (St->isVolatile())
12799 return SDValue();
12801 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12802 // pack all of the elements in one place. Next, store to memory in fewer
12803 // chunks.
12804 SDValue StVal = St->getValue();
12805 EVT VT = StVal.getValueType();
12806 if (St->isTruncatingStore() && VT.isVector()) {
12807 SelectionDAG &DAG = DCI.DAG;
12808 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12809 EVT StVT = St->getMemoryVT();
12810 unsigned NumElems = VT.getVectorNumElements();
12811 assert(StVT != VT && "Cannot truncate to the same type");
12812 unsigned FromEltSz = VT.getScalarSizeInBits();
12813 unsigned ToEltSz = StVT.getScalarSizeInBits();
12815 // From, To sizes and ElemCount must be pow of two
12816 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12818 // We are going to use the original vector elt for storing.
12819 // Accumulated smaller vector elements must be a multiple of the store size.
12820 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12822 unsigned SizeRatio = FromEltSz / ToEltSz;
12823 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12825 // Create a type on which we perform the shuffle.
12826 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12827 NumElems*SizeRatio);
12828 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12830 SDLoc DL(St);
12831 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12832 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12833 for (unsigned i = 0; i < NumElems; ++i)
12834 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12835 ? (i + 1) * SizeRatio - 1
12836 : i * SizeRatio;
12838 // Can't shuffle using an illegal type.
12839 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12841 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12842 DAG.getUNDEF(WideVec.getValueType()),
12843 ShuffleVec);
12844 // At this point all of the data is stored at the bottom of the
12845 // register. We now need to save it to mem.
12847 // Find the largest store unit
12848 MVT StoreType = MVT::i8;
12849 for (MVT Tp : MVT::integer_valuetypes()) {
12850 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12851 StoreType = Tp;
12853 // Didn't find a legal store type.
12854 if (!TLI.isTypeLegal(StoreType))
12855 return SDValue();
12857 // Bitcast the original vector into a vector of store-size units
12858 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
12859 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
12860 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
12861 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
12862 SmallVector<SDValue, 8> Chains;
12863 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
12864 TLI.getPointerTy(DAG.getDataLayout()));
12865 SDValue BasePtr = St->getBasePtr();
12867 // Perform one or more big stores into memory.
12868 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
12869 for (unsigned I = 0; I < E; I++) {
12870 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
12871 StoreType, ShuffWide,
12872 DAG.getIntPtrConstant(I, DL));
12873 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12874 St->getPointerInfo(), St->getAlignment(),
12875 St->getMemOperand()->getFlags());
12876 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12877 Increment);
12878 Chains.push_back(Ch);
12880 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12883 if (!ISD::isNormalStore(St))
12884 return SDValue();
12886 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12887 // ARM stores of arguments in the same cache line.
12888 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12889 StVal.getNode()->hasOneUse()) {
12890 SelectionDAG &DAG = DCI.DAG;
12891 bool isBigEndian = DAG.getDataLayout().isBigEndian();
12892 SDLoc DL(St);
12893 SDValue BasePtr = St->getBasePtr();
12894 SDValue NewST1 = DAG.getStore(
12895 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12896 BasePtr, St->getPointerInfo(), St->getAlignment(),
12897 St->getMemOperand()->getFlags());
12899 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12900 DAG.getConstant(4, DL, MVT::i32));
12901 return DAG.getStore(NewST1.getValue(0), DL,
12902 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12903 OffsetPtr, St->getPointerInfo(),
12904 std::min(4U, St->getAlignment() / 2),
12905 St->getMemOperand()->getFlags());
12908 if (StVal.getValueType() == MVT::i64 &&
12909 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12911 // Bitcast an i64 store extracted from a vector to f64.
12912 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12913 SelectionDAG &DAG = DCI.DAG;
12914 SDLoc dl(StVal);
12915 SDValue IntVec = StVal.getOperand(0);
12916 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12917 IntVec.getValueType().getVectorNumElements());
12918 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12919 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12920 Vec, StVal.getOperand(1));
12921 dl = SDLoc(N);
12922 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12923 // Make the DAGCombiner fold the bitcasts.
12924 DCI.AddToWorklist(Vec.getNode());
12925 DCI.AddToWorklist(ExtElt.getNode());
12926 DCI.AddToWorklist(V.getNode());
12927 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12928 St->getPointerInfo(), St->getAlignment(),
12929 St->getMemOperand()->getFlags(), St->getAAInfo());
12932 // If this is a legal vector store, try to combine it into a VST1_UPD.
12933 if (ISD::isNormalStore(N) && VT.isVector() &&
12934 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12935 return CombineBaseUpdate(N, DCI);
12937 return SDValue();
12940 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12941 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12942 /// when the VMUL has a constant operand that is a power of 2.
12944 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12945 /// vmul.f32 d16, d17, d16
12946 /// vcvt.s32.f32 d16, d16
12947 /// becomes:
12948 /// vcvt.s32.f32 d16, d16, #3
12949 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12950 const ARMSubtarget *Subtarget) {
12951 if (!Subtarget->hasNEON())
12952 return SDValue();
12954 SDValue Op = N->getOperand(0);
12955 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12956 Op.getOpcode() != ISD::FMUL)
12957 return SDValue();
12959 SDValue ConstVec = Op->getOperand(1);
12960 if (!isa<BuildVectorSDNode>(ConstVec))
12961 return SDValue();
12963 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12964 uint32_t FloatBits = FloatTy.getSizeInBits();
12965 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12966 uint32_t IntBits = IntTy.getSizeInBits();
12967 unsigned NumLanes = Op.getValueType().getVectorNumElements();
12968 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12969 // These instructions only exist converting from f32 to i32. We can handle
12970 // smaller integers by generating an extra truncate, but larger ones would
12971 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12972 // these intructions only support v2i32/v4i32 types.
12973 return SDValue();
12976 BitVector UndefElements;
12977 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12978 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12979 if (C == -1 || C == 0 || C > 32)
12980 return SDValue();
12982 SDLoc dl(N);
12983 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12984 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12985 Intrinsic::arm_neon_vcvtfp2fxu;
12986 SDValue FixConv = DAG.getNode(
12987 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12988 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12989 DAG.getConstant(C, dl, MVT::i32));
12991 if (IntBits < FloatBits)
12992 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12994 return FixConv;
12997 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12998 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12999 /// when the VDIV has a constant operand that is a power of 2.
13001 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13002 /// vcvt.f32.s32 d16, d16
13003 /// vdiv.f32 d16, d17, d16
13004 /// becomes:
13005 /// vcvt.f32.s32 d16, d16, #3
13006 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13007 const ARMSubtarget *Subtarget) {
13008 if (!Subtarget->hasNEON())
13009 return SDValue();
13011 SDValue Op = N->getOperand(0);
13012 unsigned OpOpcode = Op.getNode()->getOpcode();
13013 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13014 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13015 return SDValue();
13017 SDValue ConstVec = N->getOperand(1);
13018 if (!isa<BuildVectorSDNode>(ConstVec))
13019 return SDValue();
13021 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13022 uint32_t FloatBits = FloatTy.getSizeInBits();
13023 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13024 uint32_t IntBits = IntTy.getSizeInBits();
13025 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13026 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13027 // These instructions only exist converting from i32 to f32. We can handle
13028 // smaller integers by generating an extra extend, but larger ones would
13029 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13030 // these intructions only support v2i32/v4i32 types.
13031 return SDValue();
13034 BitVector UndefElements;
13035 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13036 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13037 if (C == -1 || C == 0 || C > 32)
13038 return SDValue();
13040 SDLoc dl(N);
13041 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13042 SDValue ConvInput = Op.getOperand(0);
13043 if (IntBits < FloatBits)
13044 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13045 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13046 ConvInput);
13048 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13049 Intrinsic::arm_neon_vcvtfxu2fp;
13050 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13051 Op.getValueType(),
13052 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13053 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13056 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13057 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13058 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13059 switch (IntNo) {
13060 default:
13061 // Don't do anything for most intrinsics.
13062 break;
13064 // Vector shifts: check for immediate versions and lower them.
13065 // Note: This is done during DAG combining instead of DAG legalizing because
13066 // the build_vectors for 64-bit vector element shift counts are generally
13067 // not legal, and it is hard to see their values after they get legalized to
13068 // loads from a constant pool.
13069 case Intrinsic::arm_neon_vshifts:
13070 case Intrinsic::arm_neon_vshiftu:
13071 case Intrinsic::arm_neon_vrshifts:
13072 case Intrinsic::arm_neon_vrshiftu:
13073 case Intrinsic::arm_neon_vrshiftn:
13074 case Intrinsic::arm_neon_vqshifts:
13075 case Intrinsic::arm_neon_vqshiftu:
13076 case Intrinsic::arm_neon_vqshiftsu:
13077 case Intrinsic::arm_neon_vqshiftns:
13078 case Intrinsic::arm_neon_vqshiftnu:
13079 case Intrinsic::arm_neon_vqshiftnsu:
13080 case Intrinsic::arm_neon_vqrshiftns:
13081 case Intrinsic::arm_neon_vqrshiftnu:
13082 case Intrinsic::arm_neon_vqrshiftnsu: {
13083 EVT VT = N->getOperand(1).getValueType();
13084 int64_t Cnt;
13085 unsigned VShiftOpc = 0;
13087 switch (IntNo) {
13088 case Intrinsic::arm_neon_vshifts:
13089 case Intrinsic::arm_neon_vshiftu:
13090 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13091 VShiftOpc = ARMISD::VSHLIMM;
13092 break;
13094 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13095 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13096 : ARMISD::VSHRuIMM);
13097 break;
13099 return SDValue();
13101 case Intrinsic::arm_neon_vrshifts:
13102 case Intrinsic::arm_neon_vrshiftu:
13103 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13104 break;
13105 return SDValue();
13107 case Intrinsic::arm_neon_vqshifts:
13108 case Intrinsic::arm_neon_vqshiftu:
13109 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13110 break;
13111 return SDValue();
13113 case Intrinsic::arm_neon_vqshiftsu:
13114 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13115 break;
13116 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13118 case Intrinsic::arm_neon_vrshiftn:
13119 case Intrinsic::arm_neon_vqshiftns:
13120 case Intrinsic::arm_neon_vqshiftnu:
13121 case Intrinsic::arm_neon_vqshiftnsu:
13122 case Intrinsic::arm_neon_vqrshiftns:
13123 case Intrinsic::arm_neon_vqrshiftnu:
13124 case Intrinsic::arm_neon_vqrshiftnsu:
13125 // Narrowing shifts require an immediate right shift.
13126 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13127 break;
13128 llvm_unreachable("invalid shift count for narrowing vector shift "
13129 "intrinsic");
13131 default:
13132 llvm_unreachable("unhandled vector shift");
13135 switch (IntNo) {
13136 case Intrinsic::arm_neon_vshifts:
13137 case Intrinsic::arm_neon_vshiftu:
13138 // Opcode already set above.
13139 break;
13140 case Intrinsic::arm_neon_vrshifts:
13141 VShiftOpc = ARMISD::VRSHRsIMM;
13142 break;
13143 case Intrinsic::arm_neon_vrshiftu:
13144 VShiftOpc = ARMISD::VRSHRuIMM;
13145 break;
13146 case Intrinsic::arm_neon_vrshiftn:
13147 VShiftOpc = ARMISD::VRSHRNIMM;
13148 break;
13149 case Intrinsic::arm_neon_vqshifts:
13150 VShiftOpc = ARMISD::VQSHLsIMM;
13151 break;
13152 case Intrinsic::arm_neon_vqshiftu:
13153 VShiftOpc = ARMISD::VQSHLuIMM;
13154 break;
13155 case Intrinsic::arm_neon_vqshiftsu:
13156 VShiftOpc = ARMISD::VQSHLsuIMM;
13157 break;
13158 case Intrinsic::arm_neon_vqshiftns:
13159 VShiftOpc = ARMISD::VQSHRNsIMM;
13160 break;
13161 case Intrinsic::arm_neon_vqshiftnu:
13162 VShiftOpc = ARMISD::VQSHRNuIMM;
13163 break;
13164 case Intrinsic::arm_neon_vqshiftnsu:
13165 VShiftOpc = ARMISD::VQSHRNsuIMM;
13166 break;
13167 case Intrinsic::arm_neon_vqrshiftns:
13168 VShiftOpc = ARMISD::VQRSHRNsIMM;
13169 break;
13170 case Intrinsic::arm_neon_vqrshiftnu:
13171 VShiftOpc = ARMISD::VQRSHRNuIMM;
13172 break;
13173 case Intrinsic::arm_neon_vqrshiftnsu:
13174 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13175 break;
13178 SDLoc dl(N);
13179 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13180 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13183 case Intrinsic::arm_neon_vshiftins: {
13184 EVT VT = N->getOperand(1).getValueType();
13185 int64_t Cnt;
13186 unsigned VShiftOpc = 0;
13188 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13189 VShiftOpc = ARMISD::VSLIIMM;
13190 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13191 VShiftOpc = ARMISD::VSRIIMM;
13192 else {
13193 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13196 SDLoc dl(N);
13197 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13198 N->getOperand(1), N->getOperand(2),
13199 DAG.getConstant(Cnt, dl, MVT::i32));
13202 case Intrinsic::arm_neon_vqrshifts:
13203 case Intrinsic::arm_neon_vqrshiftu:
13204 // No immediate versions of these to check for.
13205 break;
13208 return SDValue();
13211 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13212 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13213 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13214 /// vector element shift counts are generally not legal, and it is hard to see
13215 /// their values after they get legalized to loads from a constant pool.
13216 static SDValue PerformShiftCombine(SDNode *N,
13217 TargetLowering::DAGCombinerInfo &DCI,
13218 const ARMSubtarget *ST) {
13219 SelectionDAG &DAG = DCI.DAG;
13220 EVT VT = N->getValueType(0);
13221 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13222 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13223 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13224 SDValue N1 = N->getOperand(1);
13225 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13226 SDValue N0 = N->getOperand(0);
13227 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13228 DAG.MaskedValueIsZero(N0.getOperand(0),
13229 APInt::getHighBitsSet(32, 16)))
13230 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13234 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13235 N->getOperand(0)->getOpcode() == ISD::AND &&
13236 N->getOperand(0)->hasOneUse()) {
13237 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13238 return SDValue();
13239 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13240 // usually show up because instcombine prefers to canonicalize it to
13241 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13242 // out of GEP lowering in some cases.
13243 SDValue N0 = N->getOperand(0);
13244 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13245 if (!ShiftAmtNode)
13246 return SDValue();
13247 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13248 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13249 if (!AndMaskNode)
13250 return SDValue();
13251 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13252 // Don't transform uxtb/uxth.
13253 if (AndMask == 255 || AndMask == 65535)
13254 return SDValue();
13255 if (isMask_32(AndMask)) {
13256 uint32_t MaskedBits = countLeadingZeros(AndMask);
13257 if (MaskedBits > ShiftAmt) {
13258 SDLoc DL(N);
13259 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13260 DAG.getConstant(MaskedBits, DL, MVT::i32));
13261 return DAG.getNode(
13262 ISD::SRL, DL, MVT::i32, SHL,
13263 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13268 // Nothing to be done for scalar shifts.
13269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13270 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13271 return SDValue();
13272 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13273 return SDValue();
13275 int64_t Cnt;
13277 switch (N->getOpcode()) {
13278 default: llvm_unreachable("unexpected shift opcode");
13280 case ISD::SHL:
13281 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13282 SDLoc dl(N);
13283 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13284 DAG.getConstant(Cnt, dl, MVT::i32));
13286 break;
13288 case ISD::SRA:
13289 case ISD::SRL:
13290 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13291 unsigned VShiftOpc =
13292 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13293 SDLoc dl(N);
13294 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13295 DAG.getConstant(Cnt, dl, MVT::i32));
13298 return SDValue();
13301 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13302 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13303 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13304 const ARMSubtarget *ST) {
13305 SDValue N0 = N->getOperand(0);
13307 // Check for sign- and zero-extensions of vector extract operations of 8-
13308 // and 16-bit vector elements. NEON supports these directly. They are
13309 // handled during DAG combining because type legalization will promote them
13310 // to 32-bit types and it is messy to recognize the operations after that.
13311 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13312 SDValue Vec = N0.getOperand(0);
13313 SDValue Lane = N0.getOperand(1);
13314 EVT VT = N->getValueType(0);
13315 EVT EltVT = N0.getValueType();
13316 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13318 if (VT == MVT::i32 &&
13319 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13320 TLI.isTypeLegal(Vec.getValueType()) &&
13321 isa<ConstantSDNode>(Lane)) {
13323 unsigned Opc = 0;
13324 switch (N->getOpcode()) {
13325 default: llvm_unreachable("unexpected opcode");
13326 case ISD::SIGN_EXTEND:
13327 Opc = ARMISD::VGETLANEs;
13328 break;
13329 case ISD::ZERO_EXTEND:
13330 case ISD::ANY_EXTEND:
13331 Opc = ARMISD::VGETLANEu;
13332 break;
13334 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13338 return SDValue();
13341 static const APInt *isPowerOf2Constant(SDValue V) {
13342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13343 if (!C)
13344 return nullptr;
13345 const APInt *CV = &C->getAPIntValue();
13346 return CV->isPowerOf2() ? CV : nullptr;
13349 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13350 // If we have a CMOV, OR and AND combination such as:
13351 // if (x & CN)
13352 // y |= CM;
13354 // And:
13355 // * CN is a single bit;
13356 // * All bits covered by CM are known zero in y
13358 // Then we can convert this into a sequence of BFI instructions. This will
13359 // always be a win if CM is a single bit, will always be no worse than the
13360 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13361 // three bits (due to the extra IT instruction).
13363 SDValue Op0 = CMOV->getOperand(0);
13364 SDValue Op1 = CMOV->getOperand(1);
13365 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13366 auto CC = CCNode->getAPIntValue().getLimitedValue();
13367 SDValue CmpZ = CMOV->getOperand(4);
13369 // The compare must be against zero.
13370 if (!isNullConstant(CmpZ->getOperand(1)))
13371 return SDValue();
13373 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13374 SDValue And = CmpZ->getOperand(0);
13375 if (And->getOpcode() != ISD::AND)
13376 return SDValue();
13377 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13378 if (!AndC)
13379 return SDValue();
13380 SDValue X = And->getOperand(0);
13382 if (CC == ARMCC::EQ) {
13383 // We're performing an "equal to zero" compare. Swap the operands so we
13384 // canonicalize on a "not equal to zero" compare.
13385 std::swap(Op0, Op1);
13386 } else {
13387 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13390 if (Op1->getOpcode() != ISD::OR)
13391 return SDValue();
13393 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13394 if (!OrC)
13395 return SDValue();
13396 SDValue Y = Op1->getOperand(0);
13398 if (Op0 != Y)
13399 return SDValue();
13401 // Now, is it profitable to continue?
13402 APInt OrCI = OrC->getAPIntValue();
13403 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13404 if (OrCI.countPopulation() > Heuristic)
13405 return SDValue();
13407 // Lastly, can we determine that the bits defined by OrCI
13408 // are zero in Y?
13409 KnownBits Known = DAG.computeKnownBits(Y);
13410 if ((OrCI & Known.Zero) != OrCI)
13411 return SDValue();
13413 // OK, we can do the combine.
13414 SDValue V = Y;
13415 SDLoc dl(X);
13416 EVT VT = X.getValueType();
13417 unsigned BitInX = AndC->logBase2();
13419 if (BitInX != 0) {
13420 // We must shift X first.
13421 X = DAG.getNode(ISD::SRL, dl, VT, X,
13422 DAG.getConstant(BitInX, dl, VT));
13425 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13426 BitInY < NumActiveBits; ++BitInY) {
13427 if (OrCI[BitInY] == 0)
13428 continue;
13429 APInt Mask(VT.getSizeInBits(), 0);
13430 Mask.setBit(BitInY);
13431 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13432 // Confusingly, the operand is an *inverted* mask.
13433 DAG.getConstant(~Mask, dl, VT));
13436 return V;
13439 // Given N, the value controlling the conditional branch, search for the loop
13440 // intrinsic, returning it, along with how the value is used. We need to handle
13441 // patterns such as the following:
13442 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13443 // (brcond (setcc (loop.decrement), 0, eq), exit)
13444 // (brcond (setcc (loop.decrement), 0, ne), header)
13445 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13446 bool &Negate) {
13447 switch (N->getOpcode()) {
13448 default:
13449 break;
13450 case ISD::XOR: {
13451 if (!isa<ConstantSDNode>(N.getOperand(1)))
13452 return SDValue();
13453 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13454 return SDValue();
13455 Negate = !Negate;
13456 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13458 case ISD::SETCC: {
13459 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13460 if (!Const)
13461 return SDValue();
13462 if (Const->isNullValue())
13463 Imm = 0;
13464 else if (Const->isOne())
13465 Imm = 1;
13466 else
13467 return SDValue();
13468 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13469 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13471 case ISD::INTRINSIC_W_CHAIN: {
13472 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13473 if (IntOp != Intrinsic::test_set_loop_iterations &&
13474 IntOp != Intrinsic::loop_decrement_reg)
13475 return SDValue();
13476 return N;
13479 return SDValue();
13482 static SDValue PerformHWLoopCombine(SDNode *N,
13483 TargetLowering::DAGCombinerInfo &DCI,
13484 const ARMSubtarget *ST) {
13486 // The hwloop intrinsics that we're interested are used for control-flow,
13487 // either for entering or exiting the loop:
13488 // - test.set.loop.iterations will test whether its operand is zero. If it
13489 // is zero, the proceeding branch should not enter the loop.
13490 // - loop.decrement.reg also tests whether its operand is zero. If it is
13491 // zero, the proceeding branch should not branch back to the beginning of
13492 // the loop.
13493 // So here, we need to check that how the brcond is using the result of each
13494 // of the intrinsics to ensure that we're branching to the right place at the
13495 // right time.
13497 ISD::CondCode CC;
13498 SDValue Cond;
13499 int Imm = 1;
13500 bool Negate = false;
13501 SDValue Chain = N->getOperand(0);
13502 SDValue Dest;
13504 if (N->getOpcode() == ISD::BRCOND) {
13505 CC = ISD::SETEQ;
13506 Cond = N->getOperand(1);
13507 Dest = N->getOperand(2);
13508 } else {
13509 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13510 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13511 Cond = N->getOperand(2);
13512 Dest = N->getOperand(4);
13513 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13514 if (!Const->isOne() && !Const->isNullValue())
13515 return SDValue();
13516 Imm = Const->getZExtValue();
13517 } else
13518 return SDValue();
13521 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13522 if (!Int)
13523 return SDValue();
13525 if (Negate)
13526 CC = ISD::getSetCCInverse(CC, true);
13528 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13529 return (CC == ISD::SETEQ && Imm == 0) ||
13530 (CC == ISD::SETNE && Imm == 1) ||
13531 (CC == ISD::SETLT && Imm == 1) ||
13532 (CC == ISD::SETULT && Imm == 1);
13535 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13536 return (CC == ISD::SETEQ && Imm == 1) ||
13537 (CC == ISD::SETNE && Imm == 0) ||
13538 (CC == ISD::SETGT && Imm == 0) ||
13539 (CC == ISD::SETUGT && Imm == 0) ||
13540 (CC == ISD::SETGE && Imm == 1) ||
13541 (CC == ISD::SETUGE && Imm == 1);
13544 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13545 "unsupported condition");
13547 SDLoc dl(Int);
13548 SelectionDAG &DAG = DCI.DAG;
13549 SDValue Elements = Int.getOperand(2);
13550 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13551 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13552 && "expected single br user");
13553 SDNode *Br = *N->use_begin();
13554 SDValue OtherTarget = Br->getOperand(1);
13556 // Update the unconditional branch to branch to the given Dest.
13557 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13558 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13559 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13560 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13563 if (IntOp == Intrinsic::test_set_loop_iterations) {
13564 SDValue Res;
13565 // We expect this 'instruction' to branch when the counter is zero.
13566 if (IsTrueIfZero(CC, Imm)) {
13567 SDValue Ops[] = { Chain, Elements, Dest };
13568 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13569 } else {
13570 // The logic is the reverse of what we need for WLS, so find the other
13571 // basic block target: the target of the proceeding br.
13572 UpdateUncondBr(Br, Dest, DAG);
13574 SDValue Ops[] = { Chain, Elements, OtherTarget };
13575 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13577 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13578 return Res;
13579 } else {
13580 SDValue Size = DAG.getTargetConstant(
13581 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13582 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13583 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13584 DAG.getVTList(MVT::i32, MVT::Other), Args);
13585 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13587 // We expect this instruction to branch when the count is not zero.
13588 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13590 // Update the unconditional branch to target the loop preheader if we've
13591 // found the condition has been reversed.
13592 if (Target == OtherTarget)
13593 UpdateUncondBr(Br, Dest, DAG);
13595 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13596 SDValue(LoopDec.getNode(), 1), Chain);
13598 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13599 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13601 return SDValue();
13604 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13605 SDValue
13606 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13607 SDValue Cmp = N->getOperand(4);
13608 if (Cmp.getOpcode() != ARMISD::CMPZ)
13609 // Only looking at NE cases.
13610 return SDValue();
13612 EVT VT = N->getValueType(0);
13613 SDLoc dl(N);
13614 SDValue LHS = Cmp.getOperand(0);
13615 SDValue RHS = Cmp.getOperand(1);
13616 SDValue Chain = N->getOperand(0);
13617 SDValue BB = N->getOperand(1);
13618 SDValue ARMcc = N->getOperand(2);
13619 ARMCC::CondCodes CC =
13620 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13622 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13623 // -> (brcond Chain BB CC CPSR Cmp)
13624 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13625 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13626 LHS->getOperand(0)->hasOneUse()) {
13627 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13628 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13629 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13630 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13631 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13632 (LHS01C && LHS01C->getZExtValue() == 1) &&
13633 (LHS1C && LHS1C->getZExtValue() == 1) &&
13634 (RHSC && RHSC->getZExtValue() == 0)) {
13635 return DAG.getNode(
13636 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13637 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13641 return SDValue();
13644 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13645 SDValue
13646 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13647 SDValue Cmp = N->getOperand(4);
13648 if (Cmp.getOpcode() != ARMISD::CMPZ)
13649 // Only looking at EQ and NE cases.
13650 return SDValue();
13652 EVT VT = N->getValueType(0);
13653 SDLoc dl(N);
13654 SDValue LHS = Cmp.getOperand(0);
13655 SDValue RHS = Cmp.getOperand(1);
13656 SDValue FalseVal = N->getOperand(0);
13657 SDValue TrueVal = N->getOperand(1);
13658 SDValue ARMcc = N->getOperand(2);
13659 ARMCC::CondCodes CC =
13660 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13662 // BFI is only available on V6T2+.
13663 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13664 SDValue R = PerformCMOVToBFICombine(N, DAG);
13665 if (R)
13666 return R;
13669 // Simplify
13670 // mov r1, r0
13671 // cmp r1, x
13672 // mov r0, y
13673 // moveq r0, x
13674 // to
13675 // cmp r0, x
13676 // movne r0, y
13678 // mov r1, r0
13679 // cmp r1, x
13680 // mov r0, x
13681 // movne r0, y
13682 // to
13683 // cmp r0, x
13684 // movne r0, y
13685 /// FIXME: Turn this into a target neutral optimization?
13686 SDValue Res;
13687 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13688 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13689 N->getOperand(3), Cmp);
13690 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13691 SDValue ARMcc;
13692 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13693 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13694 N->getOperand(3), NewCmp);
13697 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13698 // -> (cmov F T CC CPSR Cmp)
13699 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13700 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13701 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13702 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13703 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13704 (LHS1C && LHS1C->getZExtValue() == 1) &&
13705 (RHSC && RHSC->getZExtValue() == 0)) {
13706 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13707 LHS->getOperand(2), LHS->getOperand(3),
13708 LHS->getOperand(4));
13712 if (!VT.isInteger())
13713 return SDValue();
13715 // Materialize a boolean comparison for integers so we can avoid branching.
13716 if (isNullConstant(FalseVal)) {
13717 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13718 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13719 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13720 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13721 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13722 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13723 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13724 DAG.getConstant(5, dl, MVT::i32));
13725 } else {
13726 // CMOV 0, 1, ==, (CMPZ x, y) ->
13727 // (ADDCARRY (SUB x, y), t:0, t:1)
13728 // where t = (SUBCARRY 0, (SUB x, y), 0)
13730 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13731 // x != y. In other words, a carry C == 1 when x == y, C == 0
13732 // otherwise.
13733 // The final ADDCARRY computes
13734 // x - y + (0 - (x - y)) + C == C
13735 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13736 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13737 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13738 // ISD::SUBCARRY returns a borrow but we want the carry here
13739 // actually.
13740 SDValue Carry =
13741 DAG.getNode(ISD::SUB, dl, MVT::i32,
13742 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13743 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13745 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13746 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13747 // This seems pointless but will allow us to combine it further below.
13748 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13749 SDValue Sub =
13750 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13751 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13752 Sub.getValue(1), SDValue());
13753 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13754 N->getOperand(3), CPSRGlue.getValue(1));
13755 FalseVal = Sub;
13757 } else if (isNullConstant(TrueVal)) {
13758 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13759 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13760 // This seems pointless but will allow us to combine it further below
13761 // Note that we change == for != as this is the dual for the case above.
13762 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13763 SDValue Sub =
13764 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13765 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13766 Sub.getValue(1), SDValue());
13767 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13768 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13769 N->getOperand(3), CPSRGlue.getValue(1));
13770 FalseVal = Sub;
13774 // On Thumb1, the DAG above may be further combined if z is a power of 2
13775 // (z == 2 ^ K).
13776 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13777 // t1 = (USUBO (SUB x, y), 1)
13778 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13779 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13781 // This also handles the special case of comparing against zero; it's
13782 // essentially, the same pattern, except there's no SUBS:
13783 // CMOV x, z, !=, (CMPZ x, 0) ->
13784 // t1 = (USUBO x, 1)
13785 // t2 = (SUBCARRY x, t1:0, t1:1)
13786 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13787 const APInt *TrueConst;
13788 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13789 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13790 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13791 (FalseVal == LHS && isNullConstant(RHS))) &&
13792 (TrueConst = isPowerOf2Constant(TrueVal))) {
13793 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13794 unsigned ShiftAmount = TrueConst->logBase2();
13795 if (ShiftAmount)
13796 TrueVal = DAG.getConstant(1, dl, VT);
13797 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13798 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13800 if (ShiftAmount)
13801 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13802 DAG.getConstant(ShiftAmount, dl, MVT::i32));
13805 if (Res.getNode()) {
13806 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
13807 // Capture demanded bits information that would be otherwise lost.
13808 if (Known.Zero == 0xfffffffe)
13809 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13810 DAG.getValueType(MVT::i1));
13811 else if (Known.Zero == 0xffffff00)
13812 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13813 DAG.getValueType(MVT::i8));
13814 else if (Known.Zero == 0xffff0000)
13815 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13816 DAG.getValueType(MVT::i16));
13819 return Res;
13822 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
13823 DAGCombinerInfo &DCI) const {
13824 switch (N->getOpcode()) {
13825 default: break;
13826 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
13827 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
13828 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
13829 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
13830 case ISD::SUB: return PerformSUBCombine(N, DCI);
13831 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
13832 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
13833 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
13834 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
13835 case ISD::BRCOND:
13836 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
13837 case ARMISD::ADDC:
13838 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
13839 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
13840 case ARMISD::BFI: return PerformBFICombine(N, DCI);
13841 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
13842 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
13843 case ISD::STORE: return PerformSTORECombine(N, DCI);
13844 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
13845 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
13846 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
13847 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
13848 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
13849 case ISD::FP_TO_SINT:
13850 case ISD::FP_TO_UINT:
13851 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
13852 case ISD::FDIV:
13853 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
13854 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
13855 case ISD::SHL:
13856 case ISD::SRA:
13857 case ISD::SRL:
13858 return PerformShiftCombine(N, DCI, Subtarget);
13859 case ISD::SIGN_EXTEND:
13860 case ISD::ZERO_EXTEND:
13861 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
13862 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
13863 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
13864 case ISD::LOAD: return PerformLOADCombine(N, DCI);
13865 case ARMISD::VLD1DUP:
13866 case ARMISD::VLD2DUP:
13867 case ARMISD::VLD3DUP:
13868 case ARMISD::VLD4DUP:
13869 return PerformVLDCombine(N, DCI);
13870 case ARMISD::BUILD_VECTOR:
13871 return PerformARMBUILD_VECTORCombine(N, DCI);
13872 case ARMISD::SMULWB: {
13873 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13874 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13875 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13876 return SDValue();
13877 break;
13879 case ARMISD::SMULWT: {
13880 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13881 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13882 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13883 return SDValue();
13884 break;
13886 case ARMISD::SMLALBB: {
13887 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13888 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13889 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13890 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13891 return SDValue();
13892 break;
13894 case ARMISD::SMLALBT: {
13895 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
13896 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13897 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
13898 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13899 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
13900 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
13901 return SDValue();
13902 break;
13904 case ARMISD::SMLALTB: {
13905 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
13906 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13907 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
13908 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13909 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
13910 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
13911 return SDValue();
13912 break;
13914 case ARMISD::SMLALTT: {
13915 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13916 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13917 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13918 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13919 return SDValue();
13920 break;
13922 case ISD::INTRINSIC_VOID:
13923 case ISD::INTRINSIC_W_CHAIN:
13924 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13925 case Intrinsic::arm_neon_vld1:
13926 case Intrinsic::arm_neon_vld1x2:
13927 case Intrinsic::arm_neon_vld1x3:
13928 case Intrinsic::arm_neon_vld1x4:
13929 case Intrinsic::arm_neon_vld2:
13930 case Intrinsic::arm_neon_vld3:
13931 case Intrinsic::arm_neon_vld4:
13932 case Intrinsic::arm_neon_vld2lane:
13933 case Intrinsic::arm_neon_vld3lane:
13934 case Intrinsic::arm_neon_vld4lane:
13935 case Intrinsic::arm_neon_vld2dup:
13936 case Intrinsic::arm_neon_vld3dup:
13937 case Intrinsic::arm_neon_vld4dup:
13938 case Intrinsic::arm_neon_vst1:
13939 case Intrinsic::arm_neon_vst1x2:
13940 case Intrinsic::arm_neon_vst1x3:
13941 case Intrinsic::arm_neon_vst1x4:
13942 case Intrinsic::arm_neon_vst2:
13943 case Intrinsic::arm_neon_vst3:
13944 case Intrinsic::arm_neon_vst4:
13945 case Intrinsic::arm_neon_vst2lane:
13946 case Intrinsic::arm_neon_vst3lane:
13947 case Intrinsic::arm_neon_vst4lane:
13948 return PerformVLDCombine(N, DCI);
13949 default: break;
13951 break;
13953 return SDValue();
13956 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
13957 EVT VT) const {
13958 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
13961 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
13962 unsigned Alignment,
13963 MachineMemOperand::Flags,
13964 bool *Fast) const {
13965 // Depends what it gets converted into if the type is weird.
13966 if (!VT.isSimple())
13967 return false;
13969 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
13970 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
13971 auto Ty = VT.getSimpleVT().SimpleTy;
13973 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
13974 // Unaligned access can use (for example) LRDB, LRDH, LDR
13975 if (AllowsUnaligned) {
13976 if (Fast)
13977 *Fast = Subtarget->hasV7Ops();
13978 return true;
13982 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
13983 // For any little-endian targets with neon, we can support unaligned ld/st
13984 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
13985 // A big-endian target may also explicitly support unaligned accesses
13986 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
13987 if (Fast)
13988 *Fast = true;
13989 return true;
13993 if (!Subtarget->hasMVEIntegerOps())
13994 return false;
13996 // These are for predicates
13997 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
13998 if (Fast)
13999 *Fast = true;
14000 return true;
14003 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 &&
14004 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 &&
14005 Ty != MVT::v2f64 &&
14006 // These are for truncated stores
14007 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16)
14008 return false;
14010 if (Subtarget->isLittle()) {
14011 // In little-endian MVE, the store instructions VSTRB.U8,
14012 // VSTRH.U16 and VSTRW.U32 all store the vector register in
14013 // exactly the same format, and differ only in the range of
14014 // their immediate offset field and the required alignment.
14016 // In particular, VSTRB.U8 can store a vector at byte alignment.
14017 // So at this stage we can simply say that loads/stores of all
14018 // 128-bit wide vector types are permitted at any alignment,
14019 // because we know at least _one_ instruction can manage that.
14021 // Later on we might find that some of those loads are better
14022 // generated as VLDRW.U32 if alignment permits, to take
14023 // advantage of the larger immediate range. But for the moment,
14024 // all that matters is that if we don't lower the load then
14025 // _some_ instruction can handle it.
14026 if (Fast)
14027 *Fast = true;
14028 return true;
14029 } else {
14030 // In big-endian MVE, those instructions aren't so similar
14031 // after all, because they reorder the bytes of the vector
14032 // differently. So this time we can only store a particular
14033 // kind of vector if its alignment is at least the element
14034 // type. And we can't store vectors of i64 or f64 at all
14035 // without having to do some postprocessing, because there's
14036 // no VSTRD.U64.
14037 if (Ty == MVT::v16i8 ||
14038 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) ||
14039 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) {
14040 if (Fast)
14041 *Fast = true;
14042 return true;
14046 return false;
14049 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14050 unsigned AlignCheck) {
14051 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14052 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14055 EVT ARMTargetLowering::getOptimalMemOpType(
14056 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14057 bool ZeroMemset, bool MemcpyStrSrc,
14058 const AttributeList &FuncAttributes) const {
14059 // See if we can use NEON instructions for this...
14060 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14061 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14062 bool Fast;
14063 if (Size >= 16 &&
14064 (memOpAlign(SrcAlign, DstAlign, 16) ||
14065 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14066 MachineMemOperand::MONone, &Fast) &&
14067 Fast))) {
14068 return MVT::v2f64;
14069 } else if (Size >= 8 &&
14070 (memOpAlign(SrcAlign, DstAlign, 8) ||
14071 (allowsMisalignedMemoryAccesses(
14072 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14073 Fast))) {
14074 return MVT::f64;
14078 // Let the target-independent logic figure it out.
14079 return MVT::Other;
14082 // 64-bit integers are split into their high and low parts and held in two
14083 // different registers, so the trunc is free since the low register can just
14084 // be used.
14085 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14086 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14087 return false;
14088 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14089 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14090 return (SrcBits == 64 && DestBits == 32);
14093 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14094 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14095 !DstVT.isInteger())
14096 return false;
14097 unsigned SrcBits = SrcVT.getSizeInBits();
14098 unsigned DestBits = DstVT.getSizeInBits();
14099 return (SrcBits == 64 && DestBits == 32);
14102 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14103 if (Val.getOpcode() != ISD::LOAD)
14104 return false;
14106 EVT VT1 = Val.getValueType();
14107 if (!VT1.isSimple() || !VT1.isInteger() ||
14108 !VT2.isSimple() || !VT2.isInteger())
14109 return false;
14111 switch (VT1.getSimpleVT().SimpleTy) {
14112 default: break;
14113 case MVT::i1:
14114 case MVT::i8:
14115 case MVT::i16:
14116 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14117 return true;
14120 return false;
14123 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14124 if (!VT.isSimple())
14125 return false;
14127 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14128 // negate values directly (fneg is free). So, we don't want to let the DAG
14129 // combiner rewrite fneg into xors and some other instructions. For f16 and
14130 // FullFP16 argument passing, some bitcast nodes may be introduced,
14131 // triggering this DAG combine rewrite, so we are avoiding that with this.
14132 switch (VT.getSimpleVT().SimpleTy) {
14133 default: break;
14134 case MVT::f16:
14135 return Subtarget->hasFullFP16();
14138 return false;
14141 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14142 /// of the vector elements.
14143 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14144 auto areExtDoubled = [](Instruction *Ext) {
14145 return Ext->getType()->getScalarSizeInBits() ==
14146 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14149 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14150 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14151 !areExtDoubled(cast<Instruction>(Ext1)) ||
14152 !areExtDoubled(cast<Instruction>(Ext2)))
14153 return false;
14155 return true;
14158 /// Check if sinking \p I's operands to I's basic block is profitable, because
14159 /// the operands can be folded into a target instruction, e.g.
14160 /// sext/zext can be folded into vsubl.
14161 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14162 SmallVectorImpl<Use *> &Ops) const {
14163 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14164 return false;
14166 switch (I->getOpcode()) {
14167 case Instruction::Sub:
14168 case Instruction::Add: {
14169 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14170 return false;
14171 Ops.push_back(&I->getOperandUse(0));
14172 Ops.push_back(&I->getOperandUse(1));
14173 return true;
14175 default:
14176 return false;
14178 return false;
14181 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14182 EVT VT = ExtVal.getValueType();
14184 if (!isTypeLegal(VT))
14185 return false;
14187 // Don't create a loadext if we can fold the extension into a wide/long
14188 // instruction.
14189 // If there's more than one user instruction, the loadext is desirable no
14190 // matter what. There can be two uses by the same instruction.
14191 if (ExtVal->use_empty() ||
14192 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14193 return true;
14195 SDNode *U = *ExtVal->use_begin();
14196 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14197 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14198 return false;
14200 return true;
14203 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14204 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14205 return false;
14207 if (!isTypeLegal(EVT::getEVT(Ty1)))
14208 return false;
14210 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14212 // Assuming the caller doesn't have a zeroext or signext return parameter,
14213 // truncation all the way down to i1 is valid.
14214 return true;
14217 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14218 const AddrMode &AM, Type *Ty,
14219 unsigned AS) const {
14220 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14221 if (Subtarget->hasFPAO())
14222 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14223 return 0;
14225 return -1;
14228 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14229 if (V < 0)
14230 return false;
14232 unsigned Scale = 1;
14233 switch (VT.getSimpleVT().SimpleTy) {
14234 case MVT::i1:
14235 case MVT::i8:
14236 // Scale == 1;
14237 break;
14238 case MVT::i16:
14239 // Scale == 2;
14240 Scale = 2;
14241 break;
14242 default:
14243 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14244 // Scale == 4;
14245 Scale = 4;
14246 break;
14249 if ((V & (Scale - 1)) != 0)
14250 return false;
14251 return isUInt<5>(V / Scale);
14254 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14255 const ARMSubtarget *Subtarget) {
14256 if (!VT.isInteger() && !VT.isFloatingPoint())
14257 return false;
14258 if (VT.isVector() && Subtarget->hasNEON())
14259 return false;
14260 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14261 !Subtarget->hasMVEFloatOps())
14262 return false;
14264 bool IsNeg = false;
14265 if (V < 0) {
14266 IsNeg = true;
14267 V = -V;
14270 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14272 // MVE: size * imm7
14273 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14274 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14275 case MVT::i32:
14276 case MVT::f32:
14277 return isShiftedUInt<7,2>(V);
14278 case MVT::i16:
14279 case MVT::f16:
14280 return isShiftedUInt<7,1>(V);
14281 case MVT::i8:
14282 return isUInt<7>(V);
14283 default:
14284 return false;
14288 // half VLDR: 2 * imm8
14289 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14290 return isShiftedUInt<8, 1>(V);
14291 // VLDR and LDRD: 4 * imm8
14292 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14293 return isShiftedUInt<8, 2>(V);
14295 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14296 // + imm12 or - imm8
14297 if (IsNeg)
14298 return isUInt<8>(V);
14299 return isUInt<12>(V);
14302 return false;
14305 /// isLegalAddressImmediate - Return true if the integer value can be used
14306 /// as the offset of the target addressing mode for load / store of the
14307 /// given type.
14308 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14309 const ARMSubtarget *Subtarget) {
14310 if (V == 0)
14311 return true;
14313 if (!VT.isSimple())
14314 return false;
14316 if (Subtarget->isThumb1Only())
14317 return isLegalT1AddressImmediate(V, VT);
14318 else if (Subtarget->isThumb2())
14319 return isLegalT2AddressImmediate(V, VT, Subtarget);
14321 // ARM mode.
14322 if (V < 0)
14323 V = - V;
14324 switch (VT.getSimpleVT().SimpleTy) {
14325 default: return false;
14326 case MVT::i1:
14327 case MVT::i8:
14328 case MVT::i32:
14329 // +- imm12
14330 return isUInt<12>(V);
14331 case MVT::i16:
14332 // +- imm8
14333 return isUInt<8>(V);
14334 case MVT::f32:
14335 case MVT::f64:
14336 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14337 return false;
14338 return isShiftedUInt<8, 2>(V);
14342 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14343 EVT VT) const {
14344 int Scale = AM.Scale;
14345 if (Scale < 0)
14346 return false;
14348 switch (VT.getSimpleVT().SimpleTy) {
14349 default: return false;
14350 case MVT::i1:
14351 case MVT::i8:
14352 case MVT::i16:
14353 case MVT::i32:
14354 if (Scale == 1)
14355 return true;
14356 // r + r << imm
14357 Scale = Scale & ~1;
14358 return Scale == 2 || Scale == 4 || Scale == 8;
14359 case MVT::i64:
14360 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14361 // version in Thumb mode.
14362 // r + r
14363 if (Scale == 1)
14364 return true;
14365 // r * 2 (this can be lowered to r + r).
14366 if (!AM.HasBaseReg && Scale == 2)
14367 return true;
14368 return false;
14369 case MVT::isVoid:
14370 // Note, we allow "void" uses (basically, uses that aren't loads or
14371 // stores), because arm allows folding a scale into many arithmetic
14372 // operations. This should be made more precise and revisited later.
14374 // Allow r << imm, but the imm has to be a multiple of two.
14375 if (Scale & 1) return false;
14376 return isPowerOf2_32(Scale);
14380 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14381 EVT VT) const {
14382 const int Scale = AM.Scale;
14384 // Negative scales are not supported in Thumb1.
14385 if (Scale < 0)
14386 return false;
14388 // Thumb1 addressing modes do not support register scaling excepting the
14389 // following cases:
14390 // 1. Scale == 1 means no scaling.
14391 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14392 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14395 /// isLegalAddressingMode - Return true if the addressing mode represented
14396 /// by AM is legal for this target, for a load/store of the specified type.
14397 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14398 const AddrMode &AM, Type *Ty,
14399 unsigned AS, Instruction *I) const {
14400 EVT VT = getValueType(DL, Ty, true);
14401 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14402 return false;
14404 // Can never fold addr of global into load/store.
14405 if (AM.BaseGV)
14406 return false;
14408 switch (AM.Scale) {
14409 case 0: // no scale reg, must be "r+i" or "r", or "i".
14410 break;
14411 default:
14412 // ARM doesn't support any R+R*scale+imm addr modes.
14413 if (AM.BaseOffs)
14414 return false;
14416 if (!VT.isSimple())
14417 return false;
14419 if (Subtarget->isThumb1Only())
14420 return isLegalT1ScaledAddressingMode(AM, VT);
14422 if (Subtarget->isThumb2())
14423 return isLegalT2ScaledAddressingMode(AM, VT);
14425 int Scale = AM.Scale;
14426 switch (VT.getSimpleVT().SimpleTy) {
14427 default: return false;
14428 case MVT::i1:
14429 case MVT::i8:
14430 case MVT::i32:
14431 if (Scale < 0) Scale = -Scale;
14432 if (Scale == 1)
14433 return true;
14434 // r + r << imm
14435 return isPowerOf2_32(Scale & ~1);
14436 case MVT::i16:
14437 case MVT::i64:
14438 // r +/- r
14439 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14440 return true;
14441 // r * 2 (this can be lowered to r + r).
14442 if (!AM.HasBaseReg && Scale == 2)
14443 return true;
14444 return false;
14446 case MVT::isVoid:
14447 // Note, we allow "void" uses (basically, uses that aren't loads or
14448 // stores), because arm allows folding a scale into many arithmetic
14449 // operations. This should be made more precise and revisited later.
14451 // Allow r << imm, but the imm has to be a multiple of two.
14452 if (Scale & 1) return false;
14453 return isPowerOf2_32(Scale);
14456 return true;
14459 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14460 /// icmp immediate, that is the target has icmp instructions which can compare
14461 /// a register against the immediate without having to materialize the
14462 /// immediate into a register.
14463 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14464 // Thumb2 and ARM modes can use cmn for negative immediates.
14465 if (!Subtarget->isThumb())
14466 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14467 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14468 if (Subtarget->isThumb2())
14469 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14470 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14471 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14472 return Imm >= 0 && Imm <= 255;
14475 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14476 /// *or sub* immediate, that is the target has add or sub instructions which can
14477 /// add a register with the immediate without having to materialize the
14478 /// immediate into a register.
14479 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14480 // Same encoding for add/sub, just flip the sign.
14481 int64_t AbsImm = std::abs(Imm);
14482 if (!Subtarget->isThumb())
14483 return ARM_AM::getSOImmVal(AbsImm) != -1;
14484 if (Subtarget->isThumb2())
14485 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14486 // Thumb1 only has 8-bit unsigned immediate.
14487 return AbsImm >= 0 && AbsImm <= 255;
14490 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14491 bool isSEXTLoad, SDValue &Base,
14492 SDValue &Offset, bool &isInc,
14493 SelectionDAG &DAG) {
14494 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14495 return false;
14497 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14498 // AddressingMode 3
14499 Base = Ptr->getOperand(0);
14500 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14501 int RHSC = (int)RHS->getZExtValue();
14502 if (RHSC < 0 && RHSC > -256) {
14503 assert(Ptr->getOpcode() == ISD::ADD);
14504 isInc = false;
14505 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14506 return true;
14509 isInc = (Ptr->getOpcode() == ISD::ADD);
14510 Offset = Ptr->getOperand(1);
14511 return true;
14512 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14513 // AddressingMode 2
14514 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14515 int RHSC = (int)RHS->getZExtValue();
14516 if (RHSC < 0 && RHSC > -0x1000) {
14517 assert(Ptr->getOpcode() == ISD::ADD);
14518 isInc = false;
14519 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14520 Base = Ptr->getOperand(0);
14521 return true;
14525 if (Ptr->getOpcode() == ISD::ADD) {
14526 isInc = true;
14527 ARM_AM::ShiftOpc ShOpcVal=
14528 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14529 if (ShOpcVal != ARM_AM::no_shift) {
14530 Base = Ptr->getOperand(1);
14531 Offset = Ptr->getOperand(0);
14532 } else {
14533 Base = Ptr->getOperand(0);
14534 Offset = Ptr->getOperand(1);
14536 return true;
14539 isInc = (Ptr->getOpcode() == ISD::ADD);
14540 Base = Ptr->getOperand(0);
14541 Offset = Ptr->getOperand(1);
14542 return true;
14545 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14546 return false;
14549 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14550 bool isSEXTLoad, SDValue &Base,
14551 SDValue &Offset, bool &isInc,
14552 SelectionDAG &DAG) {
14553 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14554 return false;
14556 Base = Ptr->getOperand(0);
14557 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14558 int RHSC = (int)RHS->getZExtValue();
14559 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14560 assert(Ptr->getOpcode() == ISD::ADD);
14561 isInc = false;
14562 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14563 return true;
14564 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14565 isInc = Ptr->getOpcode() == ISD::ADD;
14566 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14567 return true;
14571 return false;
14574 /// getPreIndexedAddressParts - returns true by value, base pointer and
14575 /// offset pointer and addressing mode by reference if the node's address
14576 /// can be legally represented as pre-indexed load / store address.
14577 bool
14578 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14579 SDValue &Offset,
14580 ISD::MemIndexedMode &AM,
14581 SelectionDAG &DAG) const {
14582 if (Subtarget->isThumb1Only())
14583 return false;
14585 EVT VT;
14586 SDValue Ptr;
14587 bool isSEXTLoad = false;
14588 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14589 Ptr = LD->getBasePtr();
14590 VT = LD->getMemoryVT();
14591 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14592 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14593 Ptr = ST->getBasePtr();
14594 VT = ST->getMemoryVT();
14595 } else
14596 return false;
14598 bool isInc;
14599 bool isLegal = false;
14600 if (Subtarget->isThumb2())
14601 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14602 Offset, isInc, DAG);
14603 else
14604 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14605 Offset, isInc, DAG);
14606 if (!isLegal)
14607 return false;
14609 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14610 return true;
14613 /// getPostIndexedAddressParts - returns true by value, base pointer and
14614 /// offset pointer and addressing mode by reference if this node can be
14615 /// combined with a load / store to form a post-indexed load / store.
14616 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14617 SDValue &Base,
14618 SDValue &Offset,
14619 ISD::MemIndexedMode &AM,
14620 SelectionDAG &DAG) const {
14621 EVT VT;
14622 SDValue Ptr;
14623 bool isSEXTLoad = false, isNonExt;
14624 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14625 VT = LD->getMemoryVT();
14626 Ptr = LD->getBasePtr();
14627 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14628 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14629 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14630 VT = ST->getMemoryVT();
14631 Ptr = ST->getBasePtr();
14632 isNonExt = !ST->isTruncatingStore();
14633 } else
14634 return false;
14636 if (Subtarget->isThumb1Only()) {
14637 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14638 // must be non-extending/truncating, i32, with an offset of 4.
14639 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14640 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14641 return false;
14642 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14643 if (!RHS || RHS->getZExtValue() != 4)
14644 return false;
14646 Offset = Op->getOperand(1);
14647 Base = Op->getOperand(0);
14648 AM = ISD::POST_INC;
14649 return true;
14652 bool isInc;
14653 bool isLegal = false;
14654 if (Subtarget->isThumb2())
14655 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14656 isInc, DAG);
14657 else
14658 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14659 isInc, DAG);
14660 if (!isLegal)
14661 return false;
14663 if (Ptr != Base) {
14664 // Swap base ptr and offset to catch more post-index load / store when
14665 // it's legal. In Thumb2 mode, offset must be an immediate.
14666 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14667 !Subtarget->isThumb2())
14668 std::swap(Base, Offset);
14670 // Post-indexed load / store update the base pointer.
14671 if (Ptr != Base)
14672 return false;
14675 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14676 return true;
14679 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14680 KnownBits &Known,
14681 const APInt &DemandedElts,
14682 const SelectionDAG &DAG,
14683 unsigned Depth) const {
14684 unsigned BitWidth = Known.getBitWidth();
14685 Known.resetAll();
14686 switch (Op.getOpcode()) {
14687 default: break;
14688 case ARMISD::ADDC:
14689 case ARMISD::ADDE:
14690 case ARMISD::SUBC:
14691 case ARMISD::SUBE:
14692 // Special cases when we convert a carry to a boolean.
14693 if (Op.getResNo() == 0) {
14694 SDValue LHS = Op.getOperand(0);
14695 SDValue RHS = Op.getOperand(1);
14696 // (ADDE 0, 0, C) will give us a single bit.
14697 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14698 isNullConstant(RHS)) {
14699 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14700 return;
14703 break;
14704 case ARMISD::CMOV: {
14705 // Bits are known zero/one if known on the LHS and RHS.
14706 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14707 if (Known.isUnknown())
14708 return;
14710 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14711 Known.Zero &= KnownRHS.Zero;
14712 Known.One &= KnownRHS.One;
14713 return;
14715 case ISD::INTRINSIC_W_CHAIN: {
14716 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14717 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14718 switch (IntID) {
14719 default: return;
14720 case Intrinsic::arm_ldaex:
14721 case Intrinsic::arm_ldrex: {
14722 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14723 unsigned MemBits = VT.getScalarSizeInBits();
14724 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14725 return;
14729 case ARMISD::BFI: {
14730 // Conservatively, we can recurse down the first operand
14731 // and just mask out all affected bits.
14732 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14734 // The operand to BFI is already a mask suitable for removing the bits it
14735 // sets.
14736 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14737 const APInt &Mask = CI->getAPIntValue();
14738 Known.Zero &= Mask;
14739 Known.One &= Mask;
14740 return;
14742 case ARMISD::VGETLANEs:
14743 case ARMISD::VGETLANEu: {
14744 const SDValue &SrcSV = Op.getOperand(0);
14745 EVT VecVT = SrcSV.getValueType();
14746 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14747 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14748 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14749 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14750 "VGETLANE index out of bounds");
14751 unsigned Idx = Pos->getZExtValue();
14752 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14753 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
14755 EVT VT = Op.getValueType();
14756 const unsigned DstSz = VT.getScalarSizeInBits();
14757 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
14758 (void)SrcSz;
14759 assert(SrcSz == Known.getBitWidth());
14760 assert(DstSz > SrcSz);
14761 if (Op.getOpcode() == ARMISD::VGETLANEs)
14762 Known = Known.sext(DstSz);
14763 else {
14764 Known = Known.zext(DstSz, true /* extended bits are known zero */);
14766 assert(DstSz == Known.getBitWidth());
14767 break;
14772 bool
14773 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
14774 const APInt &DemandedAPInt,
14775 TargetLoweringOpt &TLO) const {
14776 // Delay optimization, so we don't have to deal with illegal types, or block
14777 // optimizations.
14778 if (!TLO.LegalOps)
14779 return false;
14781 // Only optimize AND for now.
14782 if (Op.getOpcode() != ISD::AND)
14783 return false;
14785 EVT VT = Op.getValueType();
14787 // Ignore vectors.
14788 if (VT.isVector())
14789 return false;
14791 assert(VT == MVT::i32 && "Unexpected integer type");
14793 // Make sure the RHS really is a constant.
14794 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14795 if (!C)
14796 return false;
14798 unsigned Mask = C->getZExtValue();
14800 unsigned Demanded = DemandedAPInt.getZExtValue();
14801 unsigned ShrunkMask = Mask & Demanded;
14802 unsigned ExpandedMask = Mask | ~Demanded;
14804 // If the mask is all zeros, let the target-independent code replace the
14805 // result with zero.
14806 if (ShrunkMask == 0)
14807 return false;
14809 // If the mask is all ones, erase the AND. (Currently, the target-independent
14810 // code won't do this, so we have to do it explicitly to avoid an infinite
14811 // loop in obscure cases.)
14812 if (ExpandedMask == ~0U)
14813 return TLO.CombineTo(Op, Op.getOperand(0));
14815 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
14816 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
14818 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
14819 if (NewMask == Mask)
14820 return true;
14821 SDLoc DL(Op);
14822 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
14823 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
14824 return TLO.CombineTo(Op, NewOp);
14827 // Prefer uxtb mask.
14828 if (IsLegalMask(0xFF))
14829 return UseMask(0xFF);
14831 // Prefer uxth mask.
14832 if (IsLegalMask(0xFFFF))
14833 return UseMask(0xFFFF);
14835 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
14836 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14837 if (ShrunkMask < 256)
14838 return UseMask(ShrunkMask);
14840 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
14841 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14842 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
14843 return UseMask(ExpandedMask);
14845 // Potential improvements:
14847 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
14848 // We could try to prefer Thumb1 immediates which can be lowered to a
14849 // two-instruction sequence.
14850 // We could try to recognize more legal ARM/Thumb2 immediates here.
14852 return false;
14856 //===----------------------------------------------------------------------===//
14857 // ARM Inline Assembly Support
14858 //===----------------------------------------------------------------------===//
14860 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
14861 // Looking for "rev" which is V6+.
14862 if (!Subtarget->hasV6Ops())
14863 return false;
14865 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14866 std::string AsmStr = IA->getAsmString();
14867 SmallVector<StringRef, 4> AsmPieces;
14868 SplitString(AsmStr, AsmPieces, ";\n");
14870 switch (AsmPieces.size()) {
14871 default: return false;
14872 case 1:
14873 AsmStr = AsmPieces[0];
14874 AsmPieces.clear();
14875 SplitString(AsmStr, AsmPieces, " \t,");
14877 // rev $0, $1
14878 if (AsmPieces.size() == 3 &&
14879 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
14880 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
14881 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14882 if (Ty && Ty->getBitWidth() == 32)
14883 return IntrinsicLowering::LowerToByteSwap(CI);
14885 break;
14888 return false;
14891 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
14892 // At this point, we have to lower this constraint to something else, so we
14893 // lower it to an "r" or "w". However, by doing this we will force the result
14894 // to be in register, while the X constraint is much more permissive.
14896 // Although we are correct (we are free to emit anything, without
14897 // constraints), we might break use cases that would expect us to be more
14898 // efficient and emit something else.
14899 if (!Subtarget->hasVFP2Base())
14900 return "r";
14901 if (ConstraintVT.isFloatingPoint())
14902 return "w";
14903 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
14904 (ConstraintVT.getSizeInBits() == 64 ||
14905 ConstraintVT.getSizeInBits() == 128))
14906 return "w";
14908 return "r";
14911 /// getConstraintType - Given a constraint letter, return the type of
14912 /// constraint it is for this target.
14913 ARMTargetLowering::ConstraintType
14914 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
14915 if (Constraint.size() == 1) {
14916 switch (Constraint[0]) {
14917 default: break;
14918 case 'l': return C_RegisterClass;
14919 case 'w': return C_RegisterClass;
14920 case 'h': return C_RegisterClass;
14921 case 'x': return C_RegisterClass;
14922 case 't': return C_RegisterClass;
14923 case 'j': return C_Other; // Constant for movw.
14924 // An address with a single base register. Due to the way we
14925 // currently handle addresses it is the same as an 'r' memory constraint.
14926 case 'Q': return C_Memory;
14928 } else if (Constraint.size() == 2) {
14929 switch (Constraint[0]) {
14930 default: break;
14931 case 'T': return C_RegisterClass;
14932 // All 'U+' constraints are addresses.
14933 case 'U': return C_Memory;
14936 return TargetLowering::getConstraintType(Constraint);
14939 /// Examine constraint type and operand type and determine a weight value.
14940 /// This object must already have been set up with the operand type
14941 /// and the current alternative constraint selected.
14942 TargetLowering::ConstraintWeight
14943 ARMTargetLowering::getSingleConstraintMatchWeight(
14944 AsmOperandInfo &info, const char *constraint) const {
14945 ConstraintWeight weight = CW_Invalid;
14946 Value *CallOperandVal = info.CallOperandVal;
14947 // If we don't have a value, we can't do a match,
14948 // but allow it at the lowest weight.
14949 if (!CallOperandVal)
14950 return CW_Default;
14951 Type *type = CallOperandVal->getType();
14952 // Look at the constraint type.
14953 switch (*constraint) {
14954 default:
14955 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14956 break;
14957 case 'l':
14958 if (type->isIntegerTy()) {
14959 if (Subtarget->isThumb())
14960 weight = CW_SpecificReg;
14961 else
14962 weight = CW_Register;
14964 break;
14965 case 'w':
14966 if (type->isFloatingPointTy())
14967 weight = CW_Register;
14968 break;
14970 return weight;
14973 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
14975 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
14976 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
14977 switch (Constraint.size()) {
14978 case 1:
14979 // GCC ARM Constraint Letters
14980 switch (Constraint[0]) {
14981 case 'l': // Low regs or general regs.
14982 if (Subtarget->isThumb())
14983 return RCPair(0U, &ARM::tGPRRegClass);
14984 return RCPair(0U, &ARM::GPRRegClass);
14985 case 'h': // High regs or no regs.
14986 if (Subtarget->isThumb())
14987 return RCPair(0U, &ARM::hGPRRegClass);
14988 break;
14989 case 'r':
14990 if (Subtarget->isThumb1Only())
14991 return RCPair(0U, &ARM::tGPRRegClass);
14992 return RCPair(0U, &ARM::GPRRegClass);
14993 case 'w':
14994 if (VT == MVT::Other)
14995 break;
14996 if (VT == MVT::f32)
14997 return RCPair(0U, &ARM::SPRRegClass);
14998 if (VT.getSizeInBits() == 64)
14999 return RCPair(0U, &ARM::DPRRegClass);
15000 if (VT.getSizeInBits() == 128)
15001 return RCPair(0U, &ARM::QPRRegClass);
15002 break;
15003 case 'x':
15004 if (VT == MVT::Other)
15005 break;
15006 if (VT == MVT::f32)
15007 return RCPair(0U, &ARM::SPR_8RegClass);
15008 if (VT.getSizeInBits() == 64)
15009 return RCPair(0U, &ARM::DPR_8RegClass);
15010 if (VT.getSizeInBits() == 128)
15011 return RCPair(0U, &ARM::QPR_8RegClass);
15012 break;
15013 case 't':
15014 if (VT == MVT::Other)
15015 break;
15016 if (VT == MVT::f32 || VT == MVT::i32)
15017 return RCPair(0U, &ARM::SPRRegClass);
15018 if (VT.getSizeInBits() == 64)
15019 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15020 if (VT.getSizeInBits() == 128)
15021 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15022 break;
15024 break;
15026 case 2:
15027 if (Constraint[0] == 'T') {
15028 switch (Constraint[1]) {
15029 default:
15030 break;
15031 case 'e':
15032 return RCPair(0U, &ARM::tGPREvenRegClass);
15033 case 'o':
15034 return RCPair(0U, &ARM::tGPROddRegClass);
15037 break;
15039 default:
15040 break;
15043 if (StringRef("{cc}").equals_lower(Constraint))
15044 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15046 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15049 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15050 /// vector. If it is invalid, don't add anything to Ops.
15051 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15052 std::string &Constraint,
15053 std::vector<SDValue>&Ops,
15054 SelectionDAG &DAG) const {
15055 SDValue Result;
15057 // Currently only support length 1 constraints.
15058 if (Constraint.length() != 1) return;
15060 char ConstraintLetter = Constraint[0];
15061 switch (ConstraintLetter) {
15062 default: break;
15063 case 'j':
15064 case 'I': case 'J': case 'K': case 'L':
15065 case 'M': case 'N': case 'O':
15066 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15067 if (!C)
15068 return;
15070 int64_t CVal64 = C->getSExtValue();
15071 int CVal = (int) CVal64;
15072 // None of these constraints allow values larger than 32 bits. Check
15073 // that the value fits in an int.
15074 if (CVal != CVal64)
15075 return;
15077 switch (ConstraintLetter) {
15078 case 'j':
15079 // Constant suitable for movw, must be between 0 and
15080 // 65535.
15081 if (Subtarget->hasV6T2Ops())
15082 if (CVal >= 0 && CVal <= 65535)
15083 break;
15084 return;
15085 case 'I':
15086 if (Subtarget->isThumb1Only()) {
15087 // This must be a constant between 0 and 255, for ADD
15088 // immediates.
15089 if (CVal >= 0 && CVal <= 255)
15090 break;
15091 } else if (Subtarget->isThumb2()) {
15092 // A constant that can be used as an immediate value in a
15093 // data-processing instruction.
15094 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15095 break;
15096 } else {
15097 // A constant that can be used as an immediate value in a
15098 // data-processing instruction.
15099 if (ARM_AM::getSOImmVal(CVal) != -1)
15100 break;
15102 return;
15104 case 'J':
15105 if (Subtarget->isThumb1Only()) {
15106 // This must be a constant between -255 and -1, for negated ADD
15107 // immediates. This can be used in GCC with an "n" modifier that
15108 // prints the negated value, for use with SUB instructions. It is
15109 // not useful otherwise but is implemented for compatibility.
15110 if (CVal >= -255 && CVal <= -1)
15111 break;
15112 } else {
15113 // This must be a constant between -4095 and 4095. It is not clear
15114 // what this constraint is intended for. Implemented for
15115 // compatibility with GCC.
15116 if (CVal >= -4095 && CVal <= 4095)
15117 break;
15119 return;
15121 case 'K':
15122 if (Subtarget->isThumb1Only()) {
15123 // A 32-bit value where only one byte has a nonzero value. Exclude
15124 // zero to match GCC. This constraint is used by GCC internally for
15125 // constants that can be loaded with a move/shift combination.
15126 // It is not useful otherwise but is implemented for compatibility.
15127 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15128 break;
15129 } else if (Subtarget->isThumb2()) {
15130 // A constant whose bitwise inverse can be used as an immediate
15131 // value in a data-processing instruction. This can be used in GCC
15132 // with a "B" modifier that prints the inverted value, for use with
15133 // BIC and MVN instructions. It is not useful otherwise but is
15134 // implemented for compatibility.
15135 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15136 break;
15137 } else {
15138 // A constant whose bitwise inverse can be used as an immediate
15139 // value in a data-processing instruction. This can be used in GCC
15140 // with a "B" modifier that prints the inverted value, for use with
15141 // BIC and MVN instructions. It is not useful otherwise but is
15142 // implemented for compatibility.
15143 if (ARM_AM::getSOImmVal(~CVal) != -1)
15144 break;
15146 return;
15148 case 'L':
15149 if (Subtarget->isThumb1Only()) {
15150 // This must be a constant between -7 and 7,
15151 // for 3-operand ADD/SUB immediate instructions.
15152 if (CVal >= -7 && CVal < 7)
15153 break;
15154 } else if (Subtarget->isThumb2()) {
15155 // A constant whose negation can be used as an immediate value in a
15156 // data-processing instruction. This can be used in GCC with an "n"
15157 // modifier that prints the negated value, for use with SUB
15158 // instructions. It is not useful otherwise but is implemented for
15159 // compatibility.
15160 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15161 break;
15162 } else {
15163 // A constant whose negation can be used as an immediate value in a
15164 // data-processing instruction. This can be used in GCC with an "n"
15165 // modifier that prints the negated value, for use with SUB
15166 // instructions. It is not useful otherwise but is implemented for
15167 // compatibility.
15168 if (ARM_AM::getSOImmVal(-CVal) != -1)
15169 break;
15171 return;
15173 case 'M':
15174 if (Subtarget->isThumb1Only()) {
15175 // This must be a multiple of 4 between 0 and 1020, for
15176 // ADD sp + immediate.
15177 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15178 break;
15179 } else {
15180 // A power of two or a constant between 0 and 32. This is used in
15181 // GCC for the shift amount on shifted register operands, but it is
15182 // useful in general for any shift amounts.
15183 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15184 break;
15186 return;
15188 case 'N':
15189 if (Subtarget->isThumb()) { // FIXME thumb2
15190 // This must be a constant between 0 and 31, for shift amounts.
15191 if (CVal >= 0 && CVal <= 31)
15192 break;
15194 return;
15196 case 'O':
15197 if (Subtarget->isThumb()) { // FIXME thumb2
15198 // This must be a multiple of 4 between -508 and 508, for
15199 // ADD/SUB sp = sp + immediate.
15200 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15201 break;
15203 return;
15205 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15206 break;
15209 if (Result.getNode()) {
15210 Ops.push_back(Result);
15211 return;
15213 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15216 static RTLIB::Libcall getDivRemLibcall(
15217 const SDNode *N, MVT::SimpleValueType SVT) {
15218 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15219 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15220 "Unhandled Opcode in getDivRemLibcall");
15221 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15222 N->getOpcode() == ISD::SREM;
15223 RTLIB::Libcall LC;
15224 switch (SVT) {
15225 default: llvm_unreachable("Unexpected request for libcall!");
15226 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15227 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15228 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15229 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15231 return LC;
15234 static TargetLowering::ArgListTy getDivRemArgList(
15235 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15236 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15237 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15238 "Unhandled Opcode in getDivRemArgList");
15239 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15240 N->getOpcode() == ISD::SREM;
15241 TargetLowering::ArgListTy Args;
15242 TargetLowering::ArgListEntry Entry;
15243 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15244 EVT ArgVT = N->getOperand(i).getValueType();
15245 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15246 Entry.Node = N->getOperand(i);
15247 Entry.Ty = ArgTy;
15248 Entry.IsSExt = isSigned;
15249 Entry.IsZExt = !isSigned;
15250 Args.push_back(Entry);
15252 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15253 std::swap(Args[0], Args[1]);
15254 return Args;
15257 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15258 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15259 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15260 Subtarget->isTargetWindows()) &&
15261 "Register-based DivRem lowering only");
15262 unsigned Opcode = Op->getOpcode();
15263 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15264 "Invalid opcode for Div/Rem lowering");
15265 bool isSigned = (Opcode == ISD::SDIVREM);
15266 EVT VT = Op->getValueType(0);
15267 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15268 SDLoc dl(Op);
15270 // If the target has hardware divide, use divide + multiply + subtract:
15271 // div = a / b
15272 // rem = a - b * div
15273 // return {div, rem}
15274 // This should be lowered into UDIV/SDIV + MLS later on.
15275 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15276 : Subtarget->hasDivideInARMMode();
15277 if (hasDivide && Op->getValueType(0).isSimple() &&
15278 Op->getSimpleValueType(0) == MVT::i32) {
15279 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15280 const SDValue Dividend = Op->getOperand(0);
15281 const SDValue Divisor = Op->getOperand(1);
15282 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15283 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15284 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15286 SDValue Values[2] = {Div, Rem};
15287 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15290 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15291 VT.getSimpleVT().SimpleTy);
15292 SDValue InChain = DAG.getEntryNode();
15294 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15295 DAG.getContext(),
15296 Subtarget);
15298 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15299 getPointerTy(DAG.getDataLayout()));
15301 Type *RetTy = StructType::get(Ty, Ty);
15303 if (Subtarget->isTargetWindows())
15304 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15306 TargetLowering::CallLoweringInfo CLI(DAG);
15307 CLI.setDebugLoc(dl).setChain(InChain)
15308 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15309 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15311 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15312 return CallInfo.first;
15315 // Lowers REM using divmod helpers
15316 // see RTABI section 4.2/4.3
15317 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15318 // Build return types (div and rem)
15319 std::vector<Type*> RetTyParams;
15320 Type *RetTyElement;
15322 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15323 default: llvm_unreachable("Unexpected request for libcall!");
15324 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15325 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15326 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15327 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15330 RetTyParams.push_back(RetTyElement);
15331 RetTyParams.push_back(RetTyElement);
15332 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15333 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15335 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15336 SimpleTy);
15337 SDValue InChain = DAG.getEntryNode();
15338 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15339 Subtarget);
15340 bool isSigned = N->getOpcode() == ISD::SREM;
15341 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15342 getPointerTy(DAG.getDataLayout()));
15344 if (Subtarget->isTargetWindows())
15345 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15347 // Lower call
15348 CallLoweringInfo CLI(DAG);
15349 CLI.setChain(InChain)
15350 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15351 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15352 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15354 // Return second (rem) result operand (first contains div)
15355 SDNode *ResNode = CallResult.first.getNode();
15356 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15357 return ResNode->getOperand(1);
15360 SDValue
15361 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15362 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15363 SDLoc DL(Op);
15365 // Get the inputs.
15366 SDValue Chain = Op.getOperand(0);
15367 SDValue Size = Op.getOperand(1);
15369 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15370 "no-stack-arg-probe")) {
15371 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15372 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15373 Chain = SP.getValue(1);
15374 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15375 if (Align)
15376 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15377 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15378 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15379 SDValue Ops[2] = { SP, Chain };
15380 return DAG.getMergeValues(Ops, DL);
15383 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15384 DAG.getConstant(2, DL, MVT::i32));
15386 SDValue Flag;
15387 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15388 Flag = Chain.getValue(1);
15390 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15391 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15393 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15394 Chain = NewSP.getValue(1);
15396 SDValue Ops[2] = { NewSP, Chain };
15397 return DAG.getMergeValues(Ops, DL);
15400 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15401 SDValue SrcVal = Op.getOperand(0);
15402 const unsigned DstSz = Op.getValueType().getSizeInBits();
15403 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15404 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15405 "Unexpected type for custom-lowering FP_EXTEND");
15407 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15408 "With both FP DP and 16, any FP conversion is legal!");
15410 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15411 "With FP16, 16 to 32 conversion is legal!");
15413 // Either we are converting from 16 -> 64, without FP16 and/or
15414 // FP.double-precision or without Armv8-fp. So we must do it in two
15415 // steps.
15416 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15417 // without FP16. So we must do a function call.
15418 SDLoc Loc(Op);
15419 RTLIB::Libcall LC;
15420 if (SrcSz == 16) {
15421 // Instruction from 16 -> 32
15422 if (Subtarget->hasFP16())
15423 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15424 // Lib call from 16 -> 32
15425 else {
15426 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15427 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15428 "Unexpected type for custom-lowering FP_EXTEND");
15429 SrcVal =
15430 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first;
15434 if (DstSz != 64)
15435 return SrcVal;
15436 // For sure now SrcVal is 32 bits
15437 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15438 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15440 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15441 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15442 "Unexpected type for custom-lowering FP_EXTEND");
15443 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first;
15446 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15447 SDValue SrcVal = Op.getOperand(0);
15448 EVT SrcVT = SrcVal.getValueType();
15449 EVT DstVT = Op.getValueType();
15450 const unsigned DstSz = Op.getValueType().getSizeInBits();
15451 const unsigned SrcSz = SrcVT.getSizeInBits();
15452 (void)DstSz;
15453 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15454 "Unexpected type for custom-lowering FP_ROUND");
15456 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15457 "With both FP DP and 16, any FP conversion is legal!");
15459 SDLoc Loc(Op);
15461 // Instruction from 32 -> 16 if hasFP16 is valid
15462 if (SrcSz == 32 && Subtarget->hasFP16())
15463 return Op;
15465 // Lib call from 32 -> 16 / 64 -> [32, 16]
15466 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15467 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15468 "Unexpected type for custom-lowering FP_ROUND");
15469 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first;
15472 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15473 SelectionDAG &DAG) const {
15474 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15475 MVT HalfT = MVT::i32;
15476 SDLoc dl(N);
15477 SDValue Hi, Lo, Tmp;
15479 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15480 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15481 return ;
15483 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15484 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15486 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15487 DAG.getConstant(0, dl, HalfT));
15488 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15489 DAG.getConstant(1, dl, HalfT));
15491 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15492 DAG.getConstant(OpTypeBits - 1, dl,
15493 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15494 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15495 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15496 SDValue(Lo.getNode(), 1));
15497 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15498 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15500 Results.push_back(Lo);
15501 Results.push_back(Hi);
15504 bool
15505 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15506 // The ARM target isn't yet aware of offsets.
15507 return false;
15510 bool ARM::isBitFieldInvertedMask(unsigned v) {
15511 if (v == 0xffffffff)
15512 return false;
15514 // there can be 1's on either or both "outsides", all the "inside"
15515 // bits must be 0's
15516 return isShiftedMask_32(~v);
15519 /// isFPImmLegal - Returns true if the target can instruction select the
15520 /// specified FP immediate natively. If false, the legalizer will
15521 /// materialize the FP immediate as a load from a constant pool.
15522 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15523 bool ForCodeSize) const {
15524 if (!Subtarget->hasVFP3Base())
15525 return false;
15526 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15527 return ARM_AM::getFP16Imm(Imm) != -1;
15528 if (VT == MVT::f32)
15529 return ARM_AM::getFP32Imm(Imm) != -1;
15530 if (VT == MVT::f64 && Subtarget->hasFP64())
15531 return ARM_AM::getFP64Imm(Imm) != -1;
15532 return false;
15535 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15536 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15537 /// specified in the intrinsic calls.
15538 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15539 const CallInst &I,
15540 MachineFunction &MF,
15541 unsigned Intrinsic) const {
15542 switch (Intrinsic) {
15543 case Intrinsic::arm_neon_vld1:
15544 case Intrinsic::arm_neon_vld2:
15545 case Intrinsic::arm_neon_vld3:
15546 case Intrinsic::arm_neon_vld4:
15547 case Intrinsic::arm_neon_vld2lane:
15548 case Intrinsic::arm_neon_vld3lane:
15549 case Intrinsic::arm_neon_vld4lane:
15550 case Intrinsic::arm_neon_vld2dup:
15551 case Intrinsic::arm_neon_vld3dup:
15552 case Intrinsic::arm_neon_vld4dup: {
15553 Info.opc = ISD::INTRINSIC_W_CHAIN;
15554 // Conservatively set memVT to the entire set of vectors loaded.
15555 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15556 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15557 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15558 Info.ptrVal = I.getArgOperand(0);
15559 Info.offset = 0;
15560 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15561 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
15562 // volatile loads with NEON intrinsics not supported
15563 Info.flags = MachineMemOperand::MOLoad;
15564 return true;
15566 case Intrinsic::arm_neon_vld1x2:
15567 case Intrinsic::arm_neon_vld1x3:
15568 case Intrinsic::arm_neon_vld1x4: {
15569 Info.opc = ISD::INTRINSIC_W_CHAIN;
15570 // Conservatively set memVT to the entire set of vectors loaded.
15571 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15572 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15573 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15574 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15575 Info.offset = 0;
15576 Info.align = 0;
15577 // volatile loads with NEON intrinsics not supported
15578 Info.flags = MachineMemOperand::MOLoad;
15579 return true;
15581 case Intrinsic::arm_neon_vst1:
15582 case Intrinsic::arm_neon_vst2:
15583 case Intrinsic::arm_neon_vst3:
15584 case Intrinsic::arm_neon_vst4:
15585 case Intrinsic::arm_neon_vst2lane:
15586 case Intrinsic::arm_neon_vst3lane:
15587 case Intrinsic::arm_neon_vst4lane: {
15588 Info.opc = ISD::INTRINSIC_VOID;
15589 // Conservatively set memVT to the entire set of vectors stored.
15590 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15591 unsigned NumElts = 0;
15592 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15593 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15594 if (!ArgTy->isVectorTy())
15595 break;
15596 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15598 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15599 Info.ptrVal = I.getArgOperand(0);
15600 Info.offset = 0;
15601 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15602 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
15603 // volatile stores with NEON intrinsics not supported
15604 Info.flags = MachineMemOperand::MOStore;
15605 return true;
15607 case Intrinsic::arm_neon_vst1x2:
15608 case Intrinsic::arm_neon_vst1x3:
15609 case Intrinsic::arm_neon_vst1x4: {
15610 Info.opc = ISD::INTRINSIC_VOID;
15611 // Conservatively set memVT to the entire set of vectors stored.
15612 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15613 unsigned NumElts = 0;
15614 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15615 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15616 if (!ArgTy->isVectorTy())
15617 break;
15618 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15620 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15621 Info.ptrVal = I.getArgOperand(0);
15622 Info.offset = 0;
15623 Info.align = 0;
15624 // volatile stores with NEON intrinsics not supported
15625 Info.flags = MachineMemOperand::MOStore;
15626 return true;
15628 case Intrinsic::arm_ldaex:
15629 case Intrinsic::arm_ldrex: {
15630 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15631 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15632 Info.opc = ISD::INTRINSIC_W_CHAIN;
15633 Info.memVT = MVT::getVT(PtrTy->getElementType());
15634 Info.ptrVal = I.getArgOperand(0);
15635 Info.offset = 0;
15636 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15637 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15638 return true;
15640 case Intrinsic::arm_stlex:
15641 case Intrinsic::arm_strex: {
15642 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15643 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15644 Info.opc = ISD::INTRINSIC_W_CHAIN;
15645 Info.memVT = MVT::getVT(PtrTy->getElementType());
15646 Info.ptrVal = I.getArgOperand(1);
15647 Info.offset = 0;
15648 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15649 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15650 return true;
15652 case Intrinsic::arm_stlexd:
15653 case Intrinsic::arm_strexd:
15654 Info.opc = ISD::INTRINSIC_W_CHAIN;
15655 Info.memVT = MVT::i64;
15656 Info.ptrVal = I.getArgOperand(2);
15657 Info.offset = 0;
15658 Info.align = 8;
15659 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15660 return true;
15662 case Intrinsic::arm_ldaexd:
15663 case Intrinsic::arm_ldrexd:
15664 Info.opc = ISD::INTRINSIC_W_CHAIN;
15665 Info.memVT = MVT::i64;
15666 Info.ptrVal = I.getArgOperand(0);
15667 Info.offset = 0;
15668 Info.align = 8;
15669 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15670 return true;
15672 default:
15673 break;
15676 return false;
15679 /// Returns true if it is beneficial to convert a load of a constant
15680 /// to just the constant itself.
15681 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15682 Type *Ty) const {
15683 assert(Ty->isIntegerTy());
15685 unsigned Bits = Ty->getPrimitiveSizeInBits();
15686 if (Bits == 0 || Bits > 32)
15687 return false;
15688 return true;
15691 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15692 unsigned Index) const {
15693 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15694 return false;
15696 return (Index == 0 || Index == ResVT.getVectorNumElements());
15699 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15700 ARM_MB::MemBOpt Domain) const {
15701 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15703 // First, if the target has no DMB, see what fallback we can use.
15704 if (!Subtarget->hasDataBarrier()) {
15705 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15706 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15707 // here.
15708 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15709 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15710 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15711 Builder.getInt32(0), Builder.getInt32(7),
15712 Builder.getInt32(10), Builder.getInt32(5)};
15713 return Builder.CreateCall(MCR, args);
15714 } else {
15715 // Instead of using barriers, atomic accesses on these subtargets use
15716 // libcalls.
15717 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15719 } else {
15720 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15721 // Only a full system barrier exists in the M-class architectures.
15722 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15723 Constant *CDomain = Builder.getInt32(Domain);
15724 return Builder.CreateCall(DMB, CDomain);
15728 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15729 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15730 Instruction *Inst,
15731 AtomicOrdering Ord) const {
15732 switch (Ord) {
15733 case AtomicOrdering::NotAtomic:
15734 case AtomicOrdering::Unordered:
15735 llvm_unreachable("Invalid fence: unordered/non-atomic");
15736 case AtomicOrdering::Monotonic:
15737 case AtomicOrdering::Acquire:
15738 return nullptr; // Nothing to do
15739 case AtomicOrdering::SequentiallyConsistent:
15740 if (!Inst->hasAtomicStore())
15741 return nullptr; // Nothing to do
15742 LLVM_FALLTHROUGH;
15743 case AtomicOrdering::Release:
15744 case AtomicOrdering::AcquireRelease:
15745 if (Subtarget->preferISHSTBarriers())
15746 return makeDMB(Builder, ARM_MB::ISHST);
15747 // FIXME: add a comment with a link to documentation justifying this.
15748 else
15749 return makeDMB(Builder, ARM_MB::ISH);
15751 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
15754 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
15755 Instruction *Inst,
15756 AtomicOrdering Ord) const {
15757 switch (Ord) {
15758 case AtomicOrdering::NotAtomic:
15759 case AtomicOrdering::Unordered:
15760 llvm_unreachable("Invalid fence: unordered/not-atomic");
15761 case AtomicOrdering::Monotonic:
15762 case AtomicOrdering::Release:
15763 return nullptr; // Nothing to do
15764 case AtomicOrdering::Acquire:
15765 case AtomicOrdering::AcquireRelease:
15766 case AtomicOrdering::SequentiallyConsistent:
15767 return makeDMB(Builder, ARM_MB::ISH);
15769 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
15772 // Loads and stores less than 64-bits are already atomic; ones above that
15773 // are doomed anyway, so defer to the default libcall and blame the OS when
15774 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15775 // anything for those.
15776 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15777 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15778 return (Size == 64) && !Subtarget->isMClass();
15781 // Loads and stores less than 64-bits are already atomic; ones above that
15782 // are doomed anyway, so defer to the default libcall and blame the OS when
15783 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15784 // anything for those.
15785 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
15786 // guarantee, see DDI0406C ARM architecture reference manual,
15787 // sections A8.8.72-74 LDRD)
15788 TargetLowering::AtomicExpansionKind
15789 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15790 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15791 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
15792 : AtomicExpansionKind::None;
15795 // For the real atomic operations, we have ldrex/strex up to 32 bits,
15796 // and up to 64 bits on the non-M profiles
15797 TargetLowering::AtomicExpansionKind
15798 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15799 if (AI->isFloatingPointOperation())
15800 return AtomicExpansionKind::CmpXChg;
15802 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15803 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15804 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
15805 ? AtomicExpansionKind::LLSC
15806 : AtomicExpansionKind::None;
15809 TargetLowering::AtomicExpansionKind
15810 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
15811 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15812 // implement cmpxchg without spilling. If the address being exchanged is also
15813 // on the stack and close enough to the spill slot, this can lead to a
15814 // situation where the monitor always gets cleared and the atomic operation
15815 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15816 bool HasAtomicCmpXchg =
15817 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15818 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
15819 return AtomicExpansionKind::LLSC;
15820 return AtomicExpansionKind::None;
15823 bool ARMTargetLowering::shouldInsertFencesForAtomic(
15824 const Instruction *I) const {
15825 return InsertFencesForAtomic;
15828 // This has so far only been implemented for MachO.
15829 bool ARMTargetLowering::useLoadStackGuardNode() const {
15830 return Subtarget->isTargetMachO();
15833 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
15834 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15835 return TargetLowering::insertSSPDeclarations(M);
15837 // MSVC CRT has a global variable holding security cookie.
15838 M.getOrInsertGlobal("__security_cookie",
15839 Type::getInt8PtrTy(M.getContext()));
15841 // MSVC CRT has a function to validate security cookie.
15842 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15843 "__security_check_cookie", Type::getVoidTy(M.getContext()),
15844 Type::getInt8PtrTy(M.getContext()));
15845 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
15846 F->addAttribute(1, Attribute::AttrKind::InReg);
15849 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
15850 // MSVC CRT has a global variable holding security cookie.
15851 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15852 return M.getGlobalVariable("__security_cookie");
15853 return TargetLowering::getSDagStackGuard(M);
15856 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
15857 // MSVC CRT has a function to validate security cookie.
15858 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15859 return M.getFunction("__security_check_cookie");
15860 return TargetLowering::getSSPStackGuardCheck(M);
15863 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
15864 unsigned &Cost) const {
15865 // If we do not have NEON, vector types are not natively supported.
15866 if (!Subtarget->hasNEON())
15867 return false;
15869 // Floating point values and vector values map to the same register file.
15870 // Therefore, although we could do a store extract of a vector type, this is
15871 // better to leave at float as we have more freedom in the addressing mode for
15872 // those.
15873 if (VectorTy->isFPOrFPVectorTy())
15874 return false;
15876 // If the index is unknown at compile time, this is very expensive to lower
15877 // and it is not possible to combine the store with the extract.
15878 if (!isa<ConstantInt>(Idx))
15879 return false;
15881 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
15882 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
15883 // We can do a store + vector extract on any vector that fits perfectly in a D
15884 // or Q register.
15885 if (BitWidth == 64 || BitWidth == 128) {
15886 Cost = 0;
15887 return true;
15889 return false;
15892 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
15893 return Subtarget->hasV6T2Ops();
15896 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
15897 return Subtarget->hasV6T2Ops();
15900 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
15901 return !Subtarget->hasMinSize();
15904 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15905 AtomicOrdering Ord) const {
15906 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15907 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15908 bool IsAcquire = isAcquireOrStronger(Ord);
15910 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
15911 // intrinsic must return {i32, i32} and we have to recombine them into a
15912 // single i64 here.
15913 if (ValTy->getPrimitiveSizeInBits() == 64) {
15914 Intrinsic::ID Int =
15915 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
15916 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
15918 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15919 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
15921 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15922 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15923 if (!Subtarget->isLittle())
15924 std::swap (Lo, Hi);
15925 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15926 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15927 return Builder.CreateOr(
15928 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
15931 Type *Tys[] = { Addr->getType() };
15932 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
15933 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
15935 return Builder.CreateTruncOrBitCast(
15936 Builder.CreateCall(Ldrex, Addr),
15937 cast<PointerType>(Addr->getType())->getElementType());
15940 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15941 IRBuilder<> &Builder) const {
15942 if (!Subtarget->hasV7Ops())
15943 return;
15944 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15945 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
15948 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
15949 Value *Addr,
15950 AtomicOrdering Ord) const {
15951 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15952 bool IsRelease = isReleaseOrStronger(Ord);
15954 // Since the intrinsics must have legal type, the i64 intrinsics take two
15955 // parameters: "i32, i32". We must marshal Val into the appropriate form
15956 // before the call.
15957 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
15958 Intrinsic::ID Int =
15959 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
15960 Function *Strex = Intrinsic::getDeclaration(M, Int);
15961 Type *Int32Ty = Type::getInt32Ty(M->getContext());
15963 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
15964 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
15965 if (!Subtarget->isLittle())
15966 std::swap(Lo, Hi);
15967 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15968 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
15971 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
15972 Type *Tys[] = { Addr->getType() };
15973 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
15975 return Builder.CreateCall(
15976 Strex, {Builder.CreateZExtOrBitCast(
15977 Val, Strex->getFunctionType()->getParamType(0)),
15978 Addr});
15982 bool ARMTargetLowering::alignLoopsWithOptSize() const {
15983 return Subtarget->isMClass();
15986 /// A helper function for determining the number of interleaved accesses we
15987 /// will generate when lowering accesses of the given type.
15988 unsigned
15989 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
15990 const DataLayout &DL) const {
15991 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
15994 bool ARMTargetLowering::isLegalInterleavedAccessType(
15995 VectorType *VecTy, const DataLayout &DL) const {
15997 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
15998 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16000 // Ensure the vector doesn't have f16 elements. Even though we could do an
16001 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16002 // f32.
16003 if (VecTy->getElementType()->isHalfTy())
16004 return false;
16006 // Ensure the number of vector elements is greater than 1.
16007 if (VecTy->getNumElements() < 2)
16008 return false;
16010 // Ensure the element type is legal.
16011 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16012 return false;
16014 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16015 // 128 will be split into multiple interleaved accesses.
16016 return VecSize == 64 || VecSize % 128 == 0;
16019 /// Lower an interleaved load into a vldN intrinsic.
16021 /// E.g. Lower an interleaved load (Factor = 2):
16022 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16023 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16024 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16026 /// Into:
16027 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16028 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16029 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16030 bool ARMTargetLowering::lowerInterleavedLoad(
16031 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16032 ArrayRef<unsigned> Indices, unsigned Factor) const {
16033 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16034 "Invalid interleave factor");
16035 assert(!Shuffles.empty() && "Empty shufflevector input");
16036 assert(Shuffles.size() == Indices.size() &&
16037 "Unmatched number of shufflevectors and indices");
16039 VectorType *VecTy = Shuffles[0]->getType();
16040 Type *EltTy = VecTy->getVectorElementType();
16042 const DataLayout &DL = LI->getModule()->getDataLayout();
16044 // Skip if we do not have NEON and skip illegal vector types. We can
16045 // "legalize" wide vector types into multiple interleaved accesses as long as
16046 // the vector types are divisible by 128.
16047 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16048 return false;
16050 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16052 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16053 // load integer vectors first and then convert to pointer vectors.
16054 if (EltTy->isPointerTy())
16055 VecTy =
16056 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16058 IRBuilder<> Builder(LI);
16060 // The base address of the load.
16061 Value *BaseAddr = LI->getPointerOperand();
16063 if (NumLoads > 1) {
16064 // If we're going to generate more than one load, reset the sub-vector type
16065 // to something legal.
16066 VecTy = VectorType::get(VecTy->getVectorElementType(),
16067 VecTy->getVectorNumElements() / NumLoads);
16069 // We will compute the pointer operand of each load from the original base
16070 // address using GEPs. Cast the base address to a pointer to the scalar
16071 // element type.
16072 BaseAddr = Builder.CreateBitCast(
16073 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16074 LI->getPointerAddressSpace()));
16077 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16079 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16080 Type *Tys[] = {VecTy, Int8Ptr};
16081 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16082 Intrinsic::arm_neon_vld3,
16083 Intrinsic::arm_neon_vld4};
16084 Function *VldnFunc =
16085 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16087 // Holds sub-vectors extracted from the load intrinsic return values. The
16088 // sub-vectors are associated with the shufflevector instructions they will
16089 // replace.
16090 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16092 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16093 // If we're generating more than one load, compute the base address of
16094 // subsequent loads as an offset from the previous.
16095 if (LoadCount > 0)
16096 BaseAddr =
16097 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16098 VecTy->getVectorNumElements() * Factor);
16100 SmallVector<Value *, 2> Ops;
16101 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16102 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16104 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16106 // Replace uses of each shufflevector with the corresponding vector loaded
16107 // by ldN.
16108 for (unsigned i = 0; i < Shuffles.size(); i++) {
16109 ShuffleVectorInst *SV = Shuffles[i];
16110 unsigned Index = Indices[i];
16112 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16114 // Convert the integer vector to pointer vector if the element is pointer.
16115 if (EltTy->isPointerTy())
16116 SubVec = Builder.CreateIntToPtr(
16117 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16118 VecTy->getVectorNumElements()));
16120 SubVecs[SV].push_back(SubVec);
16124 // Replace uses of the shufflevector instructions with the sub-vectors
16125 // returned by the load intrinsic. If a shufflevector instruction is
16126 // associated with more than one sub-vector, those sub-vectors will be
16127 // concatenated into a single wide vector.
16128 for (ShuffleVectorInst *SVI : Shuffles) {
16129 auto &SubVec = SubVecs[SVI];
16130 auto *WideVec =
16131 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16132 SVI->replaceAllUsesWith(WideVec);
16135 return true;
16138 /// Lower an interleaved store into a vstN intrinsic.
16140 /// E.g. Lower an interleaved store (Factor = 3):
16141 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16142 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16143 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16145 /// Into:
16146 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16147 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16148 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16149 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16151 /// Note that the new shufflevectors will be removed and we'll only generate one
16152 /// vst3 instruction in CodeGen.
16154 /// Example for a more general valid mask (Factor 3). Lower:
16155 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16156 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16157 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16159 /// Into:
16160 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16161 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16162 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16163 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16164 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16165 ShuffleVectorInst *SVI,
16166 unsigned Factor) const {
16167 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16168 "Invalid interleave factor");
16170 VectorType *VecTy = SVI->getType();
16171 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16172 "Invalid interleaved store");
16174 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16175 Type *EltTy = VecTy->getVectorElementType();
16176 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16178 const DataLayout &DL = SI->getModule()->getDataLayout();
16180 // Skip if we do not have NEON and skip illegal vector types. We can
16181 // "legalize" wide vector types into multiple interleaved accesses as long as
16182 // the vector types are divisible by 128.
16183 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16184 return false;
16186 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16188 Value *Op0 = SVI->getOperand(0);
16189 Value *Op1 = SVI->getOperand(1);
16190 IRBuilder<> Builder(SI);
16192 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16193 // vectors to integer vectors.
16194 if (EltTy->isPointerTy()) {
16195 Type *IntTy = DL.getIntPtrType(EltTy);
16197 // Convert to the corresponding integer vector.
16198 Type *IntVecTy =
16199 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16200 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16201 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16203 SubVecTy = VectorType::get(IntTy, LaneLen);
16206 // The base address of the store.
16207 Value *BaseAddr = SI->getPointerOperand();
16209 if (NumStores > 1) {
16210 // If we're going to generate more than one store, reset the lane length
16211 // and sub-vector type to something legal.
16212 LaneLen /= NumStores;
16213 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16215 // We will compute the pointer operand of each store from the original base
16216 // address using GEPs. Cast the base address to a pointer to the scalar
16217 // element type.
16218 BaseAddr = Builder.CreateBitCast(
16219 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16220 SI->getPointerAddressSpace()));
16223 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16225 auto Mask = SVI->getShuffleMask();
16227 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16228 Type *Tys[] = {Int8Ptr, SubVecTy};
16229 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16230 Intrinsic::arm_neon_vst3,
16231 Intrinsic::arm_neon_vst4};
16233 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16234 // If we generating more than one store, we compute the base address of
16235 // subsequent stores as an offset from the previous.
16236 if (StoreCount > 0)
16237 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16238 BaseAddr, LaneLen * Factor);
16240 SmallVector<Value *, 6> Ops;
16241 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16243 Function *VstNFunc =
16244 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16246 // Split the shufflevector operands into sub vectors for the new vstN call.
16247 for (unsigned i = 0; i < Factor; i++) {
16248 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16249 if (Mask[IdxI] >= 0) {
16250 Ops.push_back(Builder.CreateShuffleVector(
16251 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16252 } else {
16253 unsigned StartMask = 0;
16254 for (unsigned j = 1; j < LaneLen; j++) {
16255 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16256 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16257 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16258 break;
16261 // Note: If all elements in a chunk are undefs, StartMask=0!
16262 // Note: Filling undef gaps with random elements is ok, since
16263 // those elements were being written anyway (with undefs).
16264 // In the case of all undefs we're defaulting to using elems from 0
16265 // Note: StartMask cannot be negative, it's checked in
16266 // isReInterleaveMask
16267 Ops.push_back(Builder.CreateShuffleVector(
16268 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16272 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16273 Builder.CreateCall(VstNFunc, Ops);
16275 return true;
16278 enum HABaseType {
16279 HA_UNKNOWN = 0,
16280 HA_FLOAT,
16281 HA_DOUBLE,
16282 HA_VECT64,
16283 HA_VECT128
16286 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16287 uint64_t &Members) {
16288 if (auto *ST = dyn_cast<StructType>(Ty)) {
16289 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16290 uint64_t SubMembers = 0;
16291 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16292 return false;
16293 Members += SubMembers;
16295 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16296 uint64_t SubMembers = 0;
16297 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16298 return false;
16299 Members += SubMembers * AT->getNumElements();
16300 } else if (Ty->isFloatTy()) {
16301 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16302 return false;
16303 Members = 1;
16304 Base = HA_FLOAT;
16305 } else if (Ty->isDoubleTy()) {
16306 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16307 return false;
16308 Members = 1;
16309 Base = HA_DOUBLE;
16310 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16311 Members = 1;
16312 switch (Base) {
16313 case HA_FLOAT:
16314 case HA_DOUBLE:
16315 return false;
16316 case HA_VECT64:
16317 return VT->getBitWidth() == 64;
16318 case HA_VECT128:
16319 return VT->getBitWidth() == 128;
16320 case HA_UNKNOWN:
16321 switch (VT->getBitWidth()) {
16322 case 64:
16323 Base = HA_VECT64;
16324 return true;
16325 case 128:
16326 Base = HA_VECT128;
16327 return true;
16328 default:
16329 return false;
16334 return (Members > 0 && Members <= 4);
16337 /// Return the correct alignment for the current calling convention.
16338 unsigned
16339 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16340 DataLayout DL) const {
16341 if (!ArgTy->isVectorTy())
16342 return DL.getABITypeAlignment(ArgTy);
16344 // Avoid over-aligning vector parameters. It would require realigning the
16345 // stack and waste space for no real benefit.
16346 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16349 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16350 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16351 /// passing according to AAPCS rules.
16352 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16353 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16354 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16355 CallingConv::ARM_AAPCS_VFP)
16356 return false;
16358 HABaseType Base = HA_UNKNOWN;
16359 uint64_t Members = 0;
16360 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16361 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16363 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16364 return IsHA || IsIntArray;
16367 unsigned ARMTargetLowering::getExceptionPointerRegister(
16368 const Constant *PersonalityFn) const {
16369 // Platforms which do not use SjLj EH may return values in these registers
16370 // via the personality function.
16371 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16374 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16375 const Constant *PersonalityFn) const {
16376 // Platforms which do not use SjLj EH may return values in these registers
16377 // via the personality function.
16378 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16381 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16382 // Update IsSplitCSR in ARMFunctionInfo.
16383 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16384 AFI->setIsSplitCSR(true);
16387 void ARMTargetLowering::insertCopiesSplitCSR(
16388 MachineBasicBlock *Entry,
16389 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16390 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16391 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16392 if (!IStart)
16393 return;
16395 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16396 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16397 MachineBasicBlock::iterator MBBI = Entry->begin();
16398 for (const MCPhysReg *I = IStart; *I; ++I) {
16399 const TargetRegisterClass *RC = nullptr;
16400 if (ARM::GPRRegClass.contains(*I))
16401 RC = &ARM::GPRRegClass;
16402 else if (ARM::DPRRegClass.contains(*I))
16403 RC = &ARM::DPRRegClass;
16404 else
16405 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16407 unsigned NewVR = MRI->createVirtualRegister(RC);
16408 // Create copy from CSR to a virtual register.
16409 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16410 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16411 // nounwind. If we want to generalize this later, we may need to emit
16412 // CFI pseudo-instructions.
16413 assert(Entry->getParent()->getFunction().hasFnAttribute(
16414 Attribute::NoUnwind) &&
16415 "Function should be nounwind in insertCopiesSplitCSR!");
16416 Entry->addLiveIn(*I);
16417 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16418 .addReg(*I);
16420 // Insert the copy-back instructions right before the terminator.
16421 for (auto *Exit : Exits)
16422 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16423 TII->get(TargetOpcode::COPY), *I)
16424 .addReg(NewVR);
16428 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16429 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16430 TargetLoweringBase::finalizeLowering(MF);