[ARM] Better patterns for fp <> predicate vectors
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blob8fb7ef4847f4709b3e80d4116f21044f0ae93ec3
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::VCMP: return "ARMISD::VCMP";
1519 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1520 case ARMISD::VTST: return "ARMISD::VTST";
1522 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1523 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1524 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1525 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1526 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1527 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1528 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1529 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1530 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1531 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1532 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1533 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1534 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1535 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1536 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1537 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1538 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1539 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1540 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1541 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1542 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1543 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1544 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1545 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1546 case ARMISD::VDUP: return "ARMISD::VDUP";
1547 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1548 case ARMISD::VEXT: return "ARMISD::VEXT";
1549 case ARMISD::VREV64: return "ARMISD::VREV64";
1550 case ARMISD::VREV32: return "ARMISD::VREV32";
1551 case ARMISD::VREV16: return "ARMISD::VREV16";
1552 case ARMISD::VZIP: return "ARMISD::VZIP";
1553 case ARMISD::VUZP: return "ARMISD::VUZP";
1554 case ARMISD::VTRN: return "ARMISD::VTRN";
1555 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1556 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1557 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1558 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1559 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1560 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1561 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1562 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1563 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1564 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1565 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1566 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1567 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1568 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1569 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1570 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1571 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1572 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1573 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1574 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1575 case ARMISD::BFI: return "ARMISD::BFI";
1576 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1577 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1578 case ARMISD::VBSL: return "ARMISD::VBSL";
1579 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1580 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1581 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1582 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1583 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1584 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1585 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1586 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1587 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1588 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1589 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1590 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1591 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1592 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1593 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1594 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1595 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1596 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1597 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1598 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1599 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1600 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1601 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1602 case ARMISD::WLS: return "ARMISD::WLS";
1603 case ARMISD::LE: return "ARMISD::LE";
1604 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1606 return nullptr;
1609 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1610 EVT VT) const {
1611 if (!VT.isVector())
1612 return getPointerTy(DL);
1614 // MVE has a predicate register.
1615 if (Subtarget->hasMVEIntegerOps() &&
1616 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1617 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1618 return VT.changeVectorElementTypeToInteger();
1621 /// getRegClassFor - Return the register class that should be used for the
1622 /// specified value type.
1623 const TargetRegisterClass *
1624 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1625 (void)isDivergent;
1626 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1627 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1628 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1629 // MVE Q registers.
1630 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1631 if (VT == MVT::v4i64)
1632 return &ARM::QQPRRegClass;
1633 if (VT == MVT::v8i64)
1634 return &ARM::QQQQPRRegClass;
1636 return TargetLowering::getRegClassFor(VT);
1639 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1640 // source/dest is aligned and the copy size is large enough. We therefore want
1641 // to align such objects passed to memory intrinsics.
1642 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1643 unsigned &PrefAlign) const {
1644 if (!isa<MemIntrinsic>(CI))
1645 return false;
1646 MinSize = 8;
1647 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1648 // cycle faster than 4-byte aligned LDM.
1649 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1650 return true;
1653 // Create a fast isel object.
1654 FastISel *
1655 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1656 const TargetLibraryInfo *libInfo) const {
1657 return ARM::createFastISel(funcInfo, libInfo);
1660 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1661 unsigned NumVals = N->getNumValues();
1662 if (!NumVals)
1663 return Sched::RegPressure;
1665 for (unsigned i = 0; i != NumVals; ++i) {
1666 EVT VT = N->getValueType(i);
1667 if (VT == MVT::Glue || VT == MVT::Other)
1668 continue;
1669 if (VT.isFloatingPoint() || VT.isVector())
1670 return Sched::ILP;
1673 if (!N->isMachineOpcode())
1674 return Sched::RegPressure;
1676 // Load are scheduled for latency even if there instruction itinerary
1677 // is not available.
1678 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1679 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1681 if (MCID.getNumDefs() == 0)
1682 return Sched::RegPressure;
1683 if (!Itins->isEmpty() &&
1684 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1685 return Sched::ILP;
1687 return Sched::RegPressure;
1690 //===----------------------------------------------------------------------===//
1691 // Lowering Code
1692 //===----------------------------------------------------------------------===//
1694 static bool isSRL16(const SDValue &Op) {
1695 if (Op.getOpcode() != ISD::SRL)
1696 return false;
1697 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1698 return Const->getZExtValue() == 16;
1699 return false;
1702 static bool isSRA16(const SDValue &Op) {
1703 if (Op.getOpcode() != ISD::SRA)
1704 return false;
1705 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1706 return Const->getZExtValue() == 16;
1707 return false;
1710 static bool isSHL16(const SDValue &Op) {
1711 if (Op.getOpcode() != ISD::SHL)
1712 return false;
1713 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1714 return Const->getZExtValue() == 16;
1715 return false;
1718 // Check for a signed 16-bit value. We special case SRA because it makes it
1719 // more simple when also looking for SRAs that aren't sign extending a
1720 // smaller value. Without the check, we'd need to take extra care with
1721 // checking order for some operations.
1722 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1723 if (isSRA16(Op))
1724 return isSHL16(Op.getOperand(0));
1725 return DAG.ComputeNumSignBits(Op) == 17;
1728 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1729 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1730 switch (CC) {
1731 default: llvm_unreachable("Unknown condition code!");
1732 case ISD::SETNE: return ARMCC::NE;
1733 case ISD::SETEQ: return ARMCC::EQ;
1734 case ISD::SETGT: return ARMCC::GT;
1735 case ISD::SETGE: return ARMCC::GE;
1736 case ISD::SETLT: return ARMCC::LT;
1737 case ISD::SETLE: return ARMCC::LE;
1738 case ISD::SETUGT: return ARMCC::HI;
1739 case ISD::SETUGE: return ARMCC::HS;
1740 case ISD::SETULT: return ARMCC::LO;
1741 case ISD::SETULE: return ARMCC::LS;
1745 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1746 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1747 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1748 CondCode2 = ARMCC::AL;
1749 InvalidOnQNaN = true;
1750 switch (CC) {
1751 default: llvm_unreachable("Unknown FP condition!");
1752 case ISD::SETEQ:
1753 case ISD::SETOEQ:
1754 CondCode = ARMCC::EQ;
1755 InvalidOnQNaN = false;
1756 break;
1757 case ISD::SETGT:
1758 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1759 case ISD::SETGE:
1760 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1761 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1762 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1763 case ISD::SETONE:
1764 CondCode = ARMCC::MI;
1765 CondCode2 = ARMCC::GT;
1766 InvalidOnQNaN = false;
1767 break;
1768 case ISD::SETO: CondCode = ARMCC::VC; break;
1769 case ISD::SETUO: CondCode = ARMCC::VS; break;
1770 case ISD::SETUEQ:
1771 CondCode = ARMCC::EQ;
1772 CondCode2 = ARMCC::VS;
1773 InvalidOnQNaN = false;
1774 break;
1775 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1776 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1777 case ISD::SETLT:
1778 case ISD::SETULT: CondCode = ARMCC::LT; break;
1779 case ISD::SETLE:
1780 case ISD::SETULE: CondCode = ARMCC::LE; break;
1781 case ISD::SETNE:
1782 case ISD::SETUNE:
1783 CondCode = ARMCC::NE;
1784 InvalidOnQNaN = false;
1785 break;
1789 //===----------------------------------------------------------------------===//
1790 // Calling Convention Implementation
1791 //===----------------------------------------------------------------------===//
1793 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1794 /// account presence of floating point hardware and calling convention
1795 /// limitations, such as support for variadic functions.
1796 CallingConv::ID
1797 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1798 bool isVarArg) const {
1799 switch (CC) {
1800 default:
1801 report_fatal_error("Unsupported calling convention");
1802 case CallingConv::ARM_AAPCS:
1803 case CallingConv::ARM_APCS:
1804 case CallingConv::GHC:
1805 return CC;
1806 case CallingConv::PreserveMost:
1807 return CallingConv::PreserveMost;
1808 case CallingConv::ARM_AAPCS_VFP:
1809 case CallingConv::Swift:
1810 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1811 case CallingConv::C:
1812 if (!Subtarget->isAAPCS_ABI())
1813 return CallingConv::ARM_APCS;
1814 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1815 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1816 !isVarArg)
1817 return CallingConv::ARM_AAPCS_VFP;
1818 else
1819 return CallingConv::ARM_AAPCS;
1820 case CallingConv::Fast:
1821 case CallingConv::CXX_FAST_TLS:
1822 if (!Subtarget->isAAPCS_ABI()) {
1823 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1824 return CallingConv::Fast;
1825 return CallingConv::ARM_APCS;
1826 } else if (Subtarget->hasVFP2Base() &&
1827 !Subtarget->isThumb1Only() && !isVarArg)
1828 return CallingConv::ARM_AAPCS_VFP;
1829 else
1830 return CallingConv::ARM_AAPCS;
1834 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1835 bool isVarArg) const {
1836 return CCAssignFnForNode(CC, false, isVarArg);
1839 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1840 bool isVarArg) const {
1841 return CCAssignFnForNode(CC, true, isVarArg);
1844 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1845 /// CallingConvention.
1846 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1847 bool Return,
1848 bool isVarArg) const {
1849 switch (getEffectiveCallingConv(CC, isVarArg)) {
1850 default:
1851 report_fatal_error("Unsupported calling convention");
1852 case CallingConv::ARM_APCS:
1853 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1854 case CallingConv::ARM_AAPCS:
1855 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1856 case CallingConv::ARM_AAPCS_VFP:
1857 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1858 case CallingConv::Fast:
1859 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1860 case CallingConv::GHC:
1861 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1862 case CallingConv::PreserveMost:
1863 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1867 /// LowerCallResult - Lower the result values of a call into the
1868 /// appropriate copies out of appropriate physical registers.
1869 SDValue ARMTargetLowering::LowerCallResult(
1870 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1871 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1872 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1873 SDValue ThisVal) const {
1874 // Assign locations to each value returned by this call.
1875 SmallVector<CCValAssign, 16> RVLocs;
1876 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1877 *DAG.getContext());
1878 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1880 // Copy all of the result registers out of their specified physreg.
1881 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1882 CCValAssign VA = RVLocs[i];
1884 // Pass 'this' value directly from the argument to return value, to avoid
1885 // reg unit interference
1886 if (i == 0 && isThisReturn) {
1887 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1888 "unexpected return calling convention register assignment");
1889 InVals.push_back(ThisVal);
1890 continue;
1893 SDValue Val;
1894 if (VA.needsCustom()) {
1895 // Handle f64 or half of a v2f64.
1896 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1897 InFlag);
1898 Chain = Lo.getValue(1);
1899 InFlag = Lo.getValue(2);
1900 VA = RVLocs[++i]; // skip ahead to next loc
1901 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1902 InFlag);
1903 Chain = Hi.getValue(1);
1904 InFlag = Hi.getValue(2);
1905 if (!Subtarget->isLittle())
1906 std::swap (Lo, Hi);
1907 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1909 if (VA.getLocVT() == MVT::v2f64) {
1910 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1911 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1912 DAG.getConstant(0, dl, MVT::i32));
1914 VA = RVLocs[++i]; // skip ahead to next loc
1915 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1916 Chain = Lo.getValue(1);
1917 InFlag = Lo.getValue(2);
1918 VA = RVLocs[++i]; // skip ahead to next loc
1919 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1920 Chain = Hi.getValue(1);
1921 InFlag = Hi.getValue(2);
1922 if (!Subtarget->isLittle())
1923 std::swap (Lo, Hi);
1924 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1925 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1926 DAG.getConstant(1, dl, MVT::i32));
1928 } else {
1929 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1930 InFlag);
1931 Chain = Val.getValue(1);
1932 InFlag = Val.getValue(2);
1935 switch (VA.getLocInfo()) {
1936 default: llvm_unreachable("Unknown loc info!");
1937 case CCValAssign::Full: break;
1938 case CCValAssign::BCvt:
1939 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1940 break;
1943 InVals.push_back(Val);
1946 return Chain;
1949 /// LowerMemOpCallTo - Store the argument to the stack.
1950 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1951 SDValue Arg, const SDLoc &dl,
1952 SelectionDAG &DAG,
1953 const CCValAssign &VA,
1954 ISD::ArgFlagsTy Flags) const {
1955 unsigned LocMemOffset = VA.getLocMemOffset();
1956 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1957 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1958 StackPtr, PtrOff);
1959 return DAG.getStore(
1960 Chain, dl, Arg, PtrOff,
1961 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1964 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1965 SDValue Chain, SDValue &Arg,
1966 RegsToPassVector &RegsToPass,
1967 CCValAssign &VA, CCValAssign &NextVA,
1968 SDValue &StackPtr,
1969 SmallVectorImpl<SDValue> &MemOpChains,
1970 ISD::ArgFlagsTy Flags) const {
1971 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1972 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1973 unsigned id = Subtarget->isLittle() ? 0 : 1;
1974 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1976 if (NextVA.isRegLoc())
1977 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1978 else {
1979 assert(NextVA.isMemLoc());
1980 if (!StackPtr.getNode())
1981 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1982 getPointerTy(DAG.getDataLayout()));
1984 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1985 dl, DAG, NextVA,
1986 Flags));
1990 /// LowerCall - Lowering a call into a callseq_start <-
1991 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1992 /// nodes.
1993 SDValue
1994 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1995 SmallVectorImpl<SDValue> &InVals) const {
1996 SelectionDAG &DAG = CLI.DAG;
1997 SDLoc &dl = CLI.DL;
1998 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1999 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2000 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2001 SDValue Chain = CLI.Chain;
2002 SDValue Callee = CLI.Callee;
2003 bool &isTailCall = CLI.IsTailCall;
2004 CallingConv::ID CallConv = CLI.CallConv;
2005 bool doesNotRet = CLI.DoesNotReturn;
2006 bool isVarArg = CLI.IsVarArg;
2008 MachineFunction &MF = DAG.getMachineFunction();
2009 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2010 bool isThisReturn = false;
2011 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2012 bool PreferIndirect = false;
2014 // Disable tail calls if they're not supported.
2015 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2016 isTailCall = false;
2018 if (isa<GlobalAddressSDNode>(Callee)) {
2019 // If we're optimizing for minimum size and the function is called three or
2020 // more times in this block, we can improve codesize by calling indirectly
2021 // as BLXr has a 16-bit encoding.
2022 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2023 if (CLI.CS) {
2024 auto *BB = CLI.CS.getParent();
2025 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2026 count_if(GV->users(), [&BB](const User *U) {
2027 return isa<Instruction>(U) &&
2028 cast<Instruction>(U)->getParent() == BB;
2029 }) > 2;
2032 if (isTailCall) {
2033 // Check if it's really possible to do a tail call.
2034 isTailCall = IsEligibleForTailCallOptimization(
2035 Callee, CallConv, isVarArg, isStructRet,
2036 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2037 PreferIndirect);
2038 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2039 report_fatal_error("failed to perform tail call elimination on a call "
2040 "site marked musttail");
2041 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2042 // detected sibcalls.
2043 if (isTailCall)
2044 ++NumTailCalls;
2047 // Analyze operands of the call, assigning locations to each operand.
2048 SmallVector<CCValAssign, 16> ArgLocs;
2049 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2050 *DAG.getContext());
2051 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2053 // Get a count of how many bytes are to be pushed on the stack.
2054 unsigned NumBytes = CCInfo.getNextStackOffset();
2056 if (isTailCall) {
2057 // For tail calls, memory operands are available in our caller's stack.
2058 NumBytes = 0;
2059 } else {
2060 // Adjust the stack pointer for the new arguments...
2061 // These operations are automatically eliminated by the prolog/epilog pass
2062 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2065 SDValue StackPtr =
2066 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2068 RegsToPassVector RegsToPass;
2069 SmallVector<SDValue, 8> MemOpChains;
2071 // Walk the register/memloc assignments, inserting copies/loads. In the case
2072 // of tail call optimization, arguments are handled later.
2073 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2074 i != e;
2075 ++i, ++realArgIdx) {
2076 CCValAssign &VA = ArgLocs[i];
2077 SDValue Arg = OutVals[realArgIdx];
2078 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2079 bool isByVal = Flags.isByVal();
2081 // Promote the value if needed.
2082 switch (VA.getLocInfo()) {
2083 default: llvm_unreachable("Unknown loc info!");
2084 case CCValAssign::Full: break;
2085 case CCValAssign::SExt:
2086 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2087 break;
2088 case CCValAssign::ZExt:
2089 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2090 break;
2091 case CCValAssign::AExt:
2092 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2093 break;
2094 case CCValAssign::BCvt:
2095 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2096 break;
2099 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2100 if (VA.needsCustom()) {
2101 if (VA.getLocVT() == MVT::v2f64) {
2102 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2103 DAG.getConstant(0, dl, MVT::i32));
2104 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2105 DAG.getConstant(1, dl, MVT::i32));
2107 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2108 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2110 VA = ArgLocs[++i]; // skip ahead to next loc
2111 if (VA.isRegLoc()) {
2112 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2113 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2114 } else {
2115 assert(VA.isMemLoc());
2117 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2118 dl, DAG, VA, Flags));
2120 } else {
2121 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2122 StackPtr, MemOpChains, Flags);
2124 } else if (VA.isRegLoc()) {
2125 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2126 Outs[0].VT == MVT::i32) {
2127 assert(VA.getLocVT() == MVT::i32 &&
2128 "unexpected calling convention register assignment");
2129 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2130 "unexpected use of 'returned'");
2131 isThisReturn = true;
2133 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2134 } else if (isByVal) {
2135 assert(VA.isMemLoc());
2136 unsigned offset = 0;
2138 // True if this byval aggregate will be split between registers
2139 // and memory.
2140 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2141 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2143 if (CurByValIdx < ByValArgsCount) {
2145 unsigned RegBegin, RegEnd;
2146 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2148 EVT PtrVT =
2149 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2150 unsigned int i, j;
2151 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2152 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2153 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2154 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2155 MachinePointerInfo(),
2156 DAG.InferPtrAlignment(AddArg));
2157 MemOpChains.push_back(Load.getValue(1));
2158 RegsToPass.push_back(std::make_pair(j, Load));
2161 // If parameter size outsides register area, "offset" value
2162 // helps us to calculate stack slot for remained part properly.
2163 offset = RegEnd - RegBegin;
2165 CCInfo.nextInRegsParam();
2168 if (Flags.getByValSize() > 4*offset) {
2169 auto PtrVT = getPointerTy(DAG.getDataLayout());
2170 unsigned LocMemOffset = VA.getLocMemOffset();
2171 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2172 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2173 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2174 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2175 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2176 MVT::i32);
2177 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2178 MVT::i32);
2180 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2181 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2182 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2183 Ops));
2185 } else if (!isTailCall) {
2186 assert(VA.isMemLoc());
2188 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2189 dl, DAG, VA, Flags));
2193 if (!MemOpChains.empty())
2194 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2196 // Build a sequence of copy-to-reg nodes chained together with token chain
2197 // and flag operands which copy the outgoing args into the appropriate regs.
2198 SDValue InFlag;
2199 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2200 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2201 RegsToPass[i].second, InFlag);
2202 InFlag = Chain.getValue(1);
2205 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2206 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2207 // node so that legalize doesn't hack it.
2208 bool isDirect = false;
2210 const TargetMachine &TM = getTargetMachine();
2211 const Module *Mod = MF.getFunction().getParent();
2212 const GlobalValue *GV = nullptr;
2213 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2214 GV = G->getGlobal();
2215 bool isStub =
2216 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2218 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2219 bool isLocalARMFunc = false;
2220 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2221 auto PtrVt = getPointerTy(DAG.getDataLayout());
2223 if (Subtarget->genLongCalls()) {
2224 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2225 "long-calls codegen is not position independent!");
2226 // Handle a global address or an external symbol. If it's not one of
2227 // those, the target's already in a register, so we don't need to do
2228 // anything extra.
2229 if (isa<GlobalAddressSDNode>(Callee)) {
2230 // Create a constant pool entry for the callee address
2231 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2232 ARMConstantPoolValue *CPV =
2233 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2235 // Get the address of the callee into a register
2236 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2237 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2238 Callee = DAG.getLoad(
2239 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2240 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2241 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2242 const char *Sym = S->getSymbol();
2244 // Create a constant pool entry for the callee address
2245 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2246 ARMConstantPoolValue *CPV =
2247 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2248 ARMPCLabelIndex, 0);
2249 // Get the address of the callee into a register
2250 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2251 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2252 Callee = DAG.getLoad(
2253 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2254 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2256 } else if (isa<GlobalAddressSDNode>(Callee)) {
2257 if (!PreferIndirect) {
2258 isDirect = true;
2259 bool isDef = GV->isStrongDefinitionForLinker();
2261 // ARM call to a local ARM function is predicable.
2262 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2263 // tBX takes a register source operand.
2264 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2265 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2266 Callee = DAG.getNode(
2267 ARMISD::WrapperPIC, dl, PtrVt,
2268 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2269 Callee = DAG.getLoad(
2270 PtrVt, dl, DAG.getEntryNode(), Callee,
2271 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2272 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2273 MachineMemOperand::MOInvariant);
2274 } else if (Subtarget->isTargetCOFF()) {
2275 assert(Subtarget->isTargetWindows() &&
2276 "Windows is the only supported COFF target");
2277 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2278 ? ARMII::MO_DLLIMPORT
2279 : ARMII::MO_NO_FLAG;
2280 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2281 TargetFlags);
2282 if (GV->hasDLLImportStorageClass())
2283 Callee =
2284 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2285 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2286 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2287 } else {
2288 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2291 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2292 isDirect = true;
2293 // tBX takes a register source operand.
2294 const char *Sym = S->getSymbol();
2295 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2296 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2297 ARMConstantPoolValue *CPV =
2298 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2299 ARMPCLabelIndex, 4);
2300 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2301 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2302 Callee = DAG.getLoad(
2303 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2304 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2305 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2306 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2307 } else {
2308 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2312 // FIXME: handle tail calls differently.
2313 unsigned CallOpc;
2314 if (Subtarget->isThumb()) {
2315 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2316 CallOpc = ARMISD::CALL_NOLINK;
2317 else
2318 CallOpc = ARMISD::CALL;
2319 } else {
2320 if (!isDirect && !Subtarget->hasV5TOps())
2321 CallOpc = ARMISD::CALL_NOLINK;
2322 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2323 // Emit regular call when code size is the priority
2324 !Subtarget->hasMinSize())
2325 // "mov lr, pc; b _foo" to avoid confusing the RSP
2326 CallOpc = ARMISD::CALL_NOLINK;
2327 else
2328 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2331 std::vector<SDValue> Ops;
2332 Ops.push_back(Chain);
2333 Ops.push_back(Callee);
2335 // Add argument registers to the end of the list so that they are known live
2336 // into the call.
2337 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2338 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2339 RegsToPass[i].second.getValueType()));
2341 // Add a register mask operand representing the call-preserved registers.
2342 if (!isTailCall) {
2343 const uint32_t *Mask;
2344 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2345 if (isThisReturn) {
2346 // For 'this' returns, use the R0-preserving mask if applicable
2347 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2348 if (!Mask) {
2349 // Set isThisReturn to false if the calling convention is not one that
2350 // allows 'returned' to be modeled in this way, so LowerCallResult does
2351 // not try to pass 'this' straight through
2352 isThisReturn = false;
2353 Mask = ARI->getCallPreservedMask(MF, CallConv);
2355 } else
2356 Mask = ARI->getCallPreservedMask(MF, CallConv);
2358 assert(Mask && "Missing call preserved mask for calling convention");
2359 Ops.push_back(DAG.getRegisterMask(Mask));
2362 if (InFlag.getNode())
2363 Ops.push_back(InFlag);
2365 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2366 if (isTailCall) {
2367 MF.getFrameInfo().setHasTailCall();
2368 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2371 // Returns a chain and a flag for retval copy to use.
2372 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2373 InFlag = Chain.getValue(1);
2375 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2376 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2377 if (!Ins.empty())
2378 InFlag = Chain.getValue(1);
2380 // Handle result values, copying them out of physregs into vregs that we
2381 // return.
2382 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2383 InVals, isThisReturn,
2384 isThisReturn ? OutVals[0] : SDValue());
2387 /// HandleByVal - Every parameter *after* a byval parameter is passed
2388 /// on the stack. Remember the next parameter register to allocate,
2389 /// and then confiscate the rest of the parameter registers to insure
2390 /// this.
2391 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2392 unsigned Align) const {
2393 // Byval (as with any stack) slots are always at least 4 byte aligned.
2394 Align = std::max(Align, 4U);
2396 unsigned Reg = State->AllocateReg(GPRArgRegs);
2397 if (!Reg)
2398 return;
2400 unsigned AlignInRegs = Align / 4;
2401 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2402 for (unsigned i = 0; i < Waste; ++i)
2403 Reg = State->AllocateReg(GPRArgRegs);
2405 if (!Reg)
2406 return;
2408 unsigned Excess = 4 * (ARM::R4 - Reg);
2410 // Special case when NSAA != SP and parameter size greater than size of
2411 // all remained GPR regs. In that case we can't split parameter, we must
2412 // send it to stack. We also must set NCRN to R4, so waste all
2413 // remained registers.
2414 const unsigned NSAAOffset = State->getNextStackOffset();
2415 if (NSAAOffset != 0 && Size > Excess) {
2416 while (State->AllocateReg(GPRArgRegs))
2418 return;
2421 // First register for byval parameter is the first register that wasn't
2422 // allocated before this method call, so it would be "reg".
2423 // If parameter is small enough to be saved in range [reg, r4), then
2424 // the end (first after last) register would be reg + param-size-in-regs,
2425 // else parameter would be splitted between registers and stack,
2426 // end register would be r4 in this case.
2427 unsigned ByValRegBegin = Reg;
2428 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2429 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2430 // Note, first register is allocated in the beginning of function already,
2431 // allocate remained amount of registers we need.
2432 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2433 State->AllocateReg(GPRArgRegs);
2434 // A byval parameter that is split between registers and memory needs its
2435 // size truncated here.
2436 // In the case where the entire structure fits in registers, we set the
2437 // size in memory to zero.
2438 Size = std::max<int>(Size - Excess, 0);
2441 /// MatchingStackOffset - Return true if the given stack call argument is
2442 /// already available in the same position (relatively) of the caller's
2443 /// incoming argument stack.
2444 static
2445 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2446 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2447 const TargetInstrInfo *TII) {
2448 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2449 int FI = std::numeric_limits<int>::max();
2450 if (Arg.getOpcode() == ISD::CopyFromReg) {
2451 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2452 if (!TargetRegisterInfo::isVirtualRegister(VR))
2453 return false;
2454 MachineInstr *Def = MRI->getVRegDef(VR);
2455 if (!Def)
2456 return false;
2457 if (!Flags.isByVal()) {
2458 if (!TII->isLoadFromStackSlot(*Def, FI))
2459 return false;
2460 } else {
2461 return false;
2463 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2464 if (Flags.isByVal())
2465 // ByVal argument is passed in as a pointer but it's now being
2466 // dereferenced. e.g.
2467 // define @foo(%struct.X* %A) {
2468 // tail call @bar(%struct.X* byval %A)
2469 // }
2470 return false;
2471 SDValue Ptr = Ld->getBasePtr();
2472 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2473 if (!FINode)
2474 return false;
2475 FI = FINode->getIndex();
2476 } else
2477 return false;
2479 assert(FI != std::numeric_limits<int>::max());
2480 if (!MFI.isFixedObjectIndex(FI))
2481 return false;
2482 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2485 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2486 /// for tail call optimization. Targets which want to do tail call
2487 /// optimization should implement this function.
2488 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2489 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2490 bool isCalleeStructRet, bool isCallerStructRet,
2491 const SmallVectorImpl<ISD::OutputArg> &Outs,
2492 const SmallVectorImpl<SDValue> &OutVals,
2493 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2494 const bool isIndirect) const {
2495 MachineFunction &MF = DAG.getMachineFunction();
2496 const Function &CallerF = MF.getFunction();
2497 CallingConv::ID CallerCC = CallerF.getCallingConv();
2499 assert(Subtarget->supportsTailCall());
2501 // Indirect tail calls cannot be optimized for Thumb1 if the args
2502 // to the call take up r0-r3. The reason is that there are no legal registers
2503 // left to hold the pointer to the function to be called.
2504 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2505 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2506 return false;
2508 // Look for obvious safe cases to perform tail call optimization that do not
2509 // require ABI changes. This is what gcc calls sibcall.
2511 // Exception-handling functions need a special set of instructions to indicate
2512 // a return to the hardware. Tail-calling another function would probably
2513 // break this.
2514 if (CallerF.hasFnAttribute("interrupt"))
2515 return false;
2517 // Also avoid sibcall optimization if either caller or callee uses struct
2518 // return semantics.
2519 if (isCalleeStructRet || isCallerStructRet)
2520 return false;
2522 // Externally-defined functions with weak linkage should not be
2523 // tail-called on ARM when the OS does not support dynamic
2524 // pre-emption of symbols, as the AAELF spec requires normal calls
2525 // to undefined weak functions to be replaced with a NOP or jump to the
2526 // next instruction. The behaviour of branch instructions in this
2527 // situation (as used for tail calls) is implementation-defined, so we
2528 // cannot rely on the linker replacing the tail call with a return.
2529 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2530 const GlobalValue *GV = G->getGlobal();
2531 const Triple &TT = getTargetMachine().getTargetTriple();
2532 if (GV->hasExternalWeakLinkage() &&
2533 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2534 return false;
2537 // Check that the call results are passed in the same way.
2538 LLVMContext &C = *DAG.getContext();
2539 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2540 CCAssignFnForReturn(CalleeCC, isVarArg),
2541 CCAssignFnForReturn(CallerCC, isVarArg)))
2542 return false;
2543 // The callee has to preserve all registers the caller needs to preserve.
2544 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2545 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2546 if (CalleeCC != CallerCC) {
2547 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2548 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2549 return false;
2552 // If Caller's vararg or byval argument has been split between registers and
2553 // stack, do not perform tail call, since part of the argument is in caller's
2554 // local frame.
2555 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2556 if (AFI_Caller->getArgRegsSaveSize())
2557 return false;
2559 // If the callee takes no arguments then go on to check the results of the
2560 // call.
2561 if (!Outs.empty()) {
2562 // Check if stack adjustment is needed. For now, do not do this if any
2563 // argument is passed on the stack.
2564 SmallVector<CCValAssign, 16> ArgLocs;
2565 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2566 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2567 if (CCInfo.getNextStackOffset()) {
2568 // Check if the arguments are already laid out in the right way as
2569 // the caller's fixed stack objects.
2570 MachineFrameInfo &MFI = MF.getFrameInfo();
2571 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2572 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2573 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2574 i != e;
2575 ++i, ++realArgIdx) {
2576 CCValAssign &VA = ArgLocs[i];
2577 EVT RegVT = VA.getLocVT();
2578 SDValue Arg = OutVals[realArgIdx];
2579 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2580 if (VA.getLocInfo() == CCValAssign::Indirect)
2581 return false;
2582 if (VA.needsCustom()) {
2583 // f64 and vector types are split into multiple registers or
2584 // register/stack-slot combinations. The types will not match
2585 // the registers; give up on memory f64 refs until we figure
2586 // out what to do about this.
2587 if (!VA.isRegLoc())
2588 return false;
2589 if (!ArgLocs[++i].isRegLoc())
2590 return false;
2591 if (RegVT == MVT::v2f64) {
2592 if (!ArgLocs[++i].isRegLoc())
2593 return false;
2594 if (!ArgLocs[++i].isRegLoc())
2595 return false;
2597 } else if (!VA.isRegLoc()) {
2598 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2599 MFI, MRI, TII))
2600 return false;
2605 const MachineRegisterInfo &MRI = MF.getRegInfo();
2606 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2607 return false;
2610 return true;
2613 bool
2614 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2615 MachineFunction &MF, bool isVarArg,
2616 const SmallVectorImpl<ISD::OutputArg> &Outs,
2617 LLVMContext &Context) const {
2618 SmallVector<CCValAssign, 16> RVLocs;
2619 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2620 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2623 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2624 const SDLoc &DL, SelectionDAG &DAG) {
2625 const MachineFunction &MF = DAG.getMachineFunction();
2626 const Function &F = MF.getFunction();
2628 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2630 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2631 // version of the "preferred return address". These offsets affect the return
2632 // instruction if this is a return from PL1 without hypervisor extensions.
2633 // IRQ/FIQ: +4 "subs pc, lr, #4"
2634 // SWI: 0 "subs pc, lr, #0"
2635 // ABORT: +4 "subs pc, lr, #4"
2636 // UNDEF: +4/+2 "subs pc, lr, #0"
2637 // UNDEF varies depending on where the exception came from ARM or Thumb
2638 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2640 int64_t LROffset;
2641 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2642 IntKind == "ABORT")
2643 LROffset = 4;
2644 else if (IntKind == "SWI" || IntKind == "UNDEF")
2645 LROffset = 0;
2646 else
2647 report_fatal_error("Unsupported interrupt attribute. If present, value "
2648 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2650 RetOps.insert(RetOps.begin() + 1,
2651 DAG.getConstant(LROffset, DL, MVT::i32, false));
2653 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2656 SDValue
2657 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2658 bool isVarArg,
2659 const SmallVectorImpl<ISD::OutputArg> &Outs,
2660 const SmallVectorImpl<SDValue> &OutVals,
2661 const SDLoc &dl, SelectionDAG &DAG) const {
2662 // CCValAssign - represent the assignment of the return value to a location.
2663 SmallVector<CCValAssign, 16> RVLocs;
2665 // CCState - Info about the registers and stack slots.
2666 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2667 *DAG.getContext());
2669 // Analyze outgoing return values.
2670 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2672 SDValue Flag;
2673 SmallVector<SDValue, 4> RetOps;
2674 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2675 bool isLittleEndian = Subtarget->isLittle();
2677 MachineFunction &MF = DAG.getMachineFunction();
2678 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2679 AFI->setReturnRegsCount(RVLocs.size());
2681 // Copy the result values into the output registers.
2682 for (unsigned i = 0, realRVLocIdx = 0;
2683 i != RVLocs.size();
2684 ++i, ++realRVLocIdx) {
2685 CCValAssign &VA = RVLocs[i];
2686 assert(VA.isRegLoc() && "Can only return in registers!");
2688 SDValue Arg = OutVals[realRVLocIdx];
2689 bool ReturnF16 = false;
2691 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2692 // Half-precision return values can be returned like this:
2694 // t11 f16 = fadd ...
2695 // t12: i16 = bitcast t11
2696 // t13: i32 = zero_extend t12
2697 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2699 // to avoid code generation for bitcasts, we simply set Arg to the node
2700 // that produces the f16 value, t11 in this case.
2702 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2703 SDValue ZE = Arg.getOperand(0);
2704 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2705 SDValue BC = ZE.getOperand(0);
2706 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2707 Arg = BC.getOperand(0);
2708 ReturnF16 = true;
2714 switch (VA.getLocInfo()) {
2715 default: llvm_unreachable("Unknown loc info!");
2716 case CCValAssign::Full: break;
2717 case CCValAssign::BCvt:
2718 if (!ReturnF16)
2719 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2720 break;
2723 if (VA.needsCustom()) {
2724 if (VA.getLocVT() == MVT::v2f64) {
2725 // Extract the first half and return it in two registers.
2726 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2727 DAG.getConstant(0, dl, MVT::i32));
2728 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2729 DAG.getVTList(MVT::i32, MVT::i32), Half);
2731 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2732 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2733 Flag);
2734 Flag = Chain.getValue(1);
2735 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2736 VA = RVLocs[++i]; // skip ahead to next loc
2737 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2738 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2739 Flag);
2740 Flag = Chain.getValue(1);
2741 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2742 VA = RVLocs[++i]; // skip ahead to next loc
2744 // Extract the 2nd half and fall through to handle it as an f64 value.
2745 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2746 DAG.getConstant(1, dl, MVT::i32));
2748 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2749 // available.
2750 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2751 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2752 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2753 fmrrd.getValue(isLittleEndian ? 0 : 1),
2754 Flag);
2755 Flag = Chain.getValue(1);
2756 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2757 VA = RVLocs[++i]; // skip ahead to next loc
2758 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2759 fmrrd.getValue(isLittleEndian ? 1 : 0),
2760 Flag);
2761 } else
2762 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2764 // Guarantee that all emitted copies are
2765 // stuck together, avoiding something bad.
2766 Flag = Chain.getValue(1);
2767 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2768 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2770 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2771 const MCPhysReg *I =
2772 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2773 if (I) {
2774 for (; *I; ++I) {
2775 if (ARM::GPRRegClass.contains(*I))
2776 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2777 else if (ARM::DPRRegClass.contains(*I))
2778 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2779 else
2780 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2784 // Update chain and glue.
2785 RetOps[0] = Chain;
2786 if (Flag.getNode())
2787 RetOps.push_back(Flag);
2789 // CPUs which aren't M-class use a special sequence to return from
2790 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2791 // though we use "subs pc, lr, #N").
2793 // M-class CPUs actually use a normal return sequence with a special
2794 // (hardware-provided) value in LR, so the normal code path works.
2795 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2796 !Subtarget->isMClass()) {
2797 if (Subtarget->isThumb1Only())
2798 report_fatal_error("interrupt attribute is not supported in Thumb1");
2799 return LowerInterruptReturn(RetOps, dl, DAG);
2802 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2805 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2806 if (N->getNumValues() != 1)
2807 return false;
2808 if (!N->hasNUsesOfValue(1, 0))
2809 return false;
2811 SDValue TCChain = Chain;
2812 SDNode *Copy = *N->use_begin();
2813 if (Copy->getOpcode() == ISD::CopyToReg) {
2814 // If the copy has a glue operand, we conservatively assume it isn't safe to
2815 // perform a tail call.
2816 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2817 return false;
2818 TCChain = Copy->getOperand(0);
2819 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2820 SDNode *VMov = Copy;
2821 // f64 returned in a pair of GPRs.
2822 SmallPtrSet<SDNode*, 2> Copies;
2823 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2824 UI != UE; ++UI) {
2825 if (UI->getOpcode() != ISD::CopyToReg)
2826 return false;
2827 Copies.insert(*UI);
2829 if (Copies.size() > 2)
2830 return false;
2832 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2833 UI != UE; ++UI) {
2834 SDValue UseChain = UI->getOperand(0);
2835 if (Copies.count(UseChain.getNode()))
2836 // Second CopyToReg
2837 Copy = *UI;
2838 else {
2839 // We are at the top of this chain.
2840 // If the copy has a glue operand, we conservatively assume it
2841 // isn't safe to perform a tail call.
2842 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2843 return false;
2844 // First CopyToReg
2845 TCChain = UseChain;
2848 } else if (Copy->getOpcode() == ISD::BITCAST) {
2849 // f32 returned in a single GPR.
2850 if (!Copy->hasOneUse())
2851 return false;
2852 Copy = *Copy->use_begin();
2853 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2854 return false;
2855 // If the copy has a glue operand, we conservatively assume it isn't safe to
2856 // perform a tail call.
2857 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2858 return false;
2859 TCChain = Copy->getOperand(0);
2860 } else {
2861 return false;
2864 bool HasRet = false;
2865 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2866 UI != UE; ++UI) {
2867 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2868 UI->getOpcode() != ARMISD::INTRET_FLAG)
2869 return false;
2870 HasRet = true;
2873 if (!HasRet)
2874 return false;
2876 Chain = TCChain;
2877 return true;
2880 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2881 if (!Subtarget->supportsTailCall())
2882 return false;
2884 auto Attr =
2885 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2886 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2887 return false;
2889 return true;
2892 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2893 // and pass the lower and high parts through.
2894 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2895 SDLoc DL(Op);
2896 SDValue WriteValue = Op->getOperand(2);
2898 // This function is only supposed to be called for i64 type argument.
2899 assert(WriteValue.getValueType() == MVT::i64
2900 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2902 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2903 DAG.getConstant(0, DL, MVT::i32));
2904 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2905 DAG.getConstant(1, DL, MVT::i32));
2906 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2907 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2910 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2911 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2912 // one of the above mentioned nodes. It has to be wrapped because otherwise
2913 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2914 // be used to form addressing mode. These wrapped nodes will be selected
2915 // into MOVi.
2916 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2917 SelectionDAG &DAG) const {
2918 EVT PtrVT = Op.getValueType();
2919 // FIXME there is no actual debug info here
2920 SDLoc dl(Op);
2921 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2922 SDValue Res;
2924 // When generating execute-only code Constant Pools must be promoted to the
2925 // global data section. It's a bit ugly that we can't share them across basic
2926 // blocks, but this way we guarantee that execute-only behaves correct with
2927 // position-independent addressing modes.
2928 if (Subtarget->genExecuteOnly()) {
2929 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2930 auto T = const_cast<Type*>(CP->getType());
2931 auto C = const_cast<Constant*>(CP->getConstVal());
2932 auto M = const_cast<Module*>(DAG.getMachineFunction().
2933 getFunction().getParent());
2934 auto GV = new GlobalVariable(
2935 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2936 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2937 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2938 Twine(AFI->createPICLabelUId())
2940 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2941 dl, PtrVT);
2942 return LowerGlobalAddress(GA, DAG);
2945 if (CP->isMachineConstantPoolEntry())
2946 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2947 CP->getAlignment());
2948 else
2949 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2950 CP->getAlignment());
2951 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2954 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2955 return MachineJumpTableInfo::EK_Inline;
2958 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2959 SelectionDAG &DAG) const {
2960 MachineFunction &MF = DAG.getMachineFunction();
2961 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2962 unsigned ARMPCLabelIndex = 0;
2963 SDLoc DL(Op);
2964 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2965 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2966 SDValue CPAddr;
2967 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2968 if (!IsPositionIndependent) {
2969 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2970 } else {
2971 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2972 ARMPCLabelIndex = AFI->createPICLabelUId();
2973 ARMConstantPoolValue *CPV =
2974 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2975 ARMCP::CPBlockAddress, PCAdj);
2976 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2978 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2979 SDValue Result = DAG.getLoad(
2980 PtrVT, DL, DAG.getEntryNode(), CPAddr,
2981 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2982 if (!IsPositionIndependent)
2983 return Result;
2984 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2985 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2988 /// Convert a TLS address reference into the correct sequence of loads
2989 /// and calls to compute the variable's address for Darwin, and return an
2990 /// SDValue containing the final node.
2992 /// Darwin only has one TLS scheme which must be capable of dealing with the
2993 /// fully general situation, in the worst case. This means:
2994 /// + "extern __thread" declaration.
2995 /// + Defined in a possibly unknown dynamic library.
2997 /// The general system is that each __thread variable has a [3 x i32] descriptor
2998 /// which contains information used by the runtime to calculate the address. The
2999 /// only part of this the compiler needs to know about is the first word, which
3000 /// contains a function pointer that must be called with the address of the
3001 /// entire descriptor in "r0".
3003 /// Since this descriptor may be in a different unit, in general access must
3004 /// proceed along the usual ARM rules. A common sequence to produce is:
3006 /// movw rT1, :lower16:_var$non_lazy_ptr
3007 /// movt rT1, :upper16:_var$non_lazy_ptr
3008 /// ldr r0, [rT1]
3009 /// ldr rT2, [r0]
3010 /// blx rT2
3011 /// [...address now in r0...]
3012 SDValue
3013 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3014 SelectionDAG &DAG) const {
3015 assert(Subtarget->isTargetDarwin() &&
3016 "This function expects a Darwin target");
3017 SDLoc DL(Op);
3019 // First step is to get the address of the actua global symbol. This is where
3020 // the TLS descriptor lives.
3021 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3023 // The first entry in the descriptor is a function pointer that we must call
3024 // to obtain the address of the variable.
3025 SDValue Chain = DAG.getEntryNode();
3026 SDValue FuncTLVGet = DAG.getLoad(
3027 MVT::i32, DL, Chain, DescAddr,
3028 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3029 /* Alignment = */ 4,
3030 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3031 MachineMemOperand::MOInvariant);
3032 Chain = FuncTLVGet.getValue(1);
3034 MachineFunction &F = DAG.getMachineFunction();
3035 MachineFrameInfo &MFI = F.getFrameInfo();
3036 MFI.setAdjustsStack(true);
3038 // TLS calls preserve all registers except those that absolutely must be
3039 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3040 // silly).
3041 auto TRI =
3042 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3043 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3044 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3046 // Finally, we can make the call. This is just a degenerate version of a
3047 // normal AArch64 call node: r0 takes the address of the descriptor, and
3048 // returns the address of the variable in this thread.
3049 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3050 Chain =
3051 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3052 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3053 DAG.getRegisterMask(Mask), Chain.getValue(1));
3054 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3057 SDValue
3058 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3059 SelectionDAG &DAG) const {
3060 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3062 SDValue Chain = DAG.getEntryNode();
3063 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3064 SDLoc DL(Op);
3066 // Load the current TEB (thread environment block)
3067 SDValue Ops[] = {Chain,
3068 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3069 DAG.getConstant(15, DL, MVT::i32),
3070 DAG.getConstant(0, DL, MVT::i32),
3071 DAG.getConstant(13, DL, MVT::i32),
3072 DAG.getConstant(0, DL, MVT::i32),
3073 DAG.getConstant(2, DL, MVT::i32)};
3074 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3075 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3077 SDValue TEB = CurrentTEB.getValue(0);
3078 Chain = CurrentTEB.getValue(1);
3080 // Load the ThreadLocalStoragePointer from the TEB
3081 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3082 SDValue TLSArray =
3083 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3084 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3086 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3087 // offset into the TLSArray.
3089 // Load the TLS index from the C runtime
3090 SDValue TLSIndex =
3091 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3092 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3093 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3095 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3096 DAG.getConstant(2, DL, MVT::i32));
3097 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3098 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3099 MachinePointerInfo());
3101 // Get the offset of the start of the .tls section (section base)
3102 const auto *GA = cast<GlobalAddressSDNode>(Op);
3103 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3104 SDValue Offset = DAG.getLoad(
3105 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3106 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3107 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3109 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3112 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3113 SDValue
3114 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3115 SelectionDAG &DAG) const {
3116 SDLoc dl(GA);
3117 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3118 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3119 MachineFunction &MF = DAG.getMachineFunction();
3120 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3121 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3122 ARMConstantPoolValue *CPV =
3123 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3124 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3125 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3126 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3127 Argument = DAG.getLoad(
3128 PtrVT, dl, DAG.getEntryNode(), Argument,
3129 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3130 SDValue Chain = Argument.getValue(1);
3132 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3133 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3135 // call __tls_get_addr.
3136 ArgListTy Args;
3137 ArgListEntry Entry;
3138 Entry.Node = Argument;
3139 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3140 Args.push_back(Entry);
3142 // FIXME: is there useful debug info available here?
3143 TargetLowering::CallLoweringInfo CLI(DAG);
3144 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3145 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3146 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3148 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3149 return CallResult.first;
3152 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3153 // "local exec" model.
3154 SDValue
3155 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3156 SelectionDAG &DAG,
3157 TLSModel::Model model) const {
3158 const GlobalValue *GV = GA->getGlobal();
3159 SDLoc dl(GA);
3160 SDValue Offset;
3161 SDValue Chain = DAG.getEntryNode();
3162 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3163 // Get the Thread Pointer
3164 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3166 if (model == TLSModel::InitialExec) {
3167 MachineFunction &MF = DAG.getMachineFunction();
3168 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3169 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3170 // Initial exec model.
3171 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3172 ARMConstantPoolValue *CPV =
3173 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3174 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3175 true);
3176 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3177 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3178 Offset = DAG.getLoad(
3179 PtrVT, dl, Chain, Offset,
3180 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3181 Chain = Offset.getValue(1);
3183 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3184 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3186 Offset = DAG.getLoad(
3187 PtrVT, dl, Chain, Offset,
3188 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3189 } else {
3190 // local exec model
3191 assert(model == TLSModel::LocalExec);
3192 ARMConstantPoolValue *CPV =
3193 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3194 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3195 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3196 Offset = DAG.getLoad(
3197 PtrVT, dl, Chain, Offset,
3198 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3201 // The address of the thread local variable is the add of the thread
3202 // pointer with the offset of the variable.
3203 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3206 SDValue
3207 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3208 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3209 if (DAG.getTarget().useEmulatedTLS())
3210 return LowerToTLSEmulatedModel(GA, DAG);
3212 if (Subtarget->isTargetDarwin())
3213 return LowerGlobalTLSAddressDarwin(Op, DAG);
3215 if (Subtarget->isTargetWindows())
3216 return LowerGlobalTLSAddressWindows(Op, DAG);
3218 // TODO: implement the "local dynamic" model
3219 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3220 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3222 switch (model) {
3223 case TLSModel::GeneralDynamic:
3224 case TLSModel::LocalDynamic:
3225 return LowerToTLSGeneralDynamicModel(GA, DAG);
3226 case TLSModel::InitialExec:
3227 case TLSModel::LocalExec:
3228 return LowerToTLSExecModels(GA, DAG, model);
3230 llvm_unreachable("bogus TLS model");
3233 /// Return true if all users of V are within function F, looking through
3234 /// ConstantExprs.
3235 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3236 SmallVector<const User*,4> Worklist;
3237 for (auto *U : V->users())
3238 Worklist.push_back(U);
3239 while (!Worklist.empty()) {
3240 auto *U = Worklist.pop_back_val();
3241 if (isa<ConstantExpr>(U)) {
3242 for (auto *UU : U->users())
3243 Worklist.push_back(UU);
3244 continue;
3247 auto *I = dyn_cast<Instruction>(U);
3248 if (!I || I->getParent()->getParent() != F)
3249 return false;
3251 return true;
3254 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3255 const GlobalValue *GV, SelectionDAG &DAG,
3256 EVT PtrVT, const SDLoc &dl) {
3257 // If we're creating a pool entry for a constant global with unnamed address,
3258 // and the global is small enough, we can emit it inline into the constant pool
3259 // to save ourselves an indirection.
3261 // This is a win if the constant is only used in one function (so it doesn't
3262 // need to be duplicated) or duplicating the constant wouldn't increase code
3263 // size (implying the constant is no larger than 4 bytes).
3264 const Function &F = DAG.getMachineFunction().getFunction();
3266 // We rely on this decision to inline being idemopotent and unrelated to the
3267 // use-site. We know that if we inline a variable at one use site, we'll
3268 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3269 // doesn't know about this optimization, so bail out if it's enabled else
3270 // we could decide to inline here (and thus never emit the GV) but require
3271 // the GV from fast-isel generated code.
3272 if (!EnableConstpoolPromotion ||
3273 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3274 return SDValue();
3276 auto *GVar = dyn_cast<GlobalVariable>(GV);
3277 if (!GVar || !GVar->hasInitializer() ||
3278 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3279 !GVar->hasLocalLinkage())
3280 return SDValue();
3282 // If we inline a value that contains relocations, we move the relocations
3283 // from .data to .text. This is not allowed in position-independent code.
3284 auto *Init = GVar->getInitializer();
3285 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3286 Init->needsRelocation())
3287 return SDValue();
3289 // The constant islands pass can only really deal with alignment requests
3290 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3291 // any type wanting greater alignment requirements than 4 bytes. We also
3292 // can only promote constants that are multiples of 4 bytes in size or
3293 // are paddable to a multiple of 4. Currently we only try and pad constants
3294 // that are strings for simplicity.
3295 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3296 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3297 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3298 unsigned RequiredPadding = 4 - (Size % 4);
3299 bool PaddingPossible =
3300 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3301 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3302 Size == 0)
3303 return SDValue();
3305 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3306 MachineFunction &MF = DAG.getMachineFunction();
3307 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3309 // We can't bloat the constant pool too much, else the ConstantIslands pass
3310 // may fail to converge. If we haven't promoted this global yet (it may have
3311 // multiple uses), and promoting it would increase the constant pool size (Sz
3312 // > 4), ensure we have space to do so up to MaxTotal.
3313 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3314 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3315 ConstpoolPromotionMaxTotal)
3316 return SDValue();
3318 // This is only valid if all users are in a single function; we can't clone
3319 // the constant in general. The LLVM IR unnamed_addr allows merging
3320 // constants, but not cloning them.
3322 // We could potentially allow cloning if we could prove all uses of the
3323 // constant in the current function don't care about the address, like
3324 // printf format strings. But that isn't implemented for now.
3325 if (!allUsersAreInFunction(GVar, &F))
3326 return SDValue();
3328 // We're going to inline this global. Pad it out if needed.
3329 if (RequiredPadding != 4) {
3330 StringRef S = CDAInit->getAsString();
3332 SmallVector<uint8_t,16> V(S.size());
3333 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3334 while (RequiredPadding--)
3335 V.push_back(0);
3336 Init = ConstantDataArray::get(*DAG.getContext(), V);
3339 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3340 SDValue CPAddr =
3341 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3342 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3343 AFI->markGlobalAsPromotedToConstantPool(GVar);
3344 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3345 PaddedSize - 4);
3347 ++NumConstpoolPromoted;
3348 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3351 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3352 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3353 if (!(GV = GA->getBaseObject()))
3354 return false;
3355 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3356 return V->isConstant();
3357 return isa<Function>(GV);
3360 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3361 SelectionDAG &DAG) const {
3362 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3363 default: llvm_unreachable("unknown object format");
3364 case Triple::COFF:
3365 return LowerGlobalAddressWindows(Op, DAG);
3366 case Triple::ELF:
3367 return LowerGlobalAddressELF(Op, DAG);
3368 case Triple::MachO:
3369 return LowerGlobalAddressDarwin(Op, DAG);
3373 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3374 SelectionDAG &DAG) const {
3375 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3376 SDLoc dl(Op);
3377 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3378 const TargetMachine &TM = getTargetMachine();
3379 bool IsRO = isReadOnly(GV);
3381 // promoteToConstantPool only if not generating XO text section
3382 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3383 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3384 return V;
3386 if (isPositionIndependent()) {
3387 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3388 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3389 UseGOT_PREL ? ARMII::MO_GOT : 0);
3390 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3391 if (UseGOT_PREL)
3392 Result =
3393 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3394 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3395 return Result;
3396 } else if (Subtarget->isROPI() && IsRO) {
3397 // PC-relative.
3398 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3399 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3400 return Result;
3401 } else if (Subtarget->isRWPI() && !IsRO) {
3402 // SB-relative.
3403 SDValue RelAddr;
3404 if (Subtarget->useMovt()) {
3405 ++NumMovwMovt;
3406 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3407 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3408 } else { // use literal pool for address constant
3409 ARMConstantPoolValue *CPV =
3410 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3411 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3412 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3413 RelAddr = DAG.getLoad(
3414 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3415 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3417 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3418 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3419 return Result;
3422 // If we have T2 ops, we can materialize the address directly via movt/movw
3423 // pair. This is always cheaper.
3424 if (Subtarget->useMovt()) {
3425 ++NumMovwMovt;
3426 // FIXME: Once remat is capable of dealing with instructions with register
3427 // operands, expand this into two nodes.
3428 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3429 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3430 } else {
3431 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3432 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3433 return DAG.getLoad(
3434 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3435 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3439 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3440 SelectionDAG &DAG) const {
3441 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3442 "ROPI/RWPI not currently supported for Darwin");
3443 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3444 SDLoc dl(Op);
3445 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3447 if (Subtarget->useMovt())
3448 ++NumMovwMovt;
3450 // FIXME: Once remat is capable of dealing with instructions with register
3451 // operands, expand this into multiple nodes
3452 unsigned Wrapper =
3453 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3455 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3456 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3458 if (Subtarget->isGVIndirectSymbol(GV))
3459 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3460 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3461 return Result;
3464 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3465 SelectionDAG &DAG) const {
3466 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3467 assert(Subtarget->useMovt() &&
3468 "Windows on ARM expects to use movw/movt");
3469 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3470 "ROPI/RWPI not currently supported for Windows");
3472 const TargetMachine &TM = getTargetMachine();
3473 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3474 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3475 if (GV->hasDLLImportStorageClass())
3476 TargetFlags = ARMII::MO_DLLIMPORT;
3477 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3478 TargetFlags = ARMII::MO_COFFSTUB;
3479 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3480 SDValue Result;
3481 SDLoc DL(Op);
3483 ++NumMovwMovt;
3485 // FIXME: Once remat is capable of dealing with instructions with register
3486 // operands, expand this into two nodes.
3487 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3488 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3489 TargetFlags));
3490 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3491 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3492 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3493 return Result;
3496 SDValue
3497 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3498 SDLoc dl(Op);
3499 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3500 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3501 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3502 Op.getOperand(1), Val);
3505 SDValue
3506 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3507 SDLoc dl(Op);
3508 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3509 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3512 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3513 SelectionDAG &DAG) const {
3514 SDLoc dl(Op);
3515 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3516 Op.getOperand(0));
3519 SDValue
3520 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3521 const ARMSubtarget *Subtarget) const {
3522 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3523 SDLoc dl(Op);
3524 switch (IntNo) {
3525 default: return SDValue(); // Don't custom lower most intrinsics.
3526 case Intrinsic::thread_pointer: {
3527 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3528 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3530 case Intrinsic::eh_sjlj_lsda: {
3531 MachineFunction &MF = DAG.getMachineFunction();
3532 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3533 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3534 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3535 SDValue CPAddr;
3536 bool IsPositionIndependent = isPositionIndependent();
3537 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3538 ARMConstantPoolValue *CPV =
3539 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3540 ARMCP::CPLSDA, PCAdj);
3541 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3542 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3543 SDValue Result = DAG.getLoad(
3544 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3545 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3547 if (IsPositionIndependent) {
3548 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3549 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3551 return Result;
3553 case Intrinsic::arm_neon_vabs:
3554 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3555 Op.getOperand(1));
3556 case Intrinsic::arm_neon_vmulls:
3557 case Intrinsic::arm_neon_vmullu: {
3558 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3559 ? ARMISD::VMULLs : ARMISD::VMULLu;
3560 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3561 Op.getOperand(1), Op.getOperand(2));
3563 case Intrinsic::arm_neon_vminnm:
3564 case Intrinsic::arm_neon_vmaxnm: {
3565 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3566 ? ISD::FMINNUM : ISD::FMAXNUM;
3567 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3568 Op.getOperand(1), Op.getOperand(2));
3570 case Intrinsic::arm_neon_vminu:
3571 case Intrinsic::arm_neon_vmaxu: {
3572 if (Op.getValueType().isFloatingPoint())
3573 return SDValue();
3574 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3575 ? ISD::UMIN : ISD::UMAX;
3576 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3577 Op.getOperand(1), Op.getOperand(2));
3579 case Intrinsic::arm_neon_vmins:
3580 case Intrinsic::arm_neon_vmaxs: {
3581 // v{min,max}s is overloaded between signed integers and floats.
3582 if (!Op.getValueType().isFloatingPoint()) {
3583 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3584 ? ISD::SMIN : ISD::SMAX;
3585 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3586 Op.getOperand(1), Op.getOperand(2));
3588 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3589 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3590 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3591 Op.getOperand(1), Op.getOperand(2));
3593 case Intrinsic::arm_neon_vtbl1:
3594 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3595 Op.getOperand(1), Op.getOperand(2));
3596 case Intrinsic::arm_neon_vtbl2:
3597 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3598 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3602 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3603 const ARMSubtarget *Subtarget) {
3604 SDLoc dl(Op);
3605 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3606 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3607 if (SSID == SyncScope::SingleThread)
3608 return Op;
3610 if (!Subtarget->hasDataBarrier()) {
3611 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3612 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3613 // here.
3614 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3615 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3616 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3617 DAG.getConstant(0, dl, MVT::i32));
3620 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3621 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3622 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3623 if (Subtarget->isMClass()) {
3624 // Only a full system barrier exists in the M-class architectures.
3625 Domain = ARM_MB::SY;
3626 } else if (Subtarget->preferISHSTBarriers() &&
3627 Ord == AtomicOrdering::Release) {
3628 // Swift happens to implement ISHST barriers in a way that's compatible with
3629 // Release semantics but weaker than ISH so we'd be fools not to use
3630 // it. Beware: other processors probably don't!
3631 Domain = ARM_MB::ISHST;
3634 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3635 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3636 DAG.getConstant(Domain, dl, MVT::i32));
3639 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3640 const ARMSubtarget *Subtarget) {
3641 // ARM pre v5TE and Thumb1 does not have preload instructions.
3642 if (!(Subtarget->isThumb2() ||
3643 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3644 // Just preserve the chain.
3645 return Op.getOperand(0);
3647 SDLoc dl(Op);
3648 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3649 if (!isRead &&
3650 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3651 // ARMv7 with MP extension has PLDW.
3652 return Op.getOperand(0);
3654 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3655 if (Subtarget->isThumb()) {
3656 // Invert the bits.
3657 isRead = ~isRead & 1;
3658 isData = ~isData & 1;
3661 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3662 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3663 DAG.getConstant(isData, dl, MVT::i32));
3666 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3667 MachineFunction &MF = DAG.getMachineFunction();
3668 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3670 // vastart just stores the address of the VarArgsFrameIndex slot into the
3671 // memory location argument.
3672 SDLoc dl(Op);
3673 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3674 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3675 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3676 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3677 MachinePointerInfo(SV));
3680 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3681 CCValAssign &NextVA,
3682 SDValue &Root,
3683 SelectionDAG &DAG,
3684 const SDLoc &dl) const {
3685 MachineFunction &MF = DAG.getMachineFunction();
3686 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3688 const TargetRegisterClass *RC;
3689 if (AFI->isThumb1OnlyFunction())
3690 RC = &ARM::tGPRRegClass;
3691 else
3692 RC = &ARM::GPRRegClass;
3694 // Transform the arguments stored in physical registers into virtual ones.
3695 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3696 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3698 SDValue ArgValue2;
3699 if (NextVA.isMemLoc()) {
3700 MachineFrameInfo &MFI = MF.getFrameInfo();
3701 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3703 // Create load node to retrieve arguments from the stack.
3704 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3705 ArgValue2 = DAG.getLoad(
3706 MVT::i32, dl, Root, FIN,
3707 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3708 } else {
3709 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3710 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3712 if (!Subtarget->isLittle())
3713 std::swap (ArgValue, ArgValue2);
3714 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3717 // The remaining GPRs hold either the beginning of variable-argument
3718 // data, or the beginning of an aggregate passed by value (usually
3719 // byval). Either way, we allocate stack slots adjacent to the data
3720 // provided by our caller, and store the unallocated registers there.
3721 // If this is a variadic function, the va_list pointer will begin with
3722 // these values; otherwise, this reassembles a (byval) structure that
3723 // was split between registers and memory.
3724 // Return: The frame index registers were stored into.
3725 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3726 const SDLoc &dl, SDValue &Chain,
3727 const Value *OrigArg,
3728 unsigned InRegsParamRecordIdx,
3729 int ArgOffset, unsigned ArgSize) const {
3730 // Currently, two use-cases possible:
3731 // Case #1. Non-var-args function, and we meet first byval parameter.
3732 // Setup first unallocated register as first byval register;
3733 // eat all remained registers
3734 // (these two actions are performed by HandleByVal method).
3735 // Then, here, we initialize stack frame with
3736 // "store-reg" instructions.
3737 // Case #2. Var-args function, that doesn't contain byval parameters.
3738 // The same: eat all remained unallocated registers,
3739 // initialize stack frame.
3741 MachineFunction &MF = DAG.getMachineFunction();
3742 MachineFrameInfo &MFI = MF.getFrameInfo();
3743 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3744 unsigned RBegin, REnd;
3745 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3746 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3747 } else {
3748 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3749 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3750 REnd = ARM::R4;
3753 if (REnd != RBegin)
3754 ArgOffset = -4 * (ARM::R4 - RBegin);
3756 auto PtrVT = getPointerTy(DAG.getDataLayout());
3757 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3758 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3760 SmallVector<SDValue, 4> MemOps;
3761 const TargetRegisterClass *RC =
3762 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3764 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3765 unsigned VReg = MF.addLiveIn(Reg, RC);
3766 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3767 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3768 MachinePointerInfo(OrigArg, 4 * i));
3769 MemOps.push_back(Store);
3770 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3773 if (!MemOps.empty())
3774 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3775 return FrameIndex;
3778 // Setup stack frame, the va_list pointer will start from.
3779 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3780 const SDLoc &dl, SDValue &Chain,
3781 unsigned ArgOffset,
3782 unsigned TotalArgRegsSaveSize,
3783 bool ForceMutable) const {
3784 MachineFunction &MF = DAG.getMachineFunction();
3785 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3787 // Try to store any remaining integer argument regs
3788 // to their spots on the stack so that they may be loaded by dereferencing
3789 // the result of va_next.
3790 // If there is no regs to be stored, just point address after last
3791 // argument passed via stack.
3792 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3793 CCInfo.getInRegsParamsCount(),
3794 CCInfo.getNextStackOffset(),
3795 std::max(4U, TotalArgRegsSaveSize));
3796 AFI->setVarArgsFrameIndex(FrameIndex);
3799 SDValue ARMTargetLowering::LowerFormalArguments(
3800 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3801 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3802 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3803 MachineFunction &MF = DAG.getMachineFunction();
3804 MachineFrameInfo &MFI = MF.getFrameInfo();
3806 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3808 // Assign locations to all of the incoming arguments.
3809 SmallVector<CCValAssign, 16> ArgLocs;
3810 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3811 *DAG.getContext());
3812 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3814 SmallVector<SDValue, 16> ArgValues;
3815 SDValue ArgValue;
3816 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3817 unsigned CurArgIdx = 0;
3819 // Initially ArgRegsSaveSize is zero.
3820 // Then we increase this value each time we meet byval parameter.
3821 // We also increase this value in case of varargs function.
3822 AFI->setArgRegsSaveSize(0);
3824 // Calculate the amount of stack space that we need to allocate to store
3825 // byval and variadic arguments that are passed in registers.
3826 // We need to know this before we allocate the first byval or variadic
3827 // argument, as they will be allocated a stack slot below the CFA (Canonical
3828 // Frame Address, the stack pointer at entry to the function).
3829 unsigned ArgRegBegin = ARM::R4;
3830 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3831 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3832 break;
3834 CCValAssign &VA = ArgLocs[i];
3835 unsigned Index = VA.getValNo();
3836 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3837 if (!Flags.isByVal())
3838 continue;
3840 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3841 unsigned RBegin, REnd;
3842 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3843 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3845 CCInfo.nextInRegsParam();
3847 CCInfo.rewindByValRegsInfo();
3849 int lastInsIndex = -1;
3850 if (isVarArg && MFI.hasVAStart()) {
3851 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3852 if (RegIdx != array_lengthof(GPRArgRegs))
3853 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3856 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3857 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3858 auto PtrVT = getPointerTy(DAG.getDataLayout());
3860 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3861 CCValAssign &VA = ArgLocs[i];
3862 if (Ins[VA.getValNo()].isOrigArg()) {
3863 std::advance(CurOrigArg,
3864 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3865 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3867 // Arguments stored in registers.
3868 if (VA.isRegLoc()) {
3869 EVT RegVT = VA.getLocVT();
3871 if (VA.needsCustom()) {
3872 // f64 and vector types are split up into multiple registers or
3873 // combinations of registers and stack slots.
3874 if (VA.getLocVT() == MVT::v2f64) {
3875 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3876 Chain, DAG, dl);
3877 VA = ArgLocs[++i]; // skip ahead to next loc
3878 SDValue ArgValue2;
3879 if (VA.isMemLoc()) {
3880 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3881 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3882 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3883 MachinePointerInfo::getFixedStack(
3884 DAG.getMachineFunction(), FI));
3885 } else {
3886 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3887 Chain, DAG, dl);
3889 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3890 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3891 ArgValue, ArgValue1,
3892 DAG.getIntPtrConstant(0, dl));
3893 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3894 ArgValue, ArgValue2,
3895 DAG.getIntPtrConstant(1, dl));
3896 } else
3897 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3898 } else {
3899 const TargetRegisterClass *RC;
3902 if (RegVT == MVT::f16)
3903 RC = &ARM::HPRRegClass;
3904 else if (RegVT == MVT::f32)
3905 RC = &ARM::SPRRegClass;
3906 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3907 RC = &ARM::DPRRegClass;
3908 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3909 RC = &ARM::QPRRegClass;
3910 else if (RegVT == MVT::i32)
3911 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3912 : &ARM::GPRRegClass;
3913 else
3914 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3916 // Transform the arguments in physical registers into virtual ones.
3917 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3918 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3920 // If this value is passed in r0 and has the returned attribute (e.g.
3921 // C++ 'structors), record this fact for later use.
3922 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
3923 AFI->setPreservesR0();
3927 // If this is an 8 or 16-bit value, it is really passed promoted
3928 // to 32 bits. Insert an assert[sz]ext to capture this, then
3929 // truncate to the right size.
3930 switch (VA.getLocInfo()) {
3931 default: llvm_unreachable("Unknown loc info!");
3932 case CCValAssign::Full: break;
3933 case CCValAssign::BCvt:
3934 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3935 break;
3936 case CCValAssign::SExt:
3937 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3938 DAG.getValueType(VA.getValVT()));
3939 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3940 break;
3941 case CCValAssign::ZExt:
3942 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3943 DAG.getValueType(VA.getValVT()));
3944 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3945 break;
3948 InVals.push_back(ArgValue);
3949 } else { // VA.isRegLoc()
3950 // sanity check
3951 assert(VA.isMemLoc());
3952 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3954 int index = VA.getValNo();
3956 // Some Ins[] entries become multiple ArgLoc[] entries.
3957 // Process them only once.
3958 if (index != lastInsIndex)
3960 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3961 // FIXME: For now, all byval parameter objects are marked mutable.
3962 // This can be changed with more analysis.
3963 // In case of tail call optimization mark all arguments mutable.
3964 // Since they could be overwritten by lowering of arguments in case of
3965 // a tail call.
3966 if (Flags.isByVal()) {
3967 assert(Ins[index].isOrigArg() &&
3968 "Byval arguments cannot be implicit");
3969 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3971 int FrameIndex = StoreByValRegs(
3972 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3973 VA.getLocMemOffset(), Flags.getByValSize());
3974 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3975 CCInfo.nextInRegsParam();
3976 } else {
3977 unsigned FIOffset = VA.getLocMemOffset();
3978 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3979 FIOffset, true);
3981 // Create load nodes to retrieve arguments from the stack.
3982 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3983 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3984 MachinePointerInfo::getFixedStack(
3985 DAG.getMachineFunction(), FI)));
3987 lastInsIndex = index;
3992 // varargs
3993 if (isVarArg && MFI.hasVAStart())
3994 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3995 CCInfo.getNextStackOffset(),
3996 TotalArgRegsSaveSize);
3998 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4000 return Chain;
4003 /// isFloatingPointZero - Return true if this is +0.0.
4004 static bool isFloatingPointZero(SDValue Op) {
4005 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4006 return CFP->getValueAPF().isPosZero();
4007 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4008 // Maybe this has already been legalized into the constant pool?
4009 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4010 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4011 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4012 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4013 return CFP->getValueAPF().isPosZero();
4015 } else if (Op->getOpcode() == ISD::BITCAST &&
4016 Op->getValueType(0) == MVT::f64) {
4017 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4018 // created by LowerConstantFP().
4019 SDValue BitcastOp = Op->getOperand(0);
4020 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4021 isNullConstant(BitcastOp->getOperand(0)))
4022 return true;
4024 return false;
4027 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4028 /// the given operands.
4029 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4030 SDValue &ARMcc, SelectionDAG &DAG,
4031 const SDLoc &dl) const {
4032 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4033 unsigned C = RHSC->getZExtValue();
4034 if (!isLegalICmpImmediate((int32_t)C)) {
4035 // Constant does not fit, try adjusting it by one.
4036 switch (CC) {
4037 default: break;
4038 case ISD::SETLT:
4039 case ISD::SETGE:
4040 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4041 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4042 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4044 break;
4045 case ISD::SETULT:
4046 case ISD::SETUGE:
4047 if (C != 0 && isLegalICmpImmediate(C-1)) {
4048 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4049 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4051 break;
4052 case ISD::SETLE:
4053 case ISD::SETGT:
4054 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4055 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4056 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4058 break;
4059 case ISD::SETULE:
4060 case ISD::SETUGT:
4061 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4062 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4063 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4065 break;
4068 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4069 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4070 // In ARM and Thumb-2, the compare instructions can shift their second
4071 // operand.
4072 CC = ISD::getSetCCSwappedOperands(CC);
4073 std::swap(LHS, RHS);
4076 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4078 // If the RHS is a constant zero then the V (overflow) flag will never be
4079 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4080 // simpler for other passes (like the peephole optimiser) to deal with.
4081 if (isNullConstant(RHS)) {
4082 switch (CondCode) {
4083 default: break;
4084 case ARMCC::GE:
4085 CondCode = ARMCC::PL;
4086 break;
4087 case ARMCC::LT:
4088 CondCode = ARMCC::MI;
4089 break;
4093 ARMISD::NodeType CompareType;
4094 switch (CondCode) {
4095 default:
4096 CompareType = ARMISD::CMP;
4097 break;
4098 case ARMCC::EQ:
4099 case ARMCC::NE:
4100 // Uses only Z Flag
4101 CompareType = ARMISD::CMPZ;
4102 break;
4104 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4105 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4108 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4109 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4110 SelectionDAG &DAG, const SDLoc &dl,
4111 bool InvalidOnQNaN) const {
4112 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4113 SDValue Cmp;
4114 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4115 if (!isFloatingPointZero(RHS))
4116 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4117 else
4118 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4119 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4122 /// duplicateCmp - Glue values can have only one use, so this function
4123 /// duplicates a comparison node.
4124 SDValue
4125 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4126 unsigned Opc = Cmp.getOpcode();
4127 SDLoc DL(Cmp);
4128 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4129 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4131 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4132 Cmp = Cmp.getOperand(0);
4133 Opc = Cmp.getOpcode();
4134 if (Opc == ARMISD::CMPFP)
4135 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4136 Cmp.getOperand(1), Cmp.getOperand(2));
4137 else {
4138 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4139 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4140 Cmp.getOperand(1));
4142 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4145 // This function returns three things: the arithmetic computation itself
4146 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4147 // comparison and the condition code define the case in which the arithmetic
4148 // computation *does not* overflow.
4149 std::pair<SDValue, SDValue>
4150 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4151 SDValue &ARMcc) const {
4152 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4154 SDValue Value, OverflowCmp;
4155 SDValue LHS = Op.getOperand(0);
4156 SDValue RHS = Op.getOperand(1);
4157 SDLoc dl(Op);
4159 // FIXME: We are currently always generating CMPs because we don't support
4160 // generating CMN through the backend. This is not as good as the natural
4161 // CMP case because it causes a register dependency and cannot be folded
4162 // later.
4164 switch (Op.getOpcode()) {
4165 default:
4166 llvm_unreachable("Unknown overflow instruction!");
4167 case ISD::SADDO:
4168 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4169 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4170 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4171 break;
4172 case ISD::UADDO:
4173 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4174 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4175 // We do not use it in the USUBO case as Value may not be used.
4176 Value = DAG.getNode(ARMISD::ADDC, dl,
4177 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4178 .getValue(0);
4179 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4180 break;
4181 case ISD::SSUBO:
4182 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4183 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4184 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4185 break;
4186 case ISD::USUBO:
4187 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4188 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4189 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4190 break;
4191 case ISD::UMULO:
4192 // We generate a UMUL_LOHI and then check if the high word is 0.
4193 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4194 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4195 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4196 LHS, RHS);
4197 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4198 DAG.getConstant(0, dl, MVT::i32));
4199 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4200 break;
4201 case ISD::SMULO:
4202 // We generate a SMUL_LOHI and then check if all the bits of the high word
4203 // are the same as the sign bit of the low word.
4204 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4205 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4206 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4207 LHS, RHS);
4208 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4209 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4210 Value.getValue(0),
4211 DAG.getConstant(31, dl, MVT::i32)));
4212 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4213 break;
4214 } // switch (...)
4216 return std::make_pair(Value, OverflowCmp);
4219 SDValue
4220 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4221 // Let legalize expand this if it isn't a legal type yet.
4222 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4223 return SDValue();
4225 SDValue Value, OverflowCmp;
4226 SDValue ARMcc;
4227 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4228 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4229 SDLoc dl(Op);
4230 // We use 0 and 1 as false and true values.
4231 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4232 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4233 EVT VT = Op.getValueType();
4235 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4236 ARMcc, CCR, OverflowCmp);
4238 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4239 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4242 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4243 SelectionDAG &DAG) {
4244 SDLoc DL(BoolCarry);
4245 EVT CarryVT = BoolCarry.getValueType();
4247 // This converts the boolean value carry into the carry flag by doing
4248 // ARMISD::SUBC Carry, 1
4249 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4250 DAG.getVTList(CarryVT, MVT::i32),
4251 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4252 return Carry.getValue(1);
4255 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4256 SelectionDAG &DAG) {
4257 SDLoc DL(Flags);
4259 // Now convert the carry flag into a boolean carry. We do this
4260 // using ARMISD:ADDE 0, 0, Carry
4261 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4262 DAG.getConstant(0, DL, MVT::i32),
4263 DAG.getConstant(0, DL, MVT::i32), Flags);
4266 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4267 SelectionDAG &DAG) const {
4268 // Let legalize expand this if it isn't a legal type yet.
4269 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4270 return SDValue();
4272 SDValue LHS = Op.getOperand(0);
4273 SDValue RHS = Op.getOperand(1);
4274 SDLoc dl(Op);
4276 EVT VT = Op.getValueType();
4277 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4278 SDValue Value;
4279 SDValue Overflow;
4280 switch (Op.getOpcode()) {
4281 default:
4282 llvm_unreachable("Unknown overflow instruction!");
4283 case ISD::UADDO:
4284 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4285 // Convert the carry flag into a boolean value.
4286 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4287 break;
4288 case ISD::USUBO: {
4289 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4290 // Convert the carry flag into a boolean value.
4291 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4292 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4293 // value. So compute 1 - C.
4294 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4295 DAG.getConstant(1, dl, MVT::i32), Overflow);
4296 break;
4300 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4303 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4304 SDValue Cond = Op.getOperand(0);
4305 SDValue SelectTrue = Op.getOperand(1);
4306 SDValue SelectFalse = Op.getOperand(2);
4307 SDLoc dl(Op);
4308 unsigned Opc = Cond.getOpcode();
4310 if (Cond.getResNo() == 1 &&
4311 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4312 Opc == ISD::USUBO)) {
4313 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4314 return SDValue();
4316 SDValue Value, OverflowCmp;
4317 SDValue ARMcc;
4318 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4319 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4320 EVT VT = Op.getValueType();
4322 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4323 OverflowCmp, DAG);
4326 // Convert:
4328 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4329 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4331 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4332 const ConstantSDNode *CMOVTrue =
4333 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4334 const ConstantSDNode *CMOVFalse =
4335 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4337 if (CMOVTrue && CMOVFalse) {
4338 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4339 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4341 SDValue True;
4342 SDValue False;
4343 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4344 True = SelectTrue;
4345 False = SelectFalse;
4346 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4347 True = SelectFalse;
4348 False = SelectTrue;
4351 if (True.getNode() && False.getNode()) {
4352 EVT VT = Op.getValueType();
4353 SDValue ARMcc = Cond.getOperand(2);
4354 SDValue CCR = Cond.getOperand(3);
4355 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4356 assert(True.getValueType() == VT);
4357 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4362 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4363 // undefined bits before doing a full-word comparison with zero.
4364 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4365 DAG.getConstant(1, dl, Cond.getValueType()));
4367 return DAG.getSelectCC(dl, Cond,
4368 DAG.getConstant(0, dl, Cond.getValueType()),
4369 SelectTrue, SelectFalse, ISD::SETNE);
4372 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4373 bool &swpCmpOps, bool &swpVselOps) {
4374 // Start by selecting the GE condition code for opcodes that return true for
4375 // 'equality'
4376 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4377 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4378 CondCode = ARMCC::GE;
4380 // and GT for opcodes that return false for 'equality'.
4381 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4382 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4383 CondCode = ARMCC::GT;
4385 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4386 // to swap the compare operands.
4387 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4388 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4389 swpCmpOps = true;
4391 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4392 // If we have an unordered opcode, we need to swap the operands to the VSEL
4393 // instruction (effectively negating the condition).
4395 // This also has the effect of swapping which one of 'less' or 'greater'
4396 // returns true, so we also swap the compare operands. It also switches
4397 // whether we return true for 'equality', so we compensate by picking the
4398 // opposite condition code to our original choice.
4399 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4400 CC == ISD::SETUGT) {
4401 swpCmpOps = !swpCmpOps;
4402 swpVselOps = !swpVselOps;
4403 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4406 // 'ordered' is 'anything but unordered', so use the VS condition code and
4407 // swap the VSEL operands.
4408 if (CC == ISD::SETO) {
4409 CondCode = ARMCC::VS;
4410 swpVselOps = true;
4413 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4414 // code and swap the VSEL operands. Also do this if we don't care about the
4415 // unordered case.
4416 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4417 CondCode = ARMCC::EQ;
4418 swpVselOps = true;
4422 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4423 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4424 SDValue Cmp, SelectionDAG &DAG) const {
4425 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4426 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4427 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4428 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4429 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4431 SDValue TrueLow = TrueVal.getValue(0);
4432 SDValue TrueHigh = TrueVal.getValue(1);
4433 SDValue FalseLow = FalseVal.getValue(0);
4434 SDValue FalseHigh = FalseVal.getValue(1);
4436 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4437 ARMcc, CCR, Cmp);
4438 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4439 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4441 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4442 } else {
4443 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4444 Cmp);
4448 static bool isGTorGE(ISD::CondCode CC) {
4449 return CC == ISD::SETGT || CC == ISD::SETGE;
4452 static bool isLTorLE(ISD::CondCode CC) {
4453 return CC == ISD::SETLT || CC == ISD::SETLE;
4456 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4457 // All of these conditions (and their <= and >= counterparts) will do:
4458 // x < k ? k : x
4459 // x > k ? x : k
4460 // k < x ? x : k
4461 // k > x ? k : x
4462 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4463 const SDValue TrueVal, const SDValue FalseVal,
4464 const ISD::CondCode CC, const SDValue K) {
4465 return (isGTorGE(CC) &&
4466 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4467 (isLTorLE(CC) &&
4468 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4471 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4472 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4473 const SDValue TrueVal, const SDValue FalseVal,
4474 const ISD::CondCode CC, const SDValue K) {
4475 return (isGTorGE(CC) &&
4476 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4477 (isLTorLE(CC) &&
4478 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4481 // Check if two chained conditionals could be converted into SSAT or USAT.
4483 // SSAT can replace a set of two conditional selectors that bound a number to an
4484 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4486 // x < -k ? -k : (x > k ? k : x)
4487 // x < -k ? -k : (x < k ? x : k)
4488 // x > -k ? (x > k ? k : x) : -k
4489 // x < k ? (x < -k ? -k : x) : k
4490 // etc.
4492 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4493 // a power of 2.
4495 // It returns true if the conversion can be done, false otherwise.
4496 // Additionally, the variable is returned in parameter V, the constant in K and
4497 // usat is set to true if the conditional represents an unsigned saturation
4498 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4499 uint64_t &K, bool &usat) {
4500 SDValue LHS1 = Op.getOperand(0);
4501 SDValue RHS1 = Op.getOperand(1);
4502 SDValue TrueVal1 = Op.getOperand(2);
4503 SDValue FalseVal1 = Op.getOperand(3);
4504 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4506 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4507 if (Op2.getOpcode() != ISD::SELECT_CC)
4508 return false;
4510 SDValue LHS2 = Op2.getOperand(0);
4511 SDValue RHS2 = Op2.getOperand(1);
4512 SDValue TrueVal2 = Op2.getOperand(2);
4513 SDValue FalseVal2 = Op2.getOperand(3);
4514 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4516 // Find out which are the constants and which are the variables
4517 // in each conditional
4518 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4519 ? &RHS1
4520 : nullptr;
4521 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4522 ? &RHS2
4523 : nullptr;
4524 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4525 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4526 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4527 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4529 // We must detect cases where the original operations worked with 16- or
4530 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4531 // must work with sign-extended values but the select operations return
4532 // the original non-extended value.
4533 SDValue V2TmpReg = V2Tmp;
4534 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4535 V2TmpReg = V2Tmp->getOperand(0);
4537 // Check that the registers and the constants have the correct values
4538 // in both conditionals
4539 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4540 V2TmpReg != V2)
4541 return false;
4543 // Figure out which conditional is saturating the lower/upper bound.
4544 const SDValue *LowerCheckOp =
4545 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4546 ? &Op
4547 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4548 ? &Op2
4549 : nullptr;
4550 const SDValue *UpperCheckOp =
4551 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4552 ? &Op
4553 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4554 ? &Op2
4555 : nullptr;
4557 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4558 return false;
4560 // Check that the constant in the lower-bound check is
4561 // the opposite of the constant in the upper-bound check
4562 // in 1's complement.
4563 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4564 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4565 int64_t PosVal = std::max(Val1, Val2);
4566 int64_t NegVal = std::min(Val1, Val2);
4568 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4569 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4570 isPowerOf2_64(PosVal + 1)) {
4572 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4573 if (Val1 == ~Val2)
4574 usat = false;
4575 else if (NegVal == 0)
4576 usat = true;
4577 else
4578 return false;
4580 V = V2;
4581 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4583 return true;
4586 return false;
4589 // Check if a condition of the type x < k ? k : x can be converted into a
4590 // bit operation instead of conditional moves.
4591 // Currently this is allowed given:
4592 // - The conditions and values match up
4593 // - k is 0 or -1 (all ones)
4594 // This function will not check the last condition, thats up to the caller
4595 // It returns true if the transformation can be made, and in such case
4596 // returns x in V, and k in SatK.
4597 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4598 SDValue &SatK)
4600 SDValue LHS = Op.getOperand(0);
4601 SDValue RHS = Op.getOperand(1);
4602 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4603 SDValue TrueVal = Op.getOperand(2);
4604 SDValue FalseVal = Op.getOperand(3);
4606 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4607 ? &RHS
4608 : nullptr;
4610 // No constant operation in comparison, early out
4611 if (!K)
4612 return false;
4614 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4615 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4616 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4618 // If the constant on left and right side, or variable on left and right,
4619 // does not match, early out
4620 if (*K != KTmp || V != VTmp)
4621 return false;
4623 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4624 SatK = *K;
4625 return true;
4628 return false;
4631 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4632 if (VT == MVT::f32)
4633 return !Subtarget->hasVFP2Base();
4634 if (VT == MVT::f64)
4635 return !Subtarget->hasFP64();
4636 if (VT == MVT::f16)
4637 return !Subtarget->hasFullFP16();
4638 return false;
4641 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4642 EVT VT = Op.getValueType();
4643 SDLoc dl(Op);
4645 // Try to convert two saturating conditional selects into a single SSAT
4646 SDValue SatValue;
4647 uint64_t SatConstant;
4648 bool SatUSat;
4649 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4650 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4651 if (SatUSat)
4652 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4653 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4654 else
4655 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4656 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4659 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4660 // into more efficient bit operations, which is possible when k is 0 or -1
4661 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4662 // single instructions. On Thumb the shift and the bit operation will be two
4663 // instructions.
4664 // Only allow this transformation on full-width (32-bit) operations
4665 SDValue LowerSatConstant;
4666 if (VT == MVT::i32 &&
4667 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4668 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4669 DAG.getConstant(31, dl, VT));
4670 if (isNullConstant(LowerSatConstant)) {
4671 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4672 DAG.getAllOnesConstant(dl, VT));
4673 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4674 } else if (isAllOnesConstant(LowerSatConstant))
4675 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4678 SDValue LHS = Op.getOperand(0);
4679 SDValue RHS = Op.getOperand(1);
4680 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4681 SDValue TrueVal = Op.getOperand(2);
4682 SDValue FalseVal = Op.getOperand(3);
4684 if (isUnsupportedFloatingType(LHS.getValueType())) {
4685 DAG.getTargetLoweringInfo().softenSetCCOperands(
4686 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4688 // If softenSetCCOperands only returned one value, we should compare it to
4689 // zero.
4690 if (!RHS.getNode()) {
4691 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4692 CC = ISD::SETNE;
4696 if (LHS.getValueType() == MVT::i32) {
4697 // Try to generate VSEL on ARMv8.
4698 // The VSEL instruction can't use all the usual ARM condition
4699 // codes: it only has two bits to select the condition code, so it's
4700 // constrained to use only GE, GT, VS and EQ.
4702 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4703 // swap the operands of the previous compare instruction (effectively
4704 // inverting the compare condition, swapping 'less' and 'greater') and
4705 // sometimes need to swap the operands to the VSEL (which inverts the
4706 // condition in the sense of firing whenever the previous condition didn't)
4707 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4708 TrueVal.getValueType() == MVT::f32 ||
4709 TrueVal.getValueType() == MVT::f64)) {
4710 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4711 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4712 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4713 CC = ISD::getSetCCInverse(CC, true);
4714 std::swap(TrueVal, FalseVal);
4718 SDValue ARMcc;
4719 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4720 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4721 // Choose GE over PL, which vsel does now support
4722 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4723 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4724 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4727 ARMCC::CondCodes CondCode, CondCode2;
4728 bool InvalidOnQNaN;
4729 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4731 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4732 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4733 // must use VSEL (limited condition codes), due to not having conditional f16
4734 // moves.
4735 if (Subtarget->hasFPARMv8Base() &&
4736 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4737 (TrueVal.getValueType() == MVT::f16 ||
4738 TrueVal.getValueType() == MVT::f32 ||
4739 TrueVal.getValueType() == MVT::f64)) {
4740 bool swpCmpOps = false;
4741 bool swpVselOps = false;
4742 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4744 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4745 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4746 if (swpCmpOps)
4747 std::swap(LHS, RHS);
4748 if (swpVselOps)
4749 std::swap(TrueVal, FalseVal);
4753 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4754 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4755 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4756 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4757 if (CondCode2 != ARMCC::AL) {
4758 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4759 // FIXME: Needs another CMP because flag can have but one use.
4760 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4761 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4763 return Result;
4766 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4767 /// to morph to an integer compare sequence.
4768 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4769 const ARMSubtarget *Subtarget) {
4770 SDNode *N = Op.getNode();
4771 if (!N->hasOneUse())
4772 // Otherwise it requires moving the value from fp to integer registers.
4773 return false;
4774 if (!N->getNumValues())
4775 return false;
4776 EVT VT = Op.getValueType();
4777 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4778 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4779 // vmrs are very slow, e.g. cortex-a8.
4780 return false;
4782 if (isFloatingPointZero(Op)) {
4783 SeenZero = true;
4784 return true;
4786 return ISD::isNormalLoad(N);
4789 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4790 if (isFloatingPointZero(Op))
4791 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4793 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4794 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4795 Ld->getPointerInfo(), Ld->getAlignment(),
4796 Ld->getMemOperand()->getFlags());
4798 llvm_unreachable("Unknown VFP cmp argument!");
4801 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4802 SDValue &RetVal1, SDValue &RetVal2) {
4803 SDLoc dl(Op);
4805 if (isFloatingPointZero(Op)) {
4806 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4807 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4808 return;
4811 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4812 SDValue Ptr = Ld->getBasePtr();
4813 RetVal1 =
4814 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4815 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4817 EVT PtrType = Ptr.getValueType();
4818 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4819 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4820 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4821 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4822 Ld->getPointerInfo().getWithOffset(4), NewAlign,
4823 Ld->getMemOperand()->getFlags());
4824 return;
4827 llvm_unreachable("Unknown VFP cmp argument!");
4830 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4831 /// f32 and even f64 comparisons to integer ones.
4832 SDValue
4833 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4834 SDValue Chain = Op.getOperand(0);
4835 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4836 SDValue LHS = Op.getOperand(2);
4837 SDValue RHS = Op.getOperand(3);
4838 SDValue Dest = Op.getOperand(4);
4839 SDLoc dl(Op);
4841 bool LHSSeenZero = false;
4842 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4843 bool RHSSeenZero = false;
4844 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4845 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4846 // If unsafe fp math optimization is enabled and there are no other uses of
4847 // the CMP operands, and the condition code is EQ or NE, we can optimize it
4848 // to an integer comparison.
4849 if (CC == ISD::SETOEQ)
4850 CC = ISD::SETEQ;
4851 else if (CC == ISD::SETUNE)
4852 CC = ISD::SETNE;
4854 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4855 SDValue ARMcc;
4856 if (LHS.getValueType() == MVT::f32) {
4857 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4858 bitcastf32Toi32(LHS, DAG), Mask);
4859 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4860 bitcastf32Toi32(RHS, DAG), Mask);
4861 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4862 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4863 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4864 Chain, Dest, ARMcc, CCR, Cmp);
4867 SDValue LHS1, LHS2;
4868 SDValue RHS1, RHS2;
4869 expandf64Toi32(LHS, DAG, LHS1, LHS2);
4870 expandf64Toi32(RHS, DAG, RHS1, RHS2);
4871 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4872 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4873 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4874 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4875 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4876 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4877 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4880 return SDValue();
4883 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4884 SDValue Chain = Op.getOperand(0);
4885 SDValue Cond = Op.getOperand(1);
4886 SDValue Dest = Op.getOperand(2);
4887 SDLoc dl(Op);
4889 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4890 // instruction.
4891 unsigned Opc = Cond.getOpcode();
4892 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4893 !Subtarget->isThumb1Only();
4894 if (Cond.getResNo() == 1 &&
4895 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4896 Opc == ISD::USUBO || OptimizeMul)) {
4897 // Only lower legal XALUO ops.
4898 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4899 return SDValue();
4901 // The actual operation with overflow check.
4902 SDValue Value, OverflowCmp;
4903 SDValue ARMcc;
4904 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4906 // Reverse the condition code.
4907 ARMCC::CondCodes CondCode =
4908 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4909 CondCode = ARMCC::getOppositeCondition(CondCode);
4910 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4911 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4913 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4914 OverflowCmp);
4917 return SDValue();
4920 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4921 SDValue Chain = Op.getOperand(0);
4922 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4923 SDValue LHS = Op.getOperand(2);
4924 SDValue RHS = Op.getOperand(3);
4925 SDValue Dest = Op.getOperand(4);
4926 SDLoc dl(Op);
4928 if (isUnsupportedFloatingType(LHS.getValueType())) {
4929 DAG.getTargetLoweringInfo().softenSetCCOperands(
4930 DAG, LHS.getValueType(), LHS, RHS, CC, dl);
4932 // If softenSetCCOperands only returned one value, we should compare it to
4933 // zero.
4934 if (!RHS.getNode()) {
4935 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4936 CC = ISD::SETNE;
4940 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4941 // instruction.
4942 unsigned Opc = LHS.getOpcode();
4943 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4944 !Subtarget->isThumb1Only();
4945 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4946 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4947 Opc == ISD::USUBO || OptimizeMul) &&
4948 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4949 // Only lower legal XALUO ops.
4950 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4951 return SDValue();
4953 // The actual operation with overflow check.
4954 SDValue Value, OverflowCmp;
4955 SDValue ARMcc;
4956 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4958 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4959 // Reverse the condition code.
4960 ARMCC::CondCodes CondCode =
4961 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4962 CondCode = ARMCC::getOppositeCondition(CondCode);
4963 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4965 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4967 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4968 OverflowCmp);
4971 if (LHS.getValueType() == MVT::i32) {
4972 SDValue ARMcc;
4973 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4974 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4975 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4976 Chain, Dest, ARMcc, CCR, Cmp);
4979 if (getTargetMachine().Options.UnsafeFPMath &&
4980 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4981 CC == ISD::SETNE || CC == ISD::SETUNE)) {
4982 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4983 return Result;
4986 ARMCC::CondCodes CondCode, CondCode2;
4987 bool InvalidOnQNaN;
4988 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4990 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4991 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4992 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4993 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4994 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4995 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4996 if (CondCode2 != ARMCC::AL) {
4997 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4998 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4999 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5001 return Res;
5004 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5005 SDValue Chain = Op.getOperand(0);
5006 SDValue Table = Op.getOperand(1);
5007 SDValue Index = Op.getOperand(2);
5008 SDLoc dl(Op);
5010 EVT PTy = getPointerTy(DAG.getDataLayout());
5011 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5012 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5013 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5014 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5015 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5016 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5017 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5018 // which does another jump to the destination. This also makes it easier
5019 // to translate it to TBB / TBH later (Thumb2 only).
5020 // FIXME: This might not work if the function is extremely large.
5021 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5022 Addr, Op.getOperand(2), JTI);
5024 if (isPositionIndependent() || Subtarget->isROPI()) {
5025 Addr =
5026 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5027 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5028 Chain = Addr.getValue(1);
5029 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5030 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5031 } else {
5032 Addr =
5033 DAG.getLoad(PTy, dl, Chain, Addr,
5034 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5035 Chain = Addr.getValue(1);
5036 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5040 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5041 EVT VT = Op.getValueType();
5042 SDLoc dl(Op);
5044 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5045 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5046 return Op;
5047 return DAG.UnrollVectorOp(Op.getNode());
5050 const bool HasFullFP16 =
5051 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5053 EVT NewTy;
5054 const EVT OpTy = Op.getOperand(0).getValueType();
5055 if (OpTy == MVT::v4f32)
5056 NewTy = MVT::v4i32;
5057 else if (OpTy == MVT::v4f16 && HasFullFP16)
5058 NewTy = MVT::v4i16;
5059 else if (OpTy == MVT::v8f16 && HasFullFP16)
5060 NewTy = MVT::v8i16;
5061 else
5062 llvm_unreachable("Invalid type for custom lowering!");
5064 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5065 return DAG.UnrollVectorOp(Op.getNode());
5067 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5068 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5071 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5072 EVT VT = Op.getValueType();
5073 if (VT.isVector())
5074 return LowerVectorFP_TO_INT(Op, DAG);
5075 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5076 RTLIB::Libcall LC;
5077 if (Op.getOpcode() == ISD::FP_TO_SINT)
5078 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5079 Op.getValueType());
5080 else
5081 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5082 Op.getValueType());
5083 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5084 /*isSigned*/ false, SDLoc(Op)).first;
5087 return Op;
5090 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5091 EVT VT = Op.getValueType();
5092 SDLoc dl(Op);
5094 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5095 if (VT.getVectorElementType() == MVT::f32)
5096 return Op;
5097 return DAG.UnrollVectorOp(Op.getNode());
5100 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5101 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5102 "Invalid type for custom lowering!");
5104 const bool HasFullFP16 =
5105 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5107 EVT DestVecType;
5108 if (VT == MVT::v4f32)
5109 DestVecType = MVT::v4i32;
5110 else if (VT == MVT::v4f16 && HasFullFP16)
5111 DestVecType = MVT::v4i16;
5112 else if (VT == MVT::v8f16 && HasFullFP16)
5113 DestVecType = MVT::v8i16;
5114 else
5115 return DAG.UnrollVectorOp(Op.getNode());
5117 unsigned CastOpc;
5118 unsigned Opc;
5119 switch (Op.getOpcode()) {
5120 default: llvm_unreachable("Invalid opcode!");
5121 case ISD::SINT_TO_FP:
5122 CastOpc = ISD::SIGN_EXTEND;
5123 Opc = ISD::SINT_TO_FP;
5124 break;
5125 case ISD::UINT_TO_FP:
5126 CastOpc = ISD::ZERO_EXTEND;
5127 Opc = ISD::UINT_TO_FP;
5128 break;
5131 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5132 return DAG.getNode(Opc, dl, VT, Op);
5135 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5136 EVT VT = Op.getValueType();
5137 if (VT.isVector())
5138 return LowerVectorINT_TO_FP(Op, DAG);
5139 if (isUnsupportedFloatingType(VT)) {
5140 RTLIB::Libcall LC;
5141 if (Op.getOpcode() == ISD::SINT_TO_FP)
5142 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5143 Op.getValueType());
5144 else
5145 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5146 Op.getValueType());
5147 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5148 /*isSigned*/ false, SDLoc(Op)).first;
5151 return Op;
5154 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5155 // Implement fcopysign with a fabs and a conditional fneg.
5156 SDValue Tmp0 = Op.getOperand(0);
5157 SDValue Tmp1 = Op.getOperand(1);
5158 SDLoc dl(Op);
5159 EVT VT = Op.getValueType();
5160 EVT SrcVT = Tmp1.getValueType();
5161 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5162 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5163 bool UseNEON = !InGPR && Subtarget->hasNEON();
5165 if (UseNEON) {
5166 // Use VBSL to copy the sign bit.
5167 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5168 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5169 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5170 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5171 if (VT == MVT::f64)
5172 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5173 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5174 DAG.getConstant(32, dl, MVT::i32));
5175 else /*if (VT == MVT::f32)*/
5176 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5177 if (SrcVT == MVT::f32) {
5178 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5179 if (VT == MVT::f64)
5180 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5181 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5182 DAG.getConstant(32, dl, MVT::i32));
5183 } else if (VT == MVT::f32)
5184 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5185 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5186 DAG.getConstant(32, dl, MVT::i32));
5187 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5188 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5190 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5191 dl, MVT::i32);
5192 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5193 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5194 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5196 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5197 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5198 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5199 if (VT == MVT::f32) {
5200 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5201 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5202 DAG.getConstant(0, dl, MVT::i32));
5203 } else {
5204 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5207 return Res;
5210 // Bitcast operand 1 to i32.
5211 if (SrcVT == MVT::f64)
5212 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5213 Tmp1).getValue(1);
5214 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5216 // Or in the signbit with integer operations.
5217 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5218 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5219 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5220 if (VT == MVT::f32) {
5221 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5222 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5223 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5224 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5227 // f64: Or the high part with signbit and then combine two parts.
5228 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5229 Tmp0);
5230 SDValue Lo = Tmp0.getValue(0);
5231 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5232 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5233 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5236 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5237 MachineFunction &MF = DAG.getMachineFunction();
5238 MachineFrameInfo &MFI = MF.getFrameInfo();
5239 MFI.setReturnAddressIsTaken(true);
5241 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5242 return SDValue();
5244 EVT VT = Op.getValueType();
5245 SDLoc dl(Op);
5246 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5247 if (Depth) {
5248 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5249 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5250 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5251 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5252 MachinePointerInfo());
5255 // Return LR, which contains the return address. Mark it an implicit live-in.
5256 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5257 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5260 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5261 const ARMBaseRegisterInfo &ARI =
5262 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5263 MachineFunction &MF = DAG.getMachineFunction();
5264 MachineFrameInfo &MFI = MF.getFrameInfo();
5265 MFI.setFrameAddressIsTaken(true);
5267 EVT VT = Op.getValueType();
5268 SDLoc dl(Op); // FIXME probably not meaningful
5269 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5270 unsigned FrameReg = ARI.getFrameRegister(MF);
5271 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5272 while (Depth--)
5273 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5274 MachinePointerInfo());
5275 return FrameAddr;
5278 // FIXME? Maybe this could be a TableGen attribute on some registers and
5279 // this table could be generated automatically from RegInfo.
5280 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5281 SelectionDAG &DAG) const {
5282 unsigned Reg = StringSwitch<unsigned>(RegName)
5283 .Case("sp", ARM::SP)
5284 .Default(0);
5285 if (Reg)
5286 return Reg;
5287 report_fatal_error(Twine("Invalid register name \""
5288 + StringRef(RegName) + "\"."));
5291 // Result is 64 bit value so split into two 32 bit values and return as a
5292 // pair of values.
5293 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5294 SelectionDAG &DAG) {
5295 SDLoc DL(N);
5297 // This function is only supposed to be called for i64 type destination.
5298 assert(N->getValueType(0) == MVT::i64
5299 && "ExpandREAD_REGISTER called for non-i64 type result.");
5301 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5302 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5303 N->getOperand(0),
5304 N->getOperand(1));
5306 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5307 Read.getValue(1)));
5308 Results.push_back(Read.getOperand(0));
5311 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5312 /// When \p DstVT, the destination type of \p BC, is on the vector
5313 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5314 /// it might be possible to combine them, such that everything stays on the
5315 /// vector register bank.
5316 /// \p return The node that would replace \p BT, if the combine
5317 /// is possible.
5318 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5319 SelectionDAG &DAG) {
5320 SDValue Op = BC->getOperand(0);
5321 EVT DstVT = BC->getValueType(0);
5323 // The only vector instruction that can produce a scalar (remember,
5324 // since the bitcast was about to be turned into VMOVDRR, the source
5325 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5326 // Moreover, we can do this combine only if there is one use.
5327 // Finally, if the destination type is not a vector, there is not
5328 // much point on forcing everything on the vector bank.
5329 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5330 !Op.hasOneUse())
5331 return SDValue();
5333 // If the index is not constant, we will introduce an additional
5334 // multiply that will stick.
5335 // Give up in that case.
5336 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5337 if (!Index)
5338 return SDValue();
5339 unsigned DstNumElt = DstVT.getVectorNumElements();
5341 // Compute the new index.
5342 const APInt &APIntIndex = Index->getAPIntValue();
5343 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5344 NewIndex *= APIntIndex;
5345 // Check if the new constant index fits into i32.
5346 if (NewIndex.getBitWidth() > 32)
5347 return SDValue();
5349 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5350 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5351 SDLoc dl(Op);
5352 SDValue ExtractSrc = Op.getOperand(0);
5353 EVT VecVT = EVT::getVectorVT(
5354 *DAG.getContext(), DstVT.getScalarType(),
5355 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5356 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5357 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5358 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5361 /// ExpandBITCAST - If the target supports VFP, this function is called to
5362 /// expand a bit convert where either the source or destination type is i64 to
5363 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5364 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5365 /// vectors), since the legalizer won't know what to do with that.
5366 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5367 const ARMSubtarget *Subtarget) {
5368 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5369 SDLoc dl(N);
5370 SDValue Op = N->getOperand(0);
5372 // This function is only supposed to be called for i64 types, either as the
5373 // source or destination of the bit convert.
5374 EVT SrcVT = Op.getValueType();
5375 EVT DstVT = N->getValueType(0);
5376 const bool HasFullFP16 = Subtarget->hasFullFP16();
5378 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5379 // FullFP16: half values are passed in S-registers, and we don't
5380 // need any of the bitcast and moves:
5382 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5383 // t5: i32 = bitcast t2
5384 // t18: f16 = ARMISD::VMOVhr t5
5385 if (Op.getOpcode() != ISD::CopyFromReg ||
5386 Op.getValueType() != MVT::f32)
5387 return SDValue();
5389 auto Move = N->use_begin();
5390 if (Move->getOpcode() != ARMISD::VMOVhr)
5391 return SDValue();
5393 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5394 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5395 DAG.ReplaceAllUsesWith(*Move, &Copy);
5396 return Copy;
5399 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5400 if (!HasFullFP16)
5401 return SDValue();
5402 // SoftFP: read half-precision arguments:
5404 // t2: i32,ch = ...
5405 // t7: i16 = truncate t2 <~~~~ Op
5406 // t8: f16 = bitcast t7 <~~~~ N
5408 if (Op.getOperand(0).getValueType() == MVT::i32)
5409 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5410 MVT::f16, Op.getOperand(0));
5412 return SDValue();
5415 // Half-precision return values
5416 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5417 if (!HasFullFP16)
5418 return SDValue();
5420 // t11: f16 = fadd t8, t10
5421 // t12: i16 = bitcast t11 <~~~ SDNode N
5422 // t13: i32 = zero_extend t12
5423 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5424 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5426 // transform this into:
5428 // t20: i32 = ARMISD::VMOVrh t11
5429 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5431 auto ZeroExtend = N->use_begin();
5432 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5433 ZeroExtend->getValueType(0) != MVT::i32)
5434 return SDValue();
5436 auto Copy = ZeroExtend->use_begin();
5437 if (Copy->getOpcode() == ISD::CopyToReg &&
5438 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5439 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5440 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5441 return Cvt;
5443 return SDValue();
5446 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5447 return SDValue();
5449 // Turn i64->f64 into VMOVDRR.
5450 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5451 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5452 // if we can combine the bitcast with its source.
5453 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5454 return Val;
5456 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5457 DAG.getConstant(0, dl, MVT::i32));
5458 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5459 DAG.getConstant(1, dl, MVT::i32));
5460 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5461 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5464 // Turn f64->i64 into VMOVRRD.
5465 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5466 SDValue Cvt;
5467 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5468 SrcVT.getVectorNumElements() > 1)
5469 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5470 DAG.getVTList(MVT::i32, MVT::i32),
5471 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5472 else
5473 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5474 DAG.getVTList(MVT::i32, MVT::i32), Op);
5475 // Merge the pieces into a single i64 value.
5476 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5479 return SDValue();
5482 /// getZeroVector - Returns a vector of specified type with all zero elements.
5483 /// Zero vectors are used to represent vector negation and in those cases
5484 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5485 /// not support i64 elements, so sometimes the zero vectors will need to be
5486 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5487 /// zero vector.
5488 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5489 assert(VT.isVector() && "Expected a vector type");
5490 // The canonical modified immediate encoding of a zero vector is....0!
5491 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5492 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5493 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5494 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5497 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5498 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5499 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5500 SelectionDAG &DAG) const {
5501 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5502 EVT VT = Op.getValueType();
5503 unsigned VTBits = VT.getSizeInBits();
5504 SDLoc dl(Op);
5505 SDValue ShOpLo = Op.getOperand(0);
5506 SDValue ShOpHi = Op.getOperand(1);
5507 SDValue ShAmt = Op.getOperand(2);
5508 SDValue ARMcc;
5509 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5510 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5512 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5514 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5515 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5516 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5517 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5518 DAG.getConstant(VTBits, dl, MVT::i32));
5519 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5520 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5521 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5522 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5523 ISD::SETGE, ARMcc, DAG, dl);
5524 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5525 ARMcc, CCR, CmpLo);
5527 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5528 SDValue HiBigShift = Opc == ISD::SRA
5529 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5530 DAG.getConstant(VTBits - 1, dl, VT))
5531 : DAG.getConstant(0, dl, VT);
5532 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5533 ISD::SETGE, ARMcc, DAG, dl);
5534 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5535 ARMcc, CCR, CmpHi);
5537 SDValue Ops[2] = { Lo, Hi };
5538 return DAG.getMergeValues(Ops, dl);
5541 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5542 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5543 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5544 SelectionDAG &DAG) const {
5545 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5546 EVT VT = Op.getValueType();
5547 unsigned VTBits = VT.getSizeInBits();
5548 SDLoc dl(Op);
5549 SDValue ShOpLo = Op.getOperand(0);
5550 SDValue ShOpHi = Op.getOperand(1);
5551 SDValue ShAmt = Op.getOperand(2);
5552 SDValue ARMcc;
5553 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5555 assert(Op.getOpcode() == ISD::SHL_PARTS);
5556 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5557 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5558 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5559 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5560 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5562 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5563 DAG.getConstant(VTBits, dl, MVT::i32));
5564 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5565 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5566 ISD::SETGE, ARMcc, DAG, dl);
5567 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5568 ARMcc, CCR, CmpHi);
5570 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5571 ISD::SETGE, ARMcc, DAG, dl);
5572 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5573 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5574 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5576 SDValue Ops[2] = { Lo, Hi };
5577 return DAG.getMergeValues(Ops, dl);
5580 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5581 SelectionDAG &DAG) const {
5582 // The rounding mode is in bits 23:22 of the FPSCR.
5583 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5584 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5585 // so that the shift + and get folded into a bitfield extract.
5586 SDLoc dl(Op);
5587 SDValue Ops[] = { DAG.getEntryNode(),
5588 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5590 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5591 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5592 DAG.getConstant(1U << 22, dl, MVT::i32));
5593 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5594 DAG.getConstant(22, dl, MVT::i32));
5595 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5596 DAG.getConstant(3, dl, MVT::i32));
5599 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5600 const ARMSubtarget *ST) {
5601 SDLoc dl(N);
5602 EVT VT = N->getValueType(0);
5603 if (VT.isVector()) {
5604 assert(ST->hasNEON());
5606 // Compute the least significant set bit: LSB = X & -X
5607 SDValue X = N->getOperand(0);
5608 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5609 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5611 EVT ElemTy = VT.getVectorElementType();
5613 if (ElemTy == MVT::i8) {
5614 // Compute with: cttz(x) = ctpop(lsb - 1)
5615 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5616 DAG.getTargetConstant(1, dl, ElemTy));
5617 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5618 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5621 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5622 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5623 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5624 unsigned NumBits = ElemTy.getSizeInBits();
5625 SDValue WidthMinus1 =
5626 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5627 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5628 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5629 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5632 // Compute with: cttz(x) = ctpop(lsb - 1)
5634 // Compute LSB - 1.
5635 SDValue Bits;
5636 if (ElemTy == MVT::i64) {
5637 // Load constant 0xffff'ffff'ffff'ffff to register.
5638 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5639 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5640 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5641 } else {
5642 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5643 DAG.getTargetConstant(1, dl, ElemTy));
5644 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5646 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5649 if (!ST->hasV6T2Ops())
5650 return SDValue();
5652 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5653 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5656 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5657 const ARMSubtarget *ST) {
5658 EVT VT = N->getValueType(0);
5659 SDLoc DL(N);
5661 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5662 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5663 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5664 "Unexpected type for custom ctpop lowering");
5666 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5667 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5668 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5669 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5671 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5672 unsigned EltSize = 8;
5673 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5674 while (EltSize != VT.getScalarSizeInBits()) {
5675 SmallVector<SDValue, 8> Ops;
5676 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5677 TLI.getPointerTy(DAG.getDataLayout())));
5678 Ops.push_back(Res);
5680 EltSize *= 2;
5681 NumElts /= 2;
5682 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5683 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5686 return Res;
5689 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5690 /// operand of a vector shift operation, where all the elements of the
5691 /// build_vector must have the same constant integer value.
5692 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5693 // Ignore bit_converts.
5694 while (Op.getOpcode() == ISD::BITCAST)
5695 Op = Op.getOperand(0);
5696 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5697 APInt SplatBits, SplatUndef;
5698 unsigned SplatBitSize;
5699 bool HasAnyUndefs;
5700 if (!BVN ||
5701 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5702 ElementBits) ||
5703 SplatBitSize > ElementBits)
5704 return false;
5705 Cnt = SplatBits.getSExtValue();
5706 return true;
5709 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5710 /// operand of a vector shift left operation. That value must be in the range:
5711 /// 0 <= Value < ElementBits for a left shift; or
5712 /// 0 <= Value <= ElementBits for a long left shift.
5713 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5714 assert(VT.isVector() && "vector shift count is not a vector type");
5715 int64_t ElementBits = VT.getScalarSizeInBits();
5716 if (!getVShiftImm(Op, ElementBits, Cnt))
5717 return false;
5718 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5721 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5722 /// operand of a vector shift right operation. For a shift opcode, the value
5723 /// is positive, but for an intrinsic the value count must be negative. The
5724 /// absolute value must be in the range:
5725 /// 1 <= |Value| <= ElementBits for a right shift; or
5726 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5727 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5728 int64_t &Cnt) {
5729 assert(VT.isVector() && "vector shift count is not a vector type");
5730 int64_t ElementBits = VT.getScalarSizeInBits();
5731 if (!getVShiftImm(Op, ElementBits, Cnt))
5732 return false;
5733 if (!isIntrinsic)
5734 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5735 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5736 Cnt = -Cnt;
5737 return true;
5739 return false;
5742 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5743 const ARMSubtarget *ST) {
5744 EVT VT = N->getValueType(0);
5745 SDLoc dl(N);
5746 int64_t Cnt;
5748 if (!VT.isVector())
5749 return SDValue();
5751 // We essentially have two forms here. Shift by an immediate and shift by a
5752 // vector register (there are also shift by a gpr, but that is just handled
5753 // with a tablegen pattern). We cannot easily match shift by an immediate in
5754 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5755 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5756 // signed or unsigned, and a negative shift indicates a shift right).
5757 if (N->getOpcode() == ISD::SHL) {
5758 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5759 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5760 DAG.getConstant(Cnt, dl, MVT::i32));
5761 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5762 N->getOperand(1));
5765 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5766 "unexpected vector shift opcode");
5768 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5769 unsigned VShiftOpc =
5770 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5771 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5772 DAG.getConstant(Cnt, dl, MVT::i32));
5775 // Other right shifts we don't have operations for (we use a shift left by a
5776 // negative number).
5777 EVT ShiftVT = N->getOperand(1).getValueType();
5778 SDValue NegatedCount = DAG.getNode(
5779 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5780 unsigned VShiftOpc =
5781 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5782 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5785 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5786 const ARMSubtarget *ST) {
5787 EVT VT = N->getValueType(0);
5788 SDLoc dl(N);
5790 // We can get here for a node like i32 = ISD::SHL i32, i64
5791 if (VT != MVT::i64)
5792 return SDValue();
5794 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5795 N->getOpcode() == ISD::SHL) &&
5796 "Unknown shift to lower!");
5798 unsigned ShOpc = N->getOpcode();
5799 if (ST->hasMVEIntegerOps()) {
5800 SDValue ShAmt = N->getOperand(1);
5801 unsigned ShPartsOpc = ARMISD::LSLL;
5802 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5804 // If the shift amount is greater than 32 then do the default optimisation
5805 if (Con && Con->getZExtValue() > 32)
5806 return SDValue();
5808 // Extract the lower 32 bits of the shift amount if it's an i64
5809 if (ShAmt->getValueType(0) == MVT::i64)
5810 ShAmt = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, ShAmt,
5811 DAG.getConstant(0, dl, MVT::i32));
5813 if (ShOpc == ISD::SRL) {
5814 if (!Con)
5815 // There is no t2LSRLr instruction so negate and perform an lsll if the
5816 // shift amount is in a register, emulating a right shift.
5817 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5818 DAG.getConstant(0, dl, MVT::i32), ShAmt);
5819 else
5820 // Else generate an lsrl on the immediate shift amount
5821 ShPartsOpc = ARMISD::LSRL;
5822 } else if (ShOpc == ISD::SRA)
5823 ShPartsOpc = ARMISD::ASRL;
5825 // Lower 32 bits of the destination/source
5826 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5827 DAG.getConstant(0, dl, MVT::i32));
5828 // Upper 32 bits of the destination/source
5829 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5830 DAG.getConstant(1, dl, MVT::i32));
5832 // Generate the shift operation as computed above
5833 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
5834 ShAmt);
5835 // The upper 32 bits come from the second return value of lsll
5836 Hi = SDValue(Lo.getNode(), 1);
5837 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5840 // We only lower SRA, SRL of 1 here, all others use generic lowering.
5841 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
5842 return SDValue();
5844 // If we are in thumb mode, we don't have RRX.
5845 if (ST->isThumb1Only())
5846 return SDValue();
5848 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
5849 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5850 DAG.getConstant(0, dl, MVT::i32));
5851 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5852 DAG.getConstant(1, dl, MVT::i32));
5854 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5855 // captures the result into a carry flag.
5856 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5857 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5859 // The low part is an ARMISD::RRX operand, which shifts the carry in.
5860 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5862 // Merge the pieces into a single i64 value.
5863 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5866 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
5867 const ARMSubtarget *ST) {
5868 bool Invert = false;
5869 bool Swap = false;
5870 unsigned Opc = ARMCC::AL;
5872 SDValue Op0 = Op.getOperand(0);
5873 SDValue Op1 = Op.getOperand(1);
5874 SDValue CC = Op.getOperand(2);
5875 EVT VT = Op.getValueType();
5876 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5877 SDLoc dl(Op);
5879 EVT CmpVT;
5880 if (ST->hasNEON())
5881 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5882 else {
5883 assert(ST->hasMVEIntegerOps() &&
5884 "No hardware support for integer vector comparison!");
5886 if (Op.getValueType().getVectorElementType() != MVT::i1)
5887 return SDValue();
5889 // Make sure we expand floating point setcc to scalar if we do not have
5890 // mve.fp, so that we can handle them from there.
5891 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
5892 return SDValue();
5894 CmpVT = VT;
5897 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5898 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5899 // Special-case integer 64-bit equality comparisons. They aren't legal,
5900 // but they can be lowered with a few vector instructions.
5901 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5902 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5903 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5904 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5905 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5906 DAG.getCondCode(ISD::SETEQ));
5907 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5908 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5909 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5910 if (SetCCOpcode == ISD::SETNE)
5911 Merged = DAG.getNOT(dl, Merged, CmpVT);
5912 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5913 return Merged;
5916 if (CmpVT.getVectorElementType() == MVT::i64)
5917 // 64-bit comparisons are not legal in general.
5918 return SDValue();
5920 if (Op1.getValueType().isFloatingPoint()) {
5921 switch (SetCCOpcode) {
5922 default: llvm_unreachable("Illegal FP comparison");
5923 case ISD::SETUNE:
5924 case ISD::SETNE:
5925 if (ST->hasMVEFloatOps()) {
5926 Opc = ARMCC::NE; break;
5927 } else {
5928 Invert = true; LLVM_FALLTHROUGH;
5930 case ISD::SETOEQ:
5931 case ISD::SETEQ: Opc = ARMCC::EQ; break;
5932 case ISD::SETOLT:
5933 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5934 case ISD::SETOGT:
5935 case ISD::SETGT: Opc = ARMCC::GT; break;
5936 case ISD::SETOLE:
5937 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5938 case ISD::SETOGE:
5939 case ISD::SETGE: Opc = ARMCC::GE; break;
5940 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5941 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
5942 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5943 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
5944 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5945 case ISD::SETONE: {
5946 // Expand this to (OLT | OGT).
5947 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
5948 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
5949 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
5950 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
5951 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
5952 if (Invert)
5953 Result = DAG.getNOT(dl, Result, VT);
5954 return Result;
5956 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
5957 case ISD::SETO: {
5958 // Expand this to (OLT | OGE).
5959 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
5960 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
5961 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
5962 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
5963 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
5964 if (Invert)
5965 Result = DAG.getNOT(dl, Result, VT);
5966 return Result;
5969 } else {
5970 // Integer comparisons.
5971 switch (SetCCOpcode) {
5972 default: llvm_unreachable("Illegal integer comparison");
5973 case ISD::SETNE:
5974 if (ST->hasMVEIntegerOps()) {
5975 Opc = ARMCC::NE; break;
5976 } else {
5977 Invert = true; LLVM_FALLTHROUGH;
5979 case ISD::SETEQ: Opc = ARMCC::EQ; break;
5980 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5981 case ISD::SETGT: Opc = ARMCC::GT; break;
5982 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
5983 case ISD::SETGE: Opc = ARMCC::GE; break;
5984 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5985 case ISD::SETUGT: Opc = ARMCC::HI; break;
5986 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5987 case ISD::SETUGE: Opc = ARMCC::HS; break;
5990 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5991 if (ST->hasNEON() && Opc == ARMCC::EQ) {
5992 SDValue AndOp;
5993 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5994 AndOp = Op0;
5995 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5996 AndOp = Op1;
5998 // Ignore bitconvert.
5999 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6000 AndOp = AndOp.getOperand(0);
6002 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6003 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6004 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6005 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6006 if (!Invert)
6007 Result = DAG.getNOT(dl, Result, VT);
6008 return Result;
6013 if (Swap)
6014 std::swap(Op0, Op1);
6016 // If one of the operands is a constant vector zero, attempt to fold the
6017 // comparison to a specialized compare-against-zero form.
6018 SDValue SingleOp;
6019 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6020 SingleOp = Op0;
6021 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6022 if (Opc == ARMCC::GE)
6023 Opc = ARMCC::LE;
6024 else if (Opc == ARMCC::GT)
6025 Opc = ARMCC::LT;
6026 SingleOp = Op1;
6029 SDValue Result;
6030 if (SingleOp.getNode()) {
6031 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6032 DAG.getConstant(Opc, dl, MVT::i32));
6033 } else {
6034 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6035 DAG.getConstant(Opc, dl, MVT::i32));
6038 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6040 if (Invert)
6041 Result = DAG.getNOT(dl, Result, VT);
6043 return Result;
6046 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6047 SDValue LHS = Op.getOperand(0);
6048 SDValue RHS = Op.getOperand(1);
6049 SDValue Carry = Op.getOperand(2);
6050 SDValue Cond = Op.getOperand(3);
6051 SDLoc DL(Op);
6053 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6055 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6056 // have to invert the carry first.
6057 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6058 DAG.getConstant(1, DL, MVT::i32), Carry);
6059 // This converts the boolean value carry into the carry flag.
6060 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6062 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6063 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6065 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6066 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6067 SDValue ARMcc = DAG.getConstant(
6068 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6069 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6070 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6071 Cmp.getValue(1), SDValue());
6072 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6073 CCR, Chain.getValue(1));
6076 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6077 /// valid vector constant for a NEON or MVE instruction with a "modified
6078 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6079 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6080 unsigned SplatBitSize, SelectionDAG &DAG,
6081 const SDLoc &dl, EVT &VT, bool is128Bits,
6082 VMOVModImmType type) {
6083 unsigned OpCmode, Imm;
6085 // SplatBitSize is set to the smallest size that splats the vector, so a
6086 // zero vector will always have SplatBitSize == 8. However, NEON modified
6087 // immediate instructions others than VMOV do not support the 8-bit encoding
6088 // of a zero vector, and the default encoding of zero is supposed to be the
6089 // 32-bit version.
6090 if (SplatBits == 0)
6091 SplatBitSize = 32;
6093 switch (SplatBitSize) {
6094 case 8:
6095 if (type != VMOVModImm)
6096 return SDValue();
6097 // Any 1-byte value is OK. Op=0, Cmode=1110.
6098 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6099 OpCmode = 0xe;
6100 Imm = SplatBits;
6101 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6102 break;
6104 case 16:
6105 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6106 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6107 if ((SplatBits & ~0xff) == 0) {
6108 // Value = 0x00nn: Op=x, Cmode=100x.
6109 OpCmode = 0x8;
6110 Imm = SplatBits;
6111 break;
6113 if ((SplatBits & ~0xff00) == 0) {
6114 // Value = 0xnn00: Op=x, Cmode=101x.
6115 OpCmode = 0xa;
6116 Imm = SplatBits >> 8;
6117 break;
6119 return SDValue();
6121 case 32:
6122 // NEON's 32-bit VMOV supports splat values where:
6123 // * only one byte is nonzero, or
6124 // * the least significant byte is 0xff and the second byte is nonzero, or
6125 // * the least significant 2 bytes are 0xff and the third is nonzero.
6126 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6127 if ((SplatBits & ~0xff) == 0) {
6128 // Value = 0x000000nn: Op=x, Cmode=000x.
6129 OpCmode = 0;
6130 Imm = SplatBits;
6131 break;
6133 if ((SplatBits & ~0xff00) == 0) {
6134 // Value = 0x0000nn00: Op=x, Cmode=001x.
6135 OpCmode = 0x2;
6136 Imm = SplatBits >> 8;
6137 break;
6139 if ((SplatBits & ~0xff0000) == 0) {
6140 // Value = 0x00nn0000: Op=x, Cmode=010x.
6141 OpCmode = 0x4;
6142 Imm = SplatBits >> 16;
6143 break;
6145 if ((SplatBits & ~0xff000000) == 0) {
6146 // Value = 0xnn000000: Op=x, Cmode=011x.
6147 OpCmode = 0x6;
6148 Imm = SplatBits >> 24;
6149 break;
6152 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6153 if (type == OtherModImm) return SDValue();
6155 if ((SplatBits & ~0xffff) == 0 &&
6156 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6157 // Value = 0x0000nnff: Op=x, Cmode=1100.
6158 OpCmode = 0xc;
6159 Imm = SplatBits >> 8;
6160 break;
6163 // cmode == 0b1101 is not supported for MVE VMVN
6164 if (type == MVEVMVNModImm)
6165 return SDValue();
6167 if ((SplatBits & ~0xffffff) == 0 &&
6168 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6169 // Value = 0x00nnffff: Op=x, Cmode=1101.
6170 OpCmode = 0xd;
6171 Imm = SplatBits >> 16;
6172 break;
6175 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6176 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6177 // VMOV.I32. A (very) minor optimization would be to replicate the value
6178 // and fall through here to test for a valid 64-bit splat. But, then the
6179 // caller would also need to check and handle the change in size.
6180 return SDValue();
6182 case 64: {
6183 if (type != VMOVModImm)
6184 return SDValue();
6185 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6186 uint64_t BitMask = 0xff;
6187 uint64_t Val = 0;
6188 unsigned ImmMask = 1;
6189 Imm = 0;
6190 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6191 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6192 Val |= BitMask;
6193 Imm |= ImmMask;
6194 } else if ((SplatBits & BitMask) != 0) {
6195 return SDValue();
6197 BitMask <<= 8;
6198 ImmMask <<= 1;
6201 if (DAG.getDataLayout().isBigEndian())
6202 // swap higher and lower 32 bit word
6203 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6205 // Op=1, Cmode=1110.
6206 OpCmode = 0x1e;
6207 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6208 break;
6211 default:
6212 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6215 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6216 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6219 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6220 const ARMSubtarget *ST) const {
6221 EVT VT = Op.getValueType();
6222 bool IsDouble = (VT == MVT::f64);
6223 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6224 const APFloat &FPVal = CFP->getValueAPF();
6226 // Prevent floating-point constants from using literal loads
6227 // when execute-only is enabled.
6228 if (ST->genExecuteOnly()) {
6229 // If we can represent the constant as an immediate, don't lower it
6230 if (isFPImmLegal(FPVal, VT))
6231 return Op;
6232 // Otherwise, construct as integer, and move to float register
6233 APInt INTVal = FPVal.bitcastToAPInt();
6234 SDLoc DL(CFP);
6235 switch (VT.getSimpleVT().SimpleTy) {
6236 default:
6237 llvm_unreachable("Unknown floating point type!");
6238 break;
6239 case MVT::f64: {
6240 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6241 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6242 if (!ST->isLittle())
6243 std::swap(Lo, Hi);
6244 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6246 case MVT::f32:
6247 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6248 DAG.getConstant(INTVal, DL, MVT::i32));
6252 if (!ST->hasVFP3Base())
6253 return SDValue();
6255 // Use the default (constant pool) lowering for double constants when we have
6256 // an SP-only FPU
6257 if (IsDouble && !Subtarget->hasFP64())
6258 return SDValue();
6260 // Try splatting with a VMOV.f32...
6261 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6263 if (ImmVal != -1) {
6264 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6265 // We have code in place to select a valid ConstantFP already, no need to
6266 // do any mangling.
6267 return Op;
6270 // It's a float and we are trying to use NEON operations where
6271 // possible. Lower it to a splat followed by an extract.
6272 SDLoc DL(Op);
6273 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6274 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6275 NewVal);
6276 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6277 DAG.getConstant(0, DL, MVT::i32));
6280 // The rest of our options are NEON only, make sure that's allowed before
6281 // proceeding..
6282 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6283 return SDValue();
6285 EVT VMovVT;
6286 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6288 // It wouldn't really be worth bothering for doubles except for one very
6289 // important value, which does happen to match: 0.0. So make sure we don't do
6290 // anything stupid.
6291 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6292 return SDValue();
6294 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6295 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6296 VMovVT, false, VMOVModImm);
6297 if (NewVal != SDValue()) {
6298 SDLoc DL(Op);
6299 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6300 NewVal);
6301 if (IsDouble)
6302 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6304 // It's a float: cast and extract a vector element.
6305 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6306 VecConstant);
6307 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6308 DAG.getConstant(0, DL, MVT::i32));
6311 // Finally, try a VMVN.i32
6312 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6313 false, VMVNModImm);
6314 if (NewVal != SDValue()) {
6315 SDLoc DL(Op);
6316 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6318 if (IsDouble)
6319 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6321 // It's a float: cast and extract a vector element.
6322 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6323 VecConstant);
6324 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6325 DAG.getConstant(0, DL, MVT::i32));
6328 return SDValue();
6331 // check if an VEXT instruction can handle the shuffle mask when the
6332 // vector sources of the shuffle are the same.
6333 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6334 unsigned NumElts = VT.getVectorNumElements();
6336 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6337 if (M[0] < 0)
6338 return false;
6340 Imm = M[0];
6342 // If this is a VEXT shuffle, the immediate value is the index of the first
6343 // element. The other shuffle indices must be the successive elements after
6344 // the first one.
6345 unsigned ExpectedElt = Imm;
6346 for (unsigned i = 1; i < NumElts; ++i) {
6347 // Increment the expected index. If it wraps around, just follow it
6348 // back to index zero and keep going.
6349 ++ExpectedElt;
6350 if (ExpectedElt == NumElts)
6351 ExpectedElt = 0;
6353 if (M[i] < 0) continue; // ignore UNDEF indices
6354 if (ExpectedElt != static_cast<unsigned>(M[i]))
6355 return false;
6358 return true;
6361 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6362 bool &ReverseVEXT, unsigned &Imm) {
6363 unsigned NumElts = VT.getVectorNumElements();
6364 ReverseVEXT = false;
6366 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6367 if (M[0] < 0)
6368 return false;
6370 Imm = M[0];
6372 // If this is a VEXT shuffle, the immediate value is the index of the first
6373 // element. The other shuffle indices must be the successive elements after
6374 // the first one.
6375 unsigned ExpectedElt = Imm;
6376 for (unsigned i = 1; i < NumElts; ++i) {
6377 // Increment the expected index. If it wraps around, it may still be
6378 // a VEXT but the source vectors must be swapped.
6379 ExpectedElt += 1;
6380 if (ExpectedElt == NumElts * 2) {
6381 ExpectedElt = 0;
6382 ReverseVEXT = true;
6385 if (M[i] < 0) continue; // ignore UNDEF indices
6386 if (ExpectedElt != static_cast<unsigned>(M[i]))
6387 return false;
6390 // Adjust the index value if the source operands will be swapped.
6391 if (ReverseVEXT)
6392 Imm -= NumElts;
6394 return true;
6397 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6398 /// instruction with the specified blocksize. (The order of the elements
6399 /// within each block of the vector is reversed.)
6400 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6401 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6402 "Only possible block sizes for VREV are: 16, 32, 64");
6404 unsigned EltSz = VT.getScalarSizeInBits();
6405 if (EltSz == 64)
6406 return false;
6408 unsigned NumElts = VT.getVectorNumElements();
6409 unsigned BlockElts = M[0] + 1;
6410 // If the first shuffle index is UNDEF, be optimistic.
6411 if (M[0] < 0)
6412 BlockElts = BlockSize / EltSz;
6414 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6415 return false;
6417 for (unsigned i = 0; i < NumElts; ++i) {
6418 if (M[i] < 0) continue; // ignore UNDEF indices
6419 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6420 return false;
6423 return true;
6426 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6427 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6428 // range, then 0 is placed into the resulting vector. So pretty much any mask
6429 // of 8 elements can work here.
6430 return VT == MVT::v8i8 && M.size() == 8;
6433 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6434 unsigned Index) {
6435 if (Mask.size() == Elements * 2)
6436 return Index / Elements;
6437 return Mask[Index] == 0 ? 0 : 1;
6440 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6441 // checking that pairs of elements in the shuffle mask represent the same index
6442 // in each vector, incrementing the expected index by 2 at each step.
6443 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6444 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6445 // v2={e,f,g,h}
6446 // WhichResult gives the offset for each element in the mask based on which
6447 // of the two results it belongs to.
6449 // The transpose can be represented either as:
6450 // result1 = shufflevector v1, v2, result1_shuffle_mask
6451 // result2 = shufflevector v1, v2, result2_shuffle_mask
6452 // where v1/v2 and the shuffle masks have the same number of elements
6453 // (here WhichResult (see below) indicates which result is being checked)
6455 // or as:
6456 // results = shufflevector v1, v2, shuffle_mask
6457 // where both results are returned in one vector and the shuffle mask has twice
6458 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6459 // want to check the low half and high half of the shuffle mask as if it were
6460 // the other case
6461 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6462 unsigned EltSz = VT.getScalarSizeInBits();
6463 if (EltSz == 64)
6464 return false;
6466 unsigned NumElts = VT.getVectorNumElements();
6467 if (M.size() != NumElts && M.size() != NumElts*2)
6468 return false;
6470 // If the mask is twice as long as the input vector then we need to check the
6471 // upper and lower parts of the mask with a matching value for WhichResult
6472 // FIXME: A mask with only even values will be rejected in case the first
6473 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6474 // M[0] is used to determine WhichResult
6475 for (unsigned i = 0; i < M.size(); i += NumElts) {
6476 WhichResult = SelectPairHalf(NumElts, M, i);
6477 for (unsigned j = 0; j < NumElts; j += 2) {
6478 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6479 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6480 return false;
6484 if (M.size() == NumElts*2)
6485 WhichResult = 0;
6487 return true;
6490 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6491 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6492 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6493 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6494 unsigned EltSz = VT.getScalarSizeInBits();
6495 if (EltSz == 64)
6496 return false;
6498 unsigned NumElts = VT.getVectorNumElements();
6499 if (M.size() != NumElts && M.size() != NumElts*2)
6500 return false;
6502 for (unsigned i = 0; i < M.size(); i += NumElts) {
6503 WhichResult = SelectPairHalf(NumElts, M, i);
6504 for (unsigned j = 0; j < NumElts; j += 2) {
6505 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6506 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6507 return false;
6511 if (M.size() == NumElts*2)
6512 WhichResult = 0;
6514 return true;
6517 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6518 // that the mask elements are either all even and in steps of size 2 or all odd
6519 // and in steps of size 2.
6520 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6521 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6522 // v2={e,f,g,h}
6523 // Requires similar checks to that of isVTRNMask with
6524 // respect the how results are returned.
6525 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6526 unsigned EltSz = VT.getScalarSizeInBits();
6527 if (EltSz == 64)
6528 return false;
6530 unsigned NumElts = VT.getVectorNumElements();
6531 if (M.size() != NumElts && M.size() != NumElts*2)
6532 return false;
6534 for (unsigned i = 0; i < M.size(); i += NumElts) {
6535 WhichResult = SelectPairHalf(NumElts, M, i);
6536 for (unsigned j = 0; j < NumElts; ++j) {
6537 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6538 return false;
6542 if (M.size() == NumElts*2)
6543 WhichResult = 0;
6545 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6546 if (VT.is64BitVector() && EltSz == 32)
6547 return false;
6549 return true;
6552 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6553 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6554 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6555 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6556 unsigned EltSz = VT.getScalarSizeInBits();
6557 if (EltSz == 64)
6558 return false;
6560 unsigned NumElts = VT.getVectorNumElements();
6561 if (M.size() != NumElts && M.size() != NumElts*2)
6562 return false;
6564 unsigned Half = NumElts / 2;
6565 for (unsigned i = 0; i < M.size(); i += NumElts) {
6566 WhichResult = SelectPairHalf(NumElts, M, i);
6567 for (unsigned j = 0; j < NumElts; j += Half) {
6568 unsigned Idx = WhichResult;
6569 for (unsigned k = 0; k < Half; ++k) {
6570 int MIdx = M[i + j + k];
6571 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6572 return false;
6573 Idx += 2;
6578 if (M.size() == NumElts*2)
6579 WhichResult = 0;
6581 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6582 if (VT.is64BitVector() && EltSz == 32)
6583 return false;
6585 return true;
6588 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6589 // that pairs of elements of the shufflemask represent the same index in each
6590 // vector incrementing sequentially through the vectors.
6591 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6592 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6593 // v2={e,f,g,h}
6594 // Requires similar checks to that of isVTRNMask with respect the how results
6595 // are returned.
6596 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6597 unsigned EltSz = VT.getScalarSizeInBits();
6598 if (EltSz == 64)
6599 return false;
6601 unsigned NumElts = VT.getVectorNumElements();
6602 if (M.size() != NumElts && M.size() != NumElts*2)
6603 return false;
6605 for (unsigned i = 0; i < M.size(); i += NumElts) {
6606 WhichResult = SelectPairHalf(NumElts, M, i);
6607 unsigned Idx = WhichResult * NumElts / 2;
6608 for (unsigned j = 0; j < NumElts; j += 2) {
6609 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6610 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6611 return false;
6612 Idx += 1;
6616 if (M.size() == NumElts*2)
6617 WhichResult = 0;
6619 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6620 if (VT.is64BitVector() && EltSz == 32)
6621 return false;
6623 return true;
6626 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6627 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6628 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6629 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6630 unsigned EltSz = VT.getScalarSizeInBits();
6631 if (EltSz == 64)
6632 return false;
6634 unsigned NumElts = VT.getVectorNumElements();
6635 if (M.size() != NumElts && M.size() != NumElts*2)
6636 return false;
6638 for (unsigned i = 0; i < M.size(); i += NumElts) {
6639 WhichResult = SelectPairHalf(NumElts, M, i);
6640 unsigned Idx = WhichResult * NumElts / 2;
6641 for (unsigned j = 0; j < NumElts; j += 2) {
6642 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6643 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6644 return false;
6645 Idx += 1;
6649 if (M.size() == NumElts*2)
6650 WhichResult = 0;
6652 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6653 if (VT.is64BitVector() && EltSz == 32)
6654 return false;
6656 return true;
6659 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6660 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6661 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6662 unsigned &WhichResult,
6663 bool &isV_UNDEF) {
6664 isV_UNDEF = false;
6665 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6666 return ARMISD::VTRN;
6667 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6668 return ARMISD::VUZP;
6669 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6670 return ARMISD::VZIP;
6672 isV_UNDEF = true;
6673 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6674 return ARMISD::VTRN;
6675 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6676 return ARMISD::VUZP;
6677 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6678 return ARMISD::VZIP;
6680 return 0;
6683 /// \return true if this is a reverse operation on an vector.
6684 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6685 unsigned NumElts = VT.getVectorNumElements();
6686 // Make sure the mask has the right size.
6687 if (NumElts != M.size())
6688 return false;
6690 // Look for <15, ..., 3, -1, 1, 0>.
6691 for (unsigned i = 0; i != NumElts; ++i)
6692 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6693 return false;
6695 return true;
6698 // If N is an integer constant that can be moved into a register in one
6699 // instruction, return an SDValue of such a constant (will become a MOV
6700 // instruction). Otherwise return null.
6701 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6702 const ARMSubtarget *ST, const SDLoc &dl) {
6703 uint64_t Val;
6704 if (!isa<ConstantSDNode>(N))
6705 return SDValue();
6706 Val = cast<ConstantSDNode>(N)->getZExtValue();
6708 if (ST->isThumb1Only()) {
6709 if (Val <= 255 || ~Val <= 255)
6710 return DAG.getConstant(Val, dl, MVT::i32);
6711 } else {
6712 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6713 return DAG.getConstant(Val, dl, MVT::i32);
6715 return SDValue();
6718 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6719 const ARMSubtarget *ST) {
6720 SDLoc dl(Op);
6721 EVT VT = Op.getValueType();
6723 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6725 unsigned NumElts = VT.getVectorNumElements();
6726 unsigned BoolMask;
6727 unsigned BitsPerBool;
6728 if (NumElts == 4) {
6729 BitsPerBool = 4;
6730 BoolMask = 0xf;
6731 } else if (NumElts == 8) {
6732 BitsPerBool = 2;
6733 BoolMask = 0x3;
6734 } else if (NumElts == 16) {
6735 BitsPerBool = 1;
6736 BoolMask = 0x1;
6737 } else
6738 return SDValue();
6740 // First create base with bits set where known
6741 unsigned Bits32 = 0;
6742 for (unsigned i = 0; i < NumElts; ++i) {
6743 SDValue V = Op.getOperand(i);
6744 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6745 continue;
6746 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6747 if (BitSet)
6748 Bits32 |= BoolMask << (i * BitsPerBool);
6751 // Add in unknown nodes
6752 // FIXME: Handle splats of the same value better.
6753 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6754 DAG.getConstant(Bits32, dl, MVT::i32));
6755 for (unsigned i = 0; i < NumElts; ++i) {
6756 SDValue V = Op.getOperand(i);
6757 if (isa<ConstantSDNode>(V) || V.isUndef())
6758 continue;
6759 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6760 DAG.getConstant(i, dl, MVT::i32));
6763 return Base;
6766 // If this is a case we can't handle, return null and let the default
6767 // expansion code take care of it.
6768 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6769 const ARMSubtarget *ST) const {
6770 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6771 SDLoc dl(Op);
6772 EVT VT = Op.getValueType();
6774 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6775 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6777 APInt SplatBits, SplatUndef;
6778 unsigned SplatBitSize;
6779 bool HasAnyUndefs;
6780 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6781 if (SplatUndef.isAllOnesValue())
6782 return DAG.getUNDEF(VT);
6784 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6785 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6786 // Check if an immediate VMOV works.
6787 EVT VmovVT;
6788 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6789 SplatUndef.getZExtValue(), SplatBitSize,
6790 DAG, dl, VmovVT, VT.is128BitVector(),
6791 VMOVModImm);
6793 if (Val.getNode()) {
6794 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6795 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6798 // Try an immediate VMVN.
6799 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6800 Val = isVMOVModifiedImm(
6801 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6802 DAG, dl, VmovVT, VT.is128BitVector(),
6803 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6804 if (Val.getNode()) {
6805 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6806 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6809 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6810 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6811 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6812 if (ImmVal != -1) {
6813 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6814 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6820 // Scan through the operands to see if only one value is used.
6822 // As an optimisation, even if more than one value is used it may be more
6823 // profitable to splat with one value then change some lanes.
6825 // Heuristically we decide to do this if the vector has a "dominant" value,
6826 // defined as splatted to more than half of the lanes.
6827 unsigned NumElts = VT.getVectorNumElements();
6828 bool isOnlyLowElement = true;
6829 bool usesOnlyOneValue = true;
6830 bool hasDominantValue = false;
6831 bool isConstant = true;
6833 // Map of the number of times a particular SDValue appears in the
6834 // element list.
6835 DenseMap<SDValue, unsigned> ValueCounts;
6836 SDValue Value;
6837 for (unsigned i = 0; i < NumElts; ++i) {
6838 SDValue V = Op.getOperand(i);
6839 if (V.isUndef())
6840 continue;
6841 if (i > 0)
6842 isOnlyLowElement = false;
6843 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6844 isConstant = false;
6846 ValueCounts.insert(std::make_pair(V, 0));
6847 unsigned &Count = ValueCounts[V];
6849 // Is this value dominant? (takes up more than half of the lanes)
6850 if (++Count > (NumElts / 2)) {
6851 hasDominantValue = true;
6852 Value = V;
6855 if (ValueCounts.size() != 1)
6856 usesOnlyOneValue = false;
6857 if (!Value.getNode() && !ValueCounts.empty())
6858 Value = ValueCounts.begin()->first;
6860 if (ValueCounts.empty())
6861 return DAG.getUNDEF(VT);
6863 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6864 // Keep going if we are hitting this case.
6865 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6866 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6868 unsigned EltSize = VT.getScalarSizeInBits();
6870 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
6871 // i32 and try again.
6872 if (hasDominantValue && EltSize <= 32) {
6873 if (!isConstant) {
6874 SDValue N;
6876 // If we are VDUPing a value that comes directly from a vector, that will
6877 // cause an unnecessary move to and from a GPR, where instead we could
6878 // just use VDUPLANE. We can only do this if the lane being extracted
6879 // is at a constant index, as the VDUP from lane instructions only have
6880 // constant-index forms.
6881 ConstantSDNode *constIndex;
6882 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6883 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6884 // We need to create a new undef vector to use for the VDUPLANE if the
6885 // size of the vector from which we get the value is different than the
6886 // size of the vector that we need to create. We will insert the element
6887 // such that the register coalescer will remove unnecessary copies.
6888 if (VT != Value->getOperand(0).getValueType()) {
6889 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6890 VT.getVectorNumElements();
6891 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6892 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6893 Value, DAG.getConstant(index, dl, MVT::i32)),
6894 DAG.getConstant(index, dl, MVT::i32));
6895 } else
6896 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6897 Value->getOperand(0), Value->getOperand(1));
6898 } else
6899 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6901 if (!usesOnlyOneValue) {
6902 // The dominant value was splatted as 'N', but we now have to insert
6903 // all differing elements.
6904 for (unsigned I = 0; I < NumElts; ++I) {
6905 if (Op.getOperand(I) == Value)
6906 continue;
6907 SmallVector<SDValue, 3> Ops;
6908 Ops.push_back(N);
6909 Ops.push_back(Op.getOperand(I));
6910 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6911 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6914 return N;
6916 if (VT.getVectorElementType().isFloatingPoint()) {
6917 SmallVector<SDValue, 8> Ops;
6918 MVT FVT = VT.getVectorElementType().getSimpleVT();
6919 assert(FVT == MVT::f32 || FVT == MVT::f16);
6920 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
6921 for (unsigned i = 0; i < NumElts; ++i)
6922 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
6923 Op.getOperand(i)));
6924 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
6925 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6926 Val = LowerBUILD_VECTOR(Val, DAG, ST);
6927 if (Val.getNode())
6928 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6930 if (usesOnlyOneValue) {
6931 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6932 if (isConstant && Val.getNode())
6933 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6937 // If all elements are constants and the case above didn't get hit, fall back
6938 // to the default expansion, which will generate a load from the constant
6939 // pool.
6940 if (isConstant)
6941 return SDValue();
6943 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6944 if (NumElts >= 4) {
6945 SDValue shuffle = ReconstructShuffle(Op, DAG);
6946 if (shuffle != SDValue())
6947 return shuffle;
6950 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6951 // If we haven't found an efficient lowering, try splitting a 128-bit vector
6952 // into two 64-bit vectors; we might discover a better way to lower it.
6953 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6954 EVT ExtVT = VT.getVectorElementType();
6955 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6956 SDValue Lower =
6957 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6958 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6959 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6960 SDValue Upper = DAG.getBuildVector(
6961 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6962 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6963 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6964 if (Lower && Upper)
6965 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6968 // Vectors with 32- or 64-bit elements can be built by directly assigning
6969 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
6970 // will be legalized.
6971 if (EltSize >= 32) {
6972 // Do the expansion with floating-point types, since that is what the VFP
6973 // registers are defined to use, and since i64 is not legal.
6974 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6975 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6976 SmallVector<SDValue, 8> Ops;
6977 for (unsigned i = 0; i < NumElts; ++i)
6978 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6979 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6980 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6983 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6984 // know the default expansion would otherwise fall back on something even
6985 // worse. For a vector with one or two non-undef values, that's
6986 // scalar_to_vector for the elements followed by a shuffle (provided the
6987 // shuffle is valid for the target) and materialization element by element
6988 // on the stack followed by a load for everything else.
6989 if (!isConstant && !usesOnlyOneValue) {
6990 SDValue Vec = DAG.getUNDEF(VT);
6991 for (unsigned i = 0 ; i < NumElts; ++i) {
6992 SDValue V = Op.getOperand(i);
6993 if (V.isUndef())
6994 continue;
6995 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6996 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6998 return Vec;
7001 return SDValue();
7004 // Gather data to see if the operation can be modelled as a
7005 // shuffle in combination with VEXTs.
7006 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7007 SelectionDAG &DAG) const {
7008 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7009 SDLoc dl(Op);
7010 EVT VT = Op.getValueType();
7011 unsigned NumElts = VT.getVectorNumElements();
7013 struct ShuffleSourceInfo {
7014 SDValue Vec;
7015 unsigned MinElt = std::numeric_limits<unsigned>::max();
7016 unsigned MaxElt = 0;
7018 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7019 // be compatible with the shuffle we intend to construct. As a result
7020 // ShuffleVec will be some sliding window into the original Vec.
7021 SDValue ShuffleVec;
7023 // Code should guarantee that element i in Vec starts at element "WindowBase
7024 // + i * WindowScale in ShuffleVec".
7025 int WindowBase = 0;
7026 int WindowScale = 1;
7028 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7030 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7033 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7034 // node.
7035 SmallVector<ShuffleSourceInfo, 2> Sources;
7036 for (unsigned i = 0; i < NumElts; ++i) {
7037 SDValue V = Op.getOperand(i);
7038 if (V.isUndef())
7039 continue;
7040 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7041 // A shuffle can only come from building a vector from various
7042 // elements of other vectors.
7043 return SDValue();
7044 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7045 // Furthermore, shuffles require a constant mask, whereas extractelts
7046 // accept variable indices.
7047 return SDValue();
7050 // Add this element source to the list if it's not already there.
7051 SDValue SourceVec = V.getOperand(0);
7052 auto Source = llvm::find(Sources, SourceVec);
7053 if (Source == Sources.end())
7054 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7056 // Update the minimum and maximum lane number seen.
7057 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7058 Source->MinElt = std::min(Source->MinElt, EltNo);
7059 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7062 // Currently only do something sane when at most two source vectors
7063 // are involved.
7064 if (Sources.size() > 2)
7065 return SDValue();
7067 // Find out the smallest element size among result and two sources, and use
7068 // it as element size to build the shuffle_vector.
7069 EVT SmallestEltTy = VT.getVectorElementType();
7070 for (auto &Source : Sources) {
7071 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7072 if (SrcEltTy.bitsLT(SmallestEltTy))
7073 SmallestEltTy = SrcEltTy;
7075 unsigned ResMultiplier =
7076 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7077 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7078 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7080 // If the source vector is too wide or too narrow, we may nevertheless be able
7081 // to construct a compatible shuffle either by concatenating it with UNDEF or
7082 // extracting a suitable range of elements.
7083 for (auto &Src : Sources) {
7084 EVT SrcVT = Src.ShuffleVec.getValueType();
7086 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7087 continue;
7089 // This stage of the search produces a source with the same element type as
7090 // the original, but with a total width matching the BUILD_VECTOR output.
7091 EVT EltVT = SrcVT.getVectorElementType();
7092 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7093 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7095 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7096 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7097 return SDValue();
7098 // We can pad out the smaller vector for free, so if it's part of a
7099 // shuffle...
7100 Src.ShuffleVec =
7101 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7102 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7103 continue;
7106 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7107 return SDValue();
7109 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7110 // Span too large for a VEXT to cope
7111 return SDValue();
7114 if (Src.MinElt >= NumSrcElts) {
7115 // The extraction can just take the second half
7116 Src.ShuffleVec =
7117 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7118 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7119 Src.WindowBase = -NumSrcElts;
7120 } else if (Src.MaxElt < NumSrcElts) {
7121 // The extraction can just take the first half
7122 Src.ShuffleVec =
7123 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7124 DAG.getConstant(0, dl, MVT::i32));
7125 } else {
7126 // An actual VEXT is needed
7127 SDValue VEXTSrc1 =
7128 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7129 DAG.getConstant(0, dl, MVT::i32));
7130 SDValue VEXTSrc2 =
7131 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7132 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7134 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7135 VEXTSrc2,
7136 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7137 Src.WindowBase = -Src.MinElt;
7141 // Another possible incompatibility occurs from the vector element types. We
7142 // can fix this by bitcasting the source vectors to the same type we intend
7143 // for the shuffle.
7144 for (auto &Src : Sources) {
7145 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7146 if (SrcEltTy == SmallestEltTy)
7147 continue;
7148 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7149 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7150 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7151 Src.WindowBase *= Src.WindowScale;
7154 // Final sanity check before we try to actually produce a shuffle.
7155 LLVM_DEBUG(for (auto Src
7156 : Sources)
7157 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7159 // The stars all align, our next step is to produce the mask for the shuffle.
7160 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7161 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7162 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7163 SDValue Entry = Op.getOperand(i);
7164 if (Entry.isUndef())
7165 continue;
7167 auto Src = llvm::find(Sources, Entry.getOperand(0));
7168 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7170 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7171 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7172 // segment.
7173 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7174 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7175 VT.getScalarSizeInBits());
7176 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7178 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7179 // starting at the appropriate offset.
7180 int *LaneMask = &Mask[i * ResMultiplier];
7182 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7183 ExtractBase += NumElts * (Src - Sources.begin());
7184 for (int j = 0; j < LanesDefined; ++j)
7185 LaneMask[j] = ExtractBase + j;
7188 // Final check before we try to produce nonsense...
7189 if (!isShuffleMaskLegal(Mask, ShuffleVT))
7190 return SDValue();
7192 // We can't handle more than two sources. This should have already
7193 // been checked before this point.
7194 assert(Sources.size() <= 2 && "Too many sources!");
7196 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7197 for (unsigned i = 0; i < Sources.size(); ++i)
7198 ShuffleOps[i] = Sources[i].ShuffleVec;
7200 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7201 ShuffleOps[1], Mask);
7202 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7205 enum ShuffleOpCodes {
7206 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7207 OP_VREV,
7208 OP_VDUP0,
7209 OP_VDUP1,
7210 OP_VDUP2,
7211 OP_VDUP3,
7212 OP_VEXT1,
7213 OP_VEXT2,
7214 OP_VEXT3,
7215 OP_VUZPL, // VUZP, left result
7216 OP_VUZPR, // VUZP, right result
7217 OP_VZIPL, // VZIP, left result
7218 OP_VZIPR, // VZIP, right result
7219 OP_VTRNL, // VTRN, left result
7220 OP_VTRNR // VTRN, right result
7223 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7224 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7225 switch (OpNum) {
7226 case OP_COPY:
7227 case OP_VREV:
7228 case OP_VDUP0:
7229 case OP_VDUP1:
7230 case OP_VDUP2:
7231 case OP_VDUP3:
7232 return true;
7234 return false;
7237 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7238 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7239 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7240 /// are assumed to be legal.
7241 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7242 if (VT.getVectorNumElements() == 4 &&
7243 (VT.is128BitVector() || VT.is64BitVector())) {
7244 unsigned PFIndexes[4];
7245 for (unsigned i = 0; i != 4; ++i) {
7246 if (M[i] < 0)
7247 PFIndexes[i] = 8;
7248 else
7249 PFIndexes[i] = M[i];
7252 // Compute the index in the perfect shuffle table.
7253 unsigned PFTableIndex =
7254 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7255 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7256 unsigned Cost = (PFEntry >> 30);
7258 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7259 return true;
7262 bool ReverseVEXT, isV_UNDEF;
7263 unsigned Imm, WhichResult;
7265 unsigned EltSize = VT.getScalarSizeInBits();
7266 if (EltSize >= 32 ||
7267 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7268 isVREVMask(M, VT, 64) ||
7269 isVREVMask(M, VT, 32) ||
7270 isVREVMask(M, VT, 16))
7271 return true;
7272 else if (Subtarget->hasNEON() &&
7273 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7274 isVTBLMask(M, VT) ||
7275 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7276 return true;
7277 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7278 isReverseMask(M, VT))
7279 return true;
7280 else
7281 return false;
7284 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7285 /// the specified operations to build the shuffle.
7286 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7287 SDValue RHS, SelectionDAG &DAG,
7288 const SDLoc &dl) {
7289 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7290 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7291 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7293 if (OpNum == OP_COPY) {
7294 if (LHSID == (1*9+2)*9+3) return LHS;
7295 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7296 return RHS;
7299 SDValue OpLHS, OpRHS;
7300 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7301 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7302 EVT VT = OpLHS.getValueType();
7304 switch (OpNum) {
7305 default: llvm_unreachable("Unknown shuffle opcode!");
7306 case OP_VREV:
7307 // VREV divides the vector in half and swaps within the half.
7308 if (VT.getVectorElementType() == MVT::i32 ||
7309 VT.getVectorElementType() == MVT::f32)
7310 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7311 // vrev <4 x i16> -> VREV32
7312 if (VT.getVectorElementType() == MVT::i16)
7313 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7314 // vrev <4 x i8> -> VREV16
7315 assert(VT.getVectorElementType() == MVT::i8);
7316 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7317 case OP_VDUP0:
7318 case OP_VDUP1:
7319 case OP_VDUP2:
7320 case OP_VDUP3:
7321 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7322 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7323 case OP_VEXT1:
7324 case OP_VEXT2:
7325 case OP_VEXT3:
7326 return DAG.getNode(ARMISD::VEXT, dl, VT,
7327 OpLHS, OpRHS,
7328 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7329 case OP_VUZPL:
7330 case OP_VUZPR:
7331 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7332 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7333 case OP_VZIPL:
7334 case OP_VZIPR:
7335 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7336 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7337 case OP_VTRNL:
7338 case OP_VTRNR:
7339 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7340 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7344 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7345 ArrayRef<int> ShuffleMask,
7346 SelectionDAG &DAG) {
7347 // Check to see if we can use the VTBL instruction.
7348 SDValue V1 = Op.getOperand(0);
7349 SDValue V2 = Op.getOperand(1);
7350 SDLoc DL(Op);
7352 SmallVector<SDValue, 8> VTBLMask;
7353 for (ArrayRef<int>::iterator
7354 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7355 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7357 if (V2.getNode()->isUndef())
7358 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7359 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7361 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7362 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7365 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7366 SelectionDAG &DAG) {
7367 SDLoc DL(Op);
7368 SDValue OpLHS = Op.getOperand(0);
7369 EVT VT = OpLHS.getValueType();
7371 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7372 "Expect an v8i16/v16i8 type");
7373 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7374 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7375 // extract the first 8 bytes into the top double word and the last 8 bytes
7376 // into the bottom double word. The v8i16 case is similar.
7377 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7378 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7379 DAG.getConstant(ExtractNum, DL, MVT::i32));
7382 static EVT getVectorTyFromPredicateVector(EVT VT) {
7383 switch (VT.getSimpleVT().SimpleTy) {
7384 case MVT::v4i1:
7385 return MVT::v4i32;
7386 case MVT::v8i1:
7387 return MVT::v8i16;
7388 case MVT::v16i1:
7389 return MVT::v16i8;
7390 default:
7391 llvm_unreachable("Unexpected vector predicate type");
7395 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7396 SelectionDAG &DAG) {
7397 // Converting from boolean predicates to integers involves creating a vector
7398 // of all ones or all zeroes and selecting the lanes based upon the real
7399 // predicate.
7400 SDValue AllOnes =
7401 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7402 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7404 SDValue AllZeroes =
7405 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7406 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7408 // Get full vector type from predicate type
7409 EVT NewVT = getVectorTyFromPredicateVector(VT);
7411 SDValue RecastV1;
7412 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7413 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7414 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7415 // since we know in hardware the sizes are really the same.
7416 if (VT != MVT::v16i1)
7417 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7418 else
7419 RecastV1 = Pred;
7421 // Select either all ones or zeroes depending upon the real predicate bits.
7422 SDValue PredAsVector =
7423 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7425 // Recast our new predicate-as-integer v16i8 vector into something
7426 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7427 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7430 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7431 const ARMSubtarget *ST) {
7432 EVT VT = Op.getValueType();
7433 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7434 ArrayRef<int> ShuffleMask = SVN->getMask();
7436 assert(ST->hasMVEIntegerOps() &&
7437 "No support for vector shuffle of boolean predicates");
7439 SDValue V1 = Op.getOperand(0);
7440 SDLoc dl(Op);
7441 if (isReverseMask(ShuffleMask, VT)) {
7442 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7443 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7444 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7445 DAG.getConstant(16, dl, MVT::i32));
7446 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7449 // Until we can come up with optimised cases for every single vector
7450 // shuffle in existence we have chosen the least painful strategy. This is
7451 // to essentially promote the boolean predicate to a 8-bit integer, where
7452 // each predicate represents a byte. Then we fall back on a normal integer
7453 // vector shuffle and convert the result back into a predicate vector. In
7454 // many cases the generated code might be even better than scalar code
7455 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7456 // fields in a register into 8 other arbitrary 2-bit fields!
7457 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7458 EVT NewVT = PredAsVector.getValueType();
7460 // Do the shuffle!
7461 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7462 DAG.getUNDEF(NewVT), ShuffleMask);
7464 // Now return the result of comparing the shuffled vector with zero,
7465 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7466 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7467 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7470 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7471 const ARMSubtarget *ST) {
7472 SDValue V1 = Op.getOperand(0);
7473 SDValue V2 = Op.getOperand(1);
7474 SDLoc dl(Op);
7475 EVT VT = Op.getValueType();
7476 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7477 unsigned EltSize = VT.getScalarSizeInBits();
7479 if (ST->hasMVEIntegerOps() && EltSize == 1)
7480 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7482 // Convert shuffles that are directly supported on NEON to target-specific
7483 // DAG nodes, instead of keeping them as shuffles and matching them again
7484 // during code selection. This is more efficient and avoids the possibility
7485 // of inconsistencies between legalization and selection.
7486 // FIXME: floating-point vectors should be canonicalized to integer vectors
7487 // of the same time so that they get CSEd properly.
7488 ArrayRef<int> ShuffleMask = SVN->getMask();
7490 if (EltSize <= 32) {
7491 if (SVN->isSplat()) {
7492 int Lane = SVN->getSplatIndex();
7493 // If this is undef splat, generate it via "just" vdup, if possible.
7494 if (Lane == -1) Lane = 0;
7496 // Test if V1 is a SCALAR_TO_VECTOR.
7497 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7498 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7500 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7501 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7502 // reaches it).
7503 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7504 !isa<ConstantSDNode>(V1.getOperand(0))) {
7505 bool IsScalarToVector = true;
7506 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7507 if (!V1.getOperand(i).isUndef()) {
7508 IsScalarToVector = false;
7509 break;
7511 if (IsScalarToVector)
7512 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7514 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7515 DAG.getConstant(Lane, dl, MVT::i32));
7518 bool ReverseVEXT = false;
7519 unsigned Imm = 0;
7520 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7521 if (ReverseVEXT)
7522 std::swap(V1, V2);
7523 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7524 DAG.getConstant(Imm, dl, MVT::i32));
7527 if (isVREVMask(ShuffleMask, VT, 64))
7528 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7529 if (isVREVMask(ShuffleMask, VT, 32))
7530 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7531 if (isVREVMask(ShuffleMask, VT, 16))
7532 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7534 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7535 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7536 DAG.getConstant(Imm, dl, MVT::i32));
7539 // Check for Neon shuffles that modify both input vectors in place.
7540 // If both results are used, i.e., if there are two shuffles with the same
7541 // source operands and with masks corresponding to both results of one of
7542 // these operations, DAG memoization will ensure that a single node is
7543 // used for both shuffles.
7544 unsigned WhichResult = 0;
7545 bool isV_UNDEF = false;
7546 if (ST->hasNEON()) {
7547 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7548 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7549 if (isV_UNDEF)
7550 V2 = V1;
7551 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7552 .getValue(WhichResult);
7556 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7557 // shuffles that produce a result larger than their operands with:
7558 // shuffle(concat(v1, undef), concat(v2, undef))
7559 // ->
7560 // shuffle(concat(v1, v2), undef)
7561 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7563 // This is useful in the general case, but there are special cases where
7564 // native shuffles produce larger results: the two-result ops.
7566 // Look through the concat when lowering them:
7567 // shuffle(concat(v1, v2), undef)
7568 // ->
7569 // concat(VZIP(v1, v2):0, :1)
7571 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7572 SDValue SubV1 = V1->getOperand(0);
7573 SDValue SubV2 = V1->getOperand(1);
7574 EVT SubVT = SubV1.getValueType();
7576 // We expect these to have been canonicalized to -1.
7577 assert(llvm::all_of(ShuffleMask, [&](int i) {
7578 return i < (int)VT.getVectorNumElements();
7579 }) && "Unexpected shuffle index into UNDEF operand!");
7581 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7582 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7583 if (isV_UNDEF)
7584 SubV2 = SubV1;
7585 assert((WhichResult == 0) &&
7586 "In-place shuffle of concat can only have one result!");
7587 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7588 SubV1, SubV2);
7589 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7590 Res.getValue(1));
7595 // If the shuffle is not directly supported and it has 4 elements, use
7596 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7597 unsigned NumElts = VT.getVectorNumElements();
7598 if (NumElts == 4) {
7599 unsigned PFIndexes[4];
7600 for (unsigned i = 0; i != 4; ++i) {
7601 if (ShuffleMask[i] < 0)
7602 PFIndexes[i] = 8;
7603 else
7604 PFIndexes[i] = ShuffleMask[i];
7607 // Compute the index in the perfect shuffle table.
7608 unsigned PFTableIndex =
7609 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7610 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7611 unsigned Cost = (PFEntry >> 30);
7613 if (Cost <= 4) {
7614 if (ST->hasNEON())
7615 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7616 else if (isLegalMVEShuffleOp(PFEntry)) {
7617 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7618 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7619 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7620 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7621 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7622 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7627 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7628 if (EltSize >= 32) {
7629 // Do the expansion with floating-point types, since that is what the VFP
7630 // registers are defined to use, and since i64 is not legal.
7631 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7632 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7633 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7634 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7635 SmallVector<SDValue, 8> Ops;
7636 for (unsigned i = 0; i < NumElts; ++i) {
7637 if (ShuffleMask[i] < 0)
7638 Ops.push_back(DAG.getUNDEF(EltVT));
7639 else
7640 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7641 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7642 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7643 dl, MVT::i32)));
7645 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7646 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7649 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7650 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7652 if (ST->hasNEON() && VT == MVT::v8i8)
7653 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7654 return NewOp;
7656 return SDValue();
7659 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7660 const ARMSubtarget *ST) {
7661 EVT VecVT = Op.getOperand(0).getValueType();
7662 SDLoc dl(Op);
7664 assert(ST->hasMVEIntegerOps() &&
7665 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7667 SDValue Conv =
7668 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7669 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7670 unsigned LaneWidth =
7671 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7672 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7673 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7674 Op.getOperand(1), DAG.getValueType(MVT::i1));
7675 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7676 DAG.getConstant(~Mask, dl, MVT::i32));
7677 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7680 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7681 SelectionDAG &DAG) const {
7682 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7683 SDValue Lane = Op.getOperand(2);
7684 if (!isa<ConstantSDNode>(Lane))
7685 return SDValue();
7687 SDValue Elt = Op.getOperand(1);
7688 EVT EltVT = Elt.getValueType();
7690 if (Subtarget->hasMVEIntegerOps() &&
7691 Op.getValueType().getScalarSizeInBits() == 1)
7692 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7694 if (getTypeAction(*DAG.getContext(), EltVT) ==
7695 TargetLowering::TypePromoteFloat) {
7696 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7697 // but the type system will try to do that if we don't intervene.
7698 // Reinterpret any such vector-element insertion as one with the
7699 // corresponding integer types.
7701 SDLoc dl(Op);
7703 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7704 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7705 TargetLowering::TypePromoteFloat);
7707 SDValue VecIn = Op.getOperand(0);
7708 EVT VecVT = VecIn.getValueType();
7709 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7710 VecVT.getVectorNumElements());
7712 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7713 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7714 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7715 IVecIn, IElt, Lane);
7716 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7719 return Op;
7722 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7723 const ARMSubtarget *ST) {
7724 EVT VecVT = Op.getOperand(0).getValueType();
7725 SDLoc dl(Op);
7727 assert(ST->hasMVEIntegerOps() &&
7728 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7730 SDValue Conv =
7731 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7732 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7733 unsigned LaneWidth =
7734 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7735 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7736 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7737 return Shift;
7740 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7741 const ARMSubtarget *ST) {
7742 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7743 SDValue Lane = Op.getOperand(1);
7744 if (!isa<ConstantSDNode>(Lane))
7745 return SDValue();
7747 SDValue Vec = Op.getOperand(0);
7748 EVT VT = Vec.getValueType();
7750 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7751 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7753 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7754 SDLoc dl(Op);
7755 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7758 return Op;
7761 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7762 const ARMSubtarget *ST) {
7763 SDValue V1 = Op.getOperand(0);
7764 SDValue V2 = Op.getOperand(1);
7765 SDLoc dl(Op);
7766 EVT VT = Op.getValueType();
7767 EVT Op1VT = V1.getValueType();
7768 EVT Op2VT = V2.getValueType();
7769 unsigned NumElts = VT.getVectorNumElements();
7771 assert(Op1VT == Op2VT && "Operand types don't match!");
7772 assert(VT.getScalarSizeInBits() == 1 &&
7773 "Unexpected custom CONCAT_VECTORS lowering");
7774 assert(ST->hasMVEIntegerOps() &&
7775 "CONCAT_VECTORS lowering only supported for MVE");
7777 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7778 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7780 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7781 // promoted to v8i16, etc.
7783 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7785 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7786 // to be the right size for the destination. For example, if Op1 is v4i1 then
7787 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7788 // which when promoted is v8i16. That means each i32 element from Op1 needs
7789 // truncating to i16 and inserting in the result.
7790 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7791 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7792 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7793 EVT NewVT = NewV.getValueType();
7794 EVT ConcatVT = ConVec.getValueType();
7795 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7796 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7797 DAG.getIntPtrConstant(i, dl));
7798 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7799 DAG.getConstant(j, dl, MVT::i32));
7801 return ConVec;
7803 unsigned j = 0;
7804 ConVec = ExractInto(NewV1, ConVec, j);
7805 ConVec = ExractInto(NewV2, ConVec, j);
7807 // Now return the result of comparing the subvector with zero,
7808 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7809 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
7810 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7813 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
7814 const ARMSubtarget *ST) {
7815 EVT VT = Op->getValueType(0);
7816 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7817 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
7819 // The only time a CONCAT_VECTORS operation can have legal types is when
7820 // two 64-bit vectors are concatenated to a 128-bit vector.
7821 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7822 "unexpected CONCAT_VECTORS");
7823 SDLoc dl(Op);
7824 SDValue Val = DAG.getUNDEF(MVT::v2f64);
7825 SDValue Op0 = Op.getOperand(0);
7826 SDValue Op1 = Op.getOperand(1);
7827 if (!Op0.isUndef())
7828 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7829 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7830 DAG.getIntPtrConstant(0, dl));
7831 if (!Op1.isUndef())
7832 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7833 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7834 DAG.getIntPtrConstant(1, dl));
7835 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7838 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
7839 const ARMSubtarget *ST) {
7840 SDValue V1 = Op.getOperand(0);
7841 SDValue V2 = Op.getOperand(1);
7842 SDLoc dl(Op);
7843 EVT VT = Op.getValueType();
7844 EVT Op1VT = V1.getValueType();
7845 unsigned NumElts = VT.getVectorNumElements();
7846 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
7848 assert(VT.getScalarSizeInBits() == 1 &&
7849 "Unexpected custom EXTRACT_SUBVECTOR lowering");
7850 assert(ST->hasMVEIntegerOps() &&
7851 "EXTRACT_SUBVECTOR lowering only supported for MVE");
7853 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7855 // We now have Op1 promoted to a vector of integers, where v8i1 gets
7856 // promoted to v8i16, etc.
7858 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7860 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
7861 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
7862 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
7863 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
7864 DAG.getIntPtrConstant(i, dl));
7865 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
7866 DAG.getConstant(j, dl, MVT::i32));
7869 // Now return the result of comparing the subvector with zero,
7870 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7871 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
7872 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7875 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7876 /// element has been zero/sign-extended, depending on the isSigned parameter,
7877 /// from an integer type half its size.
7878 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7879 bool isSigned) {
7880 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7881 EVT VT = N->getValueType(0);
7882 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7883 SDNode *BVN = N->getOperand(0).getNode();
7884 if (BVN->getValueType(0) != MVT::v4i32 ||
7885 BVN->getOpcode() != ISD::BUILD_VECTOR)
7886 return false;
7887 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7888 unsigned HiElt = 1 - LoElt;
7889 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7890 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7891 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7892 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7893 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7894 return false;
7895 if (isSigned) {
7896 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7897 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7898 return true;
7899 } else {
7900 if (Hi0->isNullValue() && Hi1->isNullValue())
7901 return true;
7903 return false;
7906 if (N->getOpcode() != ISD::BUILD_VECTOR)
7907 return false;
7909 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7910 SDNode *Elt = N->getOperand(i).getNode();
7911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7912 unsigned EltSize = VT.getScalarSizeInBits();
7913 unsigned HalfSize = EltSize / 2;
7914 if (isSigned) {
7915 if (!isIntN(HalfSize, C->getSExtValue()))
7916 return false;
7917 } else {
7918 if (!isUIntN(HalfSize, C->getZExtValue()))
7919 return false;
7921 continue;
7923 return false;
7926 return true;
7929 /// isSignExtended - Check if a node is a vector value that is sign-extended
7930 /// or a constant BUILD_VECTOR with sign-extended elements.
7931 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7932 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7933 return true;
7934 if (isExtendedBUILD_VECTOR(N, DAG, true))
7935 return true;
7936 return false;
7939 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7940 /// or a constant BUILD_VECTOR with zero-extended elements.
7941 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7942 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7943 return true;
7944 if (isExtendedBUILD_VECTOR(N, DAG, false))
7945 return true;
7946 return false;
7949 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7950 if (OrigVT.getSizeInBits() >= 64)
7951 return OrigVT;
7953 assert(OrigVT.isSimple() && "Expecting a simple value type");
7955 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7956 switch (OrigSimpleTy) {
7957 default: llvm_unreachable("Unexpected Vector Type");
7958 case MVT::v2i8:
7959 case MVT::v2i16:
7960 return MVT::v2i32;
7961 case MVT::v4i8:
7962 return MVT::v4i16;
7966 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7967 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7968 /// We insert the required extension here to get the vector to fill a D register.
7969 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7970 const EVT &OrigTy,
7971 const EVT &ExtTy,
7972 unsigned ExtOpcode) {
7973 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7974 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7975 // 64-bits we need to insert a new extension so that it will be 64-bits.
7976 assert(ExtTy.is128BitVector() && "Unexpected extension size");
7977 if (OrigTy.getSizeInBits() >= 64)
7978 return N;
7980 // Must extend size to at least 64 bits to be used as an operand for VMULL.
7981 EVT NewVT = getExtensionTo64Bits(OrigTy);
7983 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7986 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7987 /// does not do any sign/zero extension. If the original vector is less
7988 /// than 64 bits, an appropriate extension will be added after the load to
7989 /// reach a total size of 64 bits. We have to add the extension separately
7990 /// because ARM does not have a sign/zero extending load for vectors.
7991 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7992 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7994 // The load already has the right type.
7995 if (ExtendedTy == LD->getMemoryVT())
7996 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7997 LD->getBasePtr(), LD->getPointerInfo(),
7998 LD->getAlignment(), LD->getMemOperand()->getFlags());
8000 // We need to create a zextload/sextload. We cannot just create a load
8001 // followed by a zext/zext node because LowerMUL is also run during normal
8002 // operation legalization where we can't create illegal types.
8003 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8004 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8005 LD->getMemoryVT(), LD->getAlignment(),
8006 LD->getMemOperand()->getFlags());
8009 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8010 /// extending load, or BUILD_VECTOR with extended elements, return the
8011 /// unextended value. The unextended vector should be 64 bits so that it can
8012 /// be used as an operand to a VMULL instruction. If the original vector size
8013 /// before extension is less than 64 bits we add a an extension to resize
8014 /// the vector to 64 bits.
8015 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8016 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8017 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8018 N->getOperand(0)->getValueType(0),
8019 N->getValueType(0),
8020 N->getOpcode());
8022 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8023 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8024 "Expected extending load");
8026 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8027 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8028 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8029 SDValue extLoad =
8030 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8031 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8033 return newLoad;
8036 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8037 // have been legalized as a BITCAST from v4i32.
8038 if (N->getOpcode() == ISD::BITCAST) {
8039 SDNode *BVN = N->getOperand(0).getNode();
8040 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8041 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8042 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8043 return DAG.getBuildVector(
8044 MVT::v2i32, SDLoc(N),
8045 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8047 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8048 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8049 EVT VT = N->getValueType(0);
8050 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8051 unsigned NumElts = VT.getVectorNumElements();
8052 MVT TruncVT = MVT::getIntegerVT(EltSize);
8053 SmallVector<SDValue, 8> Ops;
8054 SDLoc dl(N);
8055 for (unsigned i = 0; i != NumElts; ++i) {
8056 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8057 const APInt &CInt = C->getAPIntValue();
8058 // Element types smaller than 32 bits are not legal, so use i32 elements.
8059 // The values are implicitly truncated so sext vs. zext doesn't matter.
8060 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8062 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8065 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8066 unsigned Opcode = N->getOpcode();
8067 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8068 SDNode *N0 = N->getOperand(0).getNode();
8069 SDNode *N1 = N->getOperand(1).getNode();
8070 return N0->hasOneUse() && N1->hasOneUse() &&
8071 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8073 return false;
8076 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8077 unsigned Opcode = N->getOpcode();
8078 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8079 SDNode *N0 = N->getOperand(0).getNode();
8080 SDNode *N1 = N->getOperand(1).getNode();
8081 return N0->hasOneUse() && N1->hasOneUse() &&
8082 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8084 return false;
8087 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8088 // Multiplications are only custom-lowered for 128-bit vectors so that
8089 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8090 EVT VT = Op.getValueType();
8091 assert(VT.is128BitVector() && VT.isInteger() &&
8092 "unexpected type for custom-lowering ISD::MUL");
8093 SDNode *N0 = Op.getOperand(0).getNode();
8094 SDNode *N1 = Op.getOperand(1).getNode();
8095 unsigned NewOpc = 0;
8096 bool isMLA = false;
8097 bool isN0SExt = isSignExtended(N0, DAG);
8098 bool isN1SExt = isSignExtended(N1, DAG);
8099 if (isN0SExt && isN1SExt)
8100 NewOpc = ARMISD::VMULLs;
8101 else {
8102 bool isN0ZExt = isZeroExtended(N0, DAG);
8103 bool isN1ZExt = isZeroExtended(N1, DAG);
8104 if (isN0ZExt && isN1ZExt)
8105 NewOpc = ARMISD::VMULLu;
8106 else if (isN1SExt || isN1ZExt) {
8107 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8108 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8109 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8110 NewOpc = ARMISD::VMULLs;
8111 isMLA = true;
8112 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8113 NewOpc = ARMISD::VMULLu;
8114 isMLA = true;
8115 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8116 std::swap(N0, N1);
8117 NewOpc = ARMISD::VMULLu;
8118 isMLA = true;
8122 if (!NewOpc) {
8123 if (VT == MVT::v2i64)
8124 // Fall through to expand this. It is not legal.
8125 return SDValue();
8126 else
8127 // Other vector multiplications are legal.
8128 return Op;
8132 // Legalize to a VMULL instruction.
8133 SDLoc DL(Op);
8134 SDValue Op0;
8135 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8136 if (!isMLA) {
8137 Op0 = SkipExtensionForVMULL(N0, DAG);
8138 assert(Op0.getValueType().is64BitVector() &&
8139 Op1.getValueType().is64BitVector() &&
8140 "unexpected types for extended operands to VMULL");
8141 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8144 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8145 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8146 // vmull q0, d4, d6
8147 // vmlal q0, d5, d6
8148 // is faster than
8149 // vaddl q0, d4, d5
8150 // vmovl q1, d6
8151 // vmul q0, q0, q1
8152 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8153 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8154 EVT Op1VT = Op1.getValueType();
8155 return DAG.getNode(N0->getOpcode(), DL, VT,
8156 DAG.getNode(NewOpc, DL, VT,
8157 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8158 DAG.getNode(NewOpc, DL, VT,
8159 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8162 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8163 SelectionDAG &DAG) {
8164 // TODO: Should this propagate fast-math-flags?
8166 // Convert to float
8167 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8168 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8169 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8170 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8171 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8172 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8173 // Get reciprocal estimate.
8174 // float4 recip = vrecpeq_f32(yf);
8175 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8176 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8178 // Because char has a smaller range than uchar, we can actually get away
8179 // without any newton steps. This requires that we use a weird bias
8180 // of 0xb000, however (again, this has been exhaustively tested).
8181 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8182 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8183 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8184 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8185 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8186 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8187 // Convert back to short.
8188 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8189 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8190 return X;
8193 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8194 SelectionDAG &DAG) {
8195 // TODO: Should this propagate fast-math-flags?
8197 SDValue N2;
8198 // Convert to float.
8199 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8200 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8201 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8202 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8203 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8204 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8206 // Use reciprocal estimate and one refinement step.
8207 // float4 recip = vrecpeq_f32(yf);
8208 // recip *= vrecpsq_f32(yf, recip);
8209 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8210 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8211 N1);
8212 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8213 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8214 N1, N2);
8215 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8216 // Because short has a smaller range than ushort, we can actually get away
8217 // with only a single newton step. This requires that we use a weird bias
8218 // of 89, however (again, this has been exhaustively tested).
8219 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8220 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8221 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8222 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8223 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8224 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8225 // Convert back to integer and return.
8226 // return vmovn_s32(vcvt_s32_f32(result));
8227 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8228 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8229 return N0;
8232 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8233 const ARMSubtarget *ST) {
8234 EVT VT = Op.getValueType();
8235 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8236 "unexpected type for custom-lowering ISD::SDIV");
8238 SDLoc dl(Op);
8239 SDValue N0 = Op.getOperand(0);
8240 SDValue N1 = Op.getOperand(1);
8241 SDValue N2, N3;
8243 if (VT == MVT::v8i8) {
8244 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8245 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8247 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8248 DAG.getIntPtrConstant(4, dl));
8249 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8250 DAG.getIntPtrConstant(4, dl));
8251 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8252 DAG.getIntPtrConstant(0, dl));
8253 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8254 DAG.getIntPtrConstant(0, dl));
8256 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8257 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8259 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8260 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8262 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8263 return N0;
8265 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8268 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8269 const ARMSubtarget *ST) {
8270 // TODO: Should this propagate fast-math-flags?
8271 EVT VT = Op.getValueType();
8272 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8273 "unexpected type for custom-lowering ISD::UDIV");
8275 SDLoc dl(Op);
8276 SDValue N0 = Op.getOperand(0);
8277 SDValue N1 = Op.getOperand(1);
8278 SDValue N2, N3;
8280 if (VT == MVT::v8i8) {
8281 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8282 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8284 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8285 DAG.getIntPtrConstant(4, dl));
8286 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8287 DAG.getIntPtrConstant(4, dl));
8288 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8289 DAG.getIntPtrConstant(0, dl));
8290 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8291 DAG.getIntPtrConstant(0, dl));
8293 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8294 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8296 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8297 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8299 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8300 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8301 MVT::i32),
8302 N0);
8303 return N0;
8306 // v4i16 sdiv ... Convert to float.
8307 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8308 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8309 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8310 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8311 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8312 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8314 // Use reciprocal estimate and two refinement steps.
8315 // float4 recip = vrecpeq_f32(yf);
8316 // recip *= vrecpsq_f32(yf, recip);
8317 // recip *= vrecpsq_f32(yf, recip);
8318 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8319 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8320 BN1);
8321 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8322 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8323 BN1, N2);
8324 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8325 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8326 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8327 BN1, N2);
8328 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8329 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8330 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8331 // and that it will never cause us to return an answer too large).
8332 // float4 result = as_float4(as_int4(xf*recip) + 2);
8333 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8334 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8335 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8336 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8337 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8338 // Convert back to integer and return.
8339 // return vmovn_u32(vcvt_s32_f32(result));
8340 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8341 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8342 return N0;
8345 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8346 SDNode *N = Op.getNode();
8347 EVT VT = N->getValueType(0);
8348 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8350 SDValue Carry = Op.getOperand(2);
8352 SDLoc DL(Op);
8354 SDValue Result;
8355 if (Op.getOpcode() == ISD::ADDCARRY) {
8356 // This converts the boolean value carry into the carry flag.
8357 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8359 // Do the addition proper using the carry flag we wanted.
8360 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8361 Op.getOperand(1), Carry);
8363 // Now convert the carry flag into a boolean value.
8364 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8365 } else {
8366 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8367 // have to invert the carry first.
8368 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8369 DAG.getConstant(1, DL, MVT::i32), Carry);
8370 // This converts the boolean value carry into the carry flag.
8371 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8373 // Do the subtraction proper using the carry flag we wanted.
8374 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8375 Op.getOperand(1), Carry);
8377 // Now convert the carry flag into a boolean value.
8378 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8379 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8380 // by ISD::SUBCARRY, so compute 1 - C.
8381 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8382 DAG.getConstant(1, DL, MVT::i32), Carry);
8385 // Return both values.
8386 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8389 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8390 assert(Subtarget->isTargetDarwin());
8392 // For iOS, we want to call an alternative entry point: __sincos_stret,
8393 // return values are passed via sret.
8394 SDLoc dl(Op);
8395 SDValue Arg = Op.getOperand(0);
8396 EVT ArgVT = Arg.getValueType();
8397 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8398 auto PtrVT = getPointerTy(DAG.getDataLayout());
8400 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8401 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8403 // Pair of floats / doubles used to pass the result.
8404 Type *RetTy = StructType::get(ArgTy, ArgTy);
8405 auto &DL = DAG.getDataLayout();
8407 ArgListTy Args;
8408 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8409 SDValue SRet;
8410 if (ShouldUseSRet) {
8411 // Create stack object for sret.
8412 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8413 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8414 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8415 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8417 ArgListEntry Entry;
8418 Entry.Node = SRet;
8419 Entry.Ty = RetTy->getPointerTo();
8420 Entry.IsSExt = false;
8421 Entry.IsZExt = false;
8422 Entry.IsSRet = true;
8423 Args.push_back(Entry);
8424 RetTy = Type::getVoidTy(*DAG.getContext());
8427 ArgListEntry Entry;
8428 Entry.Node = Arg;
8429 Entry.Ty = ArgTy;
8430 Entry.IsSExt = false;
8431 Entry.IsZExt = false;
8432 Args.push_back(Entry);
8434 RTLIB::Libcall LC =
8435 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8436 const char *LibcallName = getLibcallName(LC);
8437 CallingConv::ID CC = getLibcallCallingConv(LC);
8438 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8440 TargetLowering::CallLoweringInfo CLI(DAG);
8441 CLI.setDebugLoc(dl)
8442 .setChain(DAG.getEntryNode())
8443 .setCallee(CC, RetTy, Callee, std::move(Args))
8444 .setDiscardResult(ShouldUseSRet);
8445 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8447 if (!ShouldUseSRet)
8448 return CallResult.first;
8450 SDValue LoadSin =
8451 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8453 // Address of cos field.
8454 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8455 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8456 SDValue LoadCos =
8457 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8459 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8460 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8461 LoadSin.getValue(0), LoadCos.getValue(0));
8464 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8465 bool Signed,
8466 SDValue &Chain) const {
8467 EVT VT = Op.getValueType();
8468 assert((VT == MVT::i32 || VT == MVT::i64) &&
8469 "unexpected type for custom lowering DIV");
8470 SDLoc dl(Op);
8472 const auto &DL = DAG.getDataLayout();
8473 const auto &TLI = DAG.getTargetLoweringInfo();
8475 const char *Name = nullptr;
8476 if (Signed)
8477 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8478 else
8479 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8481 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8483 ARMTargetLowering::ArgListTy Args;
8485 for (auto AI : {1, 0}) {
8486 ArgListEntry Arg;
8487 Arg.Node = Op.getOperand(AI);
8488 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8489 Args.push_back(Arg);
8492 CallLoweringInfo CLI(DAG);
8493 CLI.setDebugLoc(dl)
8494 .setChain(Chain)
8495 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8496 ES, std::move(Args));
8498 return LowerCallTo(CLI).first;
8501 // This is a code size optimisation: return the original SDIV node to
8502 // DAGCombiner when we don't want to expand SDIV into a sequence of
8503 // instructions, and an empty node otherwise which will cause the
8504 // SDIV to be expanded in DAGCombine.
8505 SDValue
8506 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8507 SelectionDAG &DAG,
8508 SmallVectorImpl<SDNode *> &Created) const {
8509 // TODO: Support SREM
8510 if (N->getOpcode() != ISD::SDIV)
8511 return SDValue();
8513 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8514 const bool MinSize = ST.hasMinSize();
8515 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8516 : ST.hasDivideInARMMode();
8518 // Don't touch vector types; rewriting this may lead to scalarizing
8519 // the int divs.
8520 if (N->getOperand(0).getValueType().isVector())
8521 return SDValue();
8523 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8524 // hwdiv support for this to be really profitable.
8525 if (!(MinSize && HasDivide))
8526 return SDValue();
8528 // ARM mode is a bit simpler than Thumb: we can handle large power
8529 // of 2 immediates with 1 mov instruction; no further checks required,
8530 // just return the sdiv node.
8531 if (!ST.isThumb())
8532 return SDValue(N, 0);
8534 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8535 // and thus lose the code size benefits of a MOVS that requires only 2.
8536 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8537 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8538 if (Divisor.sgt(128))
8539 return SDValue();
8541 return SDValue(N, 0);
8544 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8545 bool Signed) const {
8546 assert(Op.getValueType() == MVT::i32 &&
8547 "unexpected type for custom lowering DIV");
8548 SDLoc dl(Op);
8550 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8551 DAG.getEntryNode(), Op.getOperand(1));
8553 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8556 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8557 SDLoc DL(N);
8558 SDValue Op = N->getOperand(1);
8559 if (N->getValueType(0) == MVT::i32)
8560 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8561 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8562 DAG.getConstant(0, DL, MVT::i32));
8563 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8564 DAG.getConstant(1, DL, MVT::i32));
8565 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8566 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8569 void ARMTargetLowering::ExpandDIV_Windows(
8570 SDValue Op, SelectionDAG &DAG, bool Signed,
8571 SmallVectorImpl<SDValue> &Results) const {
8572 const auto &DL = DAG.getDataLayout();
8573 const auto &TLI = DAG.getTargetLoweringInfo();
8575 assert(Op.getValueType() == MVT::i64 &&
8576 "unexpected type for custom lowering DIV");
8577 SDLoc dl(Op);
8579 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8581 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8583 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8584 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8585 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8586 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8588 Results.push_back(Lower);
8589 Results.push_back(Upper);
8592 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8593 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8594 // Acquire/Release load/store is not legal for targets without a dmb or
8595 // equivalent available.
8596 return SDValue();
8598 // Monotonic load/store is legal for all targets.
8599 return Op;
8602 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8603 SmallVectorImpl<SDValue> &Results,
8604 SelectionDAG &DAG,
8605 const ARMSubtarget *Subtarget) {
8606 SDLoc DL(N);
8607 // Under Power Management extensions, the cycle-count is:
8608 // mrc p15, #0, <Rt>, c9, c13, #0
8609 SDValue Ops[] = { N->getOperand(0), // Chain
8610 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8611 DAG.getConstant(15, DL, MVT::i32),
8612 DAG.getConstant(0, DL, MVT::i32),
8613 DAG.getConstant(9, DL, MVT::i32),
8614 DAG.getConstant(13, DL, MVT::i32),
8615 DAG.getConstant(0, DL, MVT::i32)
8618 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8619 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8620 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8621 DAG.getConstant(0, DL, MVT::i32)));
8622 Results.push_back(Cycles32.getValue(1));
8625 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8626 SDLoc dl(V.getNode());
8627 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8628 SDValue VHi = DAG.getAnyExtOrTrunc(
8629 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8630 dl, MVT::i32);
8631 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8632 if (isBigEndian)
8633 std::swap (VLo, VHi);
8634 SDValue RegClass =
8635 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8636 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8637 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8638 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8639 return SDValue(
8640 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8643 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8644 SmallVectorImpl<SDValue> & Results,
8645 SelectionDAG &DAG) {
8646 assert(N->getValueType(0) == MVT::i64 &&
8647 "AtomicCmpSwap on types less than 64 should be legal");
8648 SDValue Ops[] = {N->getOperand(1),
8649 createGPRPairNode(DAG, N->getOperand(2)),
8650 createGPRPairNode(DAG, N->getOperand(3)),
8651 N->getOperand(0)};
8652 SDNode *CmpSwap = DAG.getMachineNode(
8653 ARM::CMP_SWAP_64, SDLoc(N),
8654 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8656 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8657 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8659 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8661 Results.push_back(
8662 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8663 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8664 Results.push_back(
8665 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8666 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8667 Results.push_back(SDValue(CmpSwap, 2));
8670 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8671 SelectionDAG &DAG) {
8672 const auto &TLI = DAG.getTargetLoweringInfo();
8674 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8675 "Custom lowering is MSVCRT specific!");
8677 SDLoc dl(Op);
8678 SDValue Val = Op.getOperand(0);
8679 MVT Ty = Val->getSimpleValueType(0);
8680 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8681 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8682 TLI.getPointerTy(DAG.getDataLayout()));
8684 TargetLowering::ArgListTy Args;
8685 TargetLowering::ArgListEntry Entry;
8687 Entry.Node = Val;
8688 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8689 Entry.IsZExt = true;
8690 Args.push_back(Entry);
8692 Entry.Node = Exponent;
8693 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8694 Entry.IsZExt = true;
8695 Args.push_back(Entry);
8697 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8699 // In the in-chain to the call is the entry node If we are emitting a
8700 // tailcall, the chain will be mutated if the node has a non-entry input
8701 // chain.
8702 SDValue InChain = DAG.getEntryNode();
8703 SDValue TCChain = InChain;
8705 const Function &F = DAG.getMachineFunction().getFunction();
8706 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8707 F.getReturnType() == LCRTy;
8708 if (IsTC)
8709 InChain = TCChain;
8711 TargetLowering::CallLoweringInfo CLI(DAG);
8712 CLI.setDebugLoc(dl)
8713 .setChain(InChain)
8714 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8715 .setTailCall(IsTC);
8716 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8718 // Return the chain (the DAG root) if it is a tail call
8719 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8722 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8723 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8724 switch (Op.getOpcode()) {
8725 default: llvm_unreachable("Don't know how to custom lower this!");
8726 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8727 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8728 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8729 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8730 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8731 case ISD::SELECT: return LowerSELECT(Op, DAG);
8732 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8733 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8734 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8735 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8736 case ISD::VASTART: return LowerVASTART(Op, DAG);
8737 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8738 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8739 case ISD::SINT_TO_FP:
8740 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8741 case ISD::FP_TO_SINT:
8742 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8743 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8744 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8745 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8746 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8747 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8748 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8749 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8750 Subtarget);
8751 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8752 case ISD::SHL:
8753 case ISD::SRL:
8754 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8755 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8756 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8757 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8758 case ISD::SRL_PARTS:
8759 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8760 case ISD::CTTZ:
8761 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8762 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8763 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8764 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8765 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8766 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8767 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8768 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8769 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8770 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8771 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8772 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8773 case ISD::MUL: return LowerMUL(Op, DAG);
8774 case ISD::SDIV:
8775 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8776 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8777 return LowerSDIV(Op, DAG, Subtarget);
8778 case ISD::UDIV:
8779 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8780 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8781 return LowerUDIV(Op, DAG, Subtarget);
8782 case ISD::ADDCARRY:
8783 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8784 case ISD::SADDO:
8785 case ISD::SSUBO:
8786 return LowerSignedALUO(Op, DAG);
8787 case ISD::UADDO:
8788 case ISD::USUBO:
8789 return LowerUnsignedALUO(Op, DAG);
8790 case ISD::ATOMIC_LOAD:
8791 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8792 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8793 case ISD::SDIVREM:
8794 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8795 case ISD::DYNAMIC_STACKALLOC:
8796 if (Subtarget->isTargetWindows())
8797 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8798 llvm_unreachable("Don't know how to custom lower this!");
8799 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8800 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8801 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8802 case ARMISD::WIN__DBZCHK: return SDValue();
8806 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8807 SelectionDAG &DAG) {
8808 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8809 unsigned Opc = 0;
8810 if (IntNo == Intrinsic::arm_smlald)
8811 Opc = ARMISD::SMLALD;
8812 else if (IntNo == Intrinsic::arm_smlaldx)
8813 Opc = ARMISD::SMLALDX;
8814 else if (IntNo == Intrinsic::arm_smlsld)
8815 Opc = ARMISD::SMLSLD;
8816 else if (IntNo == Intrinsic::arm_smlsldx)
8817 Opc = ARMISD::SMLSLDX;
8818 else
8819 return;
8821 SDLoc dl(N);
8822 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8823 N->getOperand(3),
8824 DAG.getConstant(0, dl, MVT::i32));
8825 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8826 N->getOperand(3),
8827 DAG.getConstant(1, dl, MVT::i32));
8829 SDValue LongMul = DAG.getNode(Opc, dl,
8830 DAG.getVTList(MVT::i32, MVT::i32),
8831 N->getOperand(1), N->getOperand(2),
8832 Lo, Hi);
8833 Results.push_back(LongMul.getValue(0));
8834 Results.push_back(LongMul.getValue(1));
8837 /// ReplaceNodeResults - Replace the results of node with an illegal result
8838 /// type with new values built out of custom code.
8839 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8840 SmallVectorImpl<SDValue> &Results,
8841 SelectionDAG &DAG) const {
8842 SDValue Res;
8843 switch (N->getOpcode()) {
8844 default:
8845 llvm_unreachable("Don't know how to custom expand this!");
8846 case ISD::READ_REGISTER:
8847 ExpandREAD_REGISTER(N, Results, DAG);
8848 break;
8849 case ISD::BITCAST:
8850 Res = ExpandBITCAST(N, DAG, Subtarget);
8851 break;
8852 case ISD::SRL:
8853 case ISD::SRA:
8854 case ISD::SHL:
8855 Res = Expand64BitShift(N, DAG, Subtarget);
8856 break;
8857 case ISD::SREM:
8858 case ISD::UREM:
8859 Res = LowerREM(N, DAG);
8860 break;
8861 case ISD::SDIVREM:
8862 case ISD::UDIVREM:
8863 Res = LowerDivRem(SDValue(N, 0), DAG);
8864 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8865 Results.push_back(Res.getValue(0));
8866 Results.push_back(Res.getValue(1));
8867 return;
8868 case ISD::READCYCLECOUNTER:
8869 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8870 return;
8871 case ISD::UDIV:
8872 case ISD::SDIV:
8873 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8874 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8875 Results);
8876 case ISD::ATOMIC_CMP_SWAP:
8877 ReplaceCMP_SWAP_64Results(N, Results, DAG);
8878 return;
8879 case ISD::INTRINSIC_WO_CHAIN:
8880 return ReplaceLongIntrinsic(N, Results, DAG);
8881 case ISD::ABS:
8882 lowerABS(N, Results, DAG);
8883 return ;
8886 if (Res.getNode())
8887 Results.push_back(Res);
8890 //===----------------------------------------------------------------------===//
8891 // ARM Scheduler Hooks
8892 //===----------------------------------------------------------------------===//
8894 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8895 /// registers the function context.
8896 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8897 MachineBasicBlock *MBB,
8898 MachineBasicBlock *DispatchBB,
8899 int FI) const {
8900 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8901 "ROPI/RWPI not currently supported with SjLj");
8902 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8903 DebugLoc dl = MI.getDebugLoc();
8904 MachineFunction *MF = MBB->getParent();
8905 MachineRegisterInfo *MRI = &MF->getRegInfo();
8906 MachineConstantPool *MCP = MF->getConstantPool();
8907 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8908 const Function &F = MF->getFunction();
8910 bool isThumb = Subtarget->isThumb();
8911 bool isThumb2 = Subtarget->isThumb2();
8913 unsigned PCLabelId = AFI->createPICLabelUId();
8914 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8915 ARMConstantPoolValue *CPV =
8916 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8917 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8919 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8920 : &ARM::GPRRegClass;
8922 // Grab constant pool and fixed stack memory operands.
8923 MachineMemOperand *CPMMO =
8924 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8925 MachineMemOperand::MOLoad, 4, 4);
8927 MachineMemOperand *FIMMOSt =
8928 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8929 MachineMemOperand::MOStore, 4, 4);
8931 // Load the address of the dispatch MBB into the jump buffer.
8932 if (isThumb2) {
8933 // Incoming value: jbuf
8934 // ldr.n r5, LCPI1_1
8935 // orr r5, r5, #1
8936 // add r5, pc
8937 // str r5, [$jbuf, #+4] ; &jbuf[1]
8938 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8939 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8940 .addConstantPoolIndex(CPI)
8941 .addMemOperand(CPMMO)
8942 .add(predOps(ARMCC::AL));
8943 // Set the low bit because of thumb mode.
8944 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8945 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8946 .addReg(NewVReg1, RegState::Kill)
8947 .addImm(0x01)
8948 .add(predOps(ARMCC::AL))
8949 .add(condCodeOp());
8950 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8951 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8952 .addReg(NewVReg2, RegState::Kill)
8953 .addImm(PCLabelId);
8954 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8955 .addReg(NewVReg3, RegState::Kill)
8956 .addFrameIndex(FI)
8957 .addImm(36) // &jbuf[1] :: pc
8958 .addMemOperand(FIMMOSt)
8959 .add(predOps(ARMCC::AL));
8960 } else if (isThumb) {
8961 // Incoming value: jbuf
8962 // ldr.n r1, LCPI1_4
8963 // add r1, pc
8964 // mov r2, #1
8965 // orrs r1, r2
8966 // add r2, $jbuf, #+4 ; &jbuf[1]
8967 // str r1, [r2]
8968 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8969 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8970 .addConstantPoolIndex(CPI)
8971 .addMemOperand(CPMMO)
8972 .add(predOps(ARMCC::AL));
8973 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8974 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8975 .addReg(NewVReg1, RegState::Kill)
8976 .addImm(PCLabelId);
8977 // Set the low bit because of thumb mode.
8978 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8979 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8980 .addReg(ARM::CPSR, RegState::Define)
8981 .addImm(1)
8982 .add(predOps(ARMCC::AL));
8983 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8984 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8985 .addReg(ARM::CPSR, RegState::Define)
8986 .addReg(NewVReg2, RegState::Kill)
8987 .addReg(NewVReg3, RegState::Kill)
8988 .add(predOps(ARMCC::AL));
8989 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8990 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8991 .addFrameIndex(FI)
8992 .addImm(36); // &jbuf[1] :: pc
8993 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8994 .addReg(NewVReg4, RegState::Kill)
8995 .addReg(NewVReg5, RegState::Kill)
8996 .addImm(0)
8997 .addMemOperand(FIMMOSt)
8998 .add(predOps(ARMCC::AL));
8999 } else {
9000 // Incoming value: jbuf
9001 // ldr r1, LCPI1_1
9002 // add r1, pc, r1
9003 // str r1, [$jbuf, #+4] ; &jbuf[1]
9004 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9005 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9006 .addConstantPoolIndex(CPI)
9007 .addImm(0)
9008 .addMemOperand(CPMMO)
9009 .add(predOps(ARMCC::AL));
9010 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
9011 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9012 .addReg(NewVReg1, RegState::Kill)
9013 .addImm(PCLabelId)
9014 .add(predOps(ARMCC::AL));
9015 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9016 .addReg(NewVReg2, RegState::Kill)
9017 .addFrameIndex(FI)
9018 .addImm(36) // &jbuf[1] :: pc
9019 .addMemOperand(FIMMOSt)
9020 .add(predOps(ARMCC::AL));
9024 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9025 MachineBasicBlock *MBB) const {
9026 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9027 DebugLoc dl = MI.getDebugLoc();
9028 MachineFunction *MF = MBB->getParent();
9029 MachineRegisterInfo *MRI = &MF->getRegInfo();
9030 MachineFrameInfo &MFI = MF->getFrameInfo();
9031 int FI = MFI.getFunctionContextIndex();
9033 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9034 : &ARM::GPRnopcRegClass;
9036 // Get a mapping of the call site numbers to all of the landing pads they're
9037 // associated with.
9038 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9039 unsigned MaxCSNum = 0;
9040 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9041 ++BB) {
9042 if (!BB->isEHPad()) continue;
9044 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9045 // pad.
9046 for (MachineBasicBlock::iterator
9047 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9048 if (!II->isEHLabel()) continue;
9050 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9051 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9053 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9054 for (SmallVectorImpl<unsigned>::iterator
9055 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9056 CSI != CSE; ++CSI) {
9057 CallSiteNumToLPad[*CSI].push_back(&*BB);
9058 MaxCSNum = std::max(MaxCSNum, *CSI);
9060 break;
9064 // Get an ordered list of the machine basic blocks for the jump table.
9065 std::vector<MachineBasicBlock*> LPadList;
9066 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9067 LPadList.reserve(CallSiteNumToLPad.size());
9068 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9069 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9070 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9071 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9072 LPadList.push_back(*II);
9073 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9077 assert(!LPadList.empty() &&
9078 "No landing pad destinations for the dispatch jump table!");
9080 // Create the jump table and associated information.
9081 MachineJumpTableInfo *JTI =
9082 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9083 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9085 // Create the MBBs for the dispatch code.
9087 // Shove the dispatch's address into the return slot in the function context.
9088 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9089 DispatchBB->setIsEHPad();
9091 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9092 unsigned trap_opcode;
9093 if (Subtarget->isThumb())
9094 trap_opcode = ARM::tTRAP;
9095 else
9096 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9098 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9099 DispatchBB->addSuccessor(TrapBB);
9101 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9102 DispatchBB->addSuccessor(DispContBB);
9104 // Insert and MBBs.
9105 MF->insert(MF->end(), DispatchBB);
9106 MF->insert(MF->end(), DispContBB);
9107 MF->insert(MF->end(), TrapBB);
9109 // Insert code into the entry block that creates and registers the function
9110 // context.
9111 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9113 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9114 MachinePointerInfo::getFixedStack(*MF, FI),
9115 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9117 MachineInstrBuilder MIB;
9118 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9120 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9121 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9123 // Add a register mask with no preserved registers. This results in all
9124 // registers being marked as clobbered. This can't work if the dispatch block
9125 // is in a Thumb1 function and is linked with ARM code which uses the FP
9126 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9127 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9129 bool IsPositionIndependent = isPositionIndependent();
9130 unsigned NumLPads = LPadList.size();
9131 if (Subtarget->isThumb2()) {
9132 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9133 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9134 .addFrameIndex(FI)
9135 .addImm(4)
9136 .addMemOperand(FIMMOLd)
9137 .add(predOps(ARMCC::AL));
9139 if (NumLPads < 256) {
9140 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9141 .addReg(NewVReg1)
9142 .addImm(LPadList.size())
9143 .add(predOps(ARMCC::AL));
9144 } else {
9145 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9146 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9147 .addImm(NumLPads & 0xFFFF)
9148 .add(predOps(ARMCC::AL));
9150 unsigned VReg2 = VReg1;
9151 if ((NumLPads & 0xFFFF0000) != 0) {
9152 VReg2 = MRI->createVirtualRegister(TRC);
9153 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9154 .addReg(VReg1)
9155 .addImm(NumLPads >> 16)
9156 .add(predOps(ARMCC::AL));
9159 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9160 .addReg(NewVReg1)
9161 .addReg(VReg2)
9162 .add(predOps(ARMCC::AL));
9165 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9166 .addMBB(TrapBB)
9167 .addImm(ARMCC::HI)
9168 .addReg(ARM::CPSR);
9170 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9171 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9172 .addJumpTableIndex(MJTI)
9173 .add(predOps(ARMCC::AL));
9175 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9176 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9177 .addReg(NewVReg3, RegState::Kill)
9178 .addReg(NewVReg1)
9179 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9180 .add(predOps(ARMCC::AL))
9181 .add(condCodeOp());
9183 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9184 .addReg(NewVReg4, RegState::Kill)
9185 .addReg(NewVReg1)
9186 .addJumpTableIndex(MJTI);
9187 } else if (Subtarget->isThumb()) {
9188 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9189 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9190 .addFrameIndex(FI)
9191 .addImm(1)
9192 .addMemOperand(FIMMOLd)
9193 .add(predOps(ARMCC::AL));
9195 if (NumLPads < 256) {
9196 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9197 .addReg(NewVReg1)
9198 .addImm(NumLPads)
9199 .add(predOps(ARMCC::AL));
9200 } else {
9201 MachineConstantPool *ConstantPool = MF->getConstantPool();
9202 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9203 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9205 // MachineConstantPool wants an explicit alignment.
9206 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9207 if (Align == 0)
9208 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9209 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9211 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9212 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9213 .addReg(VReg1, RegState::Define)
9214 .addConstantPoolIndex(Idx)
9215 .add(predOps(ARMCC::AL));
9216 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9217 .addReg(NewVReg1)
9218 .addReg(VReg1)
9219 .add(predOps(ARMCC::AL));
9222 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9223 .addMBB(TrapBB)
9224 .addImm(ARMCC::HI)
9225 .addReg(ARM::CPSR);
9227 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
9228 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9229 .addReg(ARM::CPSR, RegState::Define)
9230 .addReg(NewVReg1)
9231 .addImm(2)
9232 .add(predOps(ARMCC::AL));
9234 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9235 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9236 .addJumpTableIndex(MJTI)
9237 .add(predOps(ARMCC::AL));
9239 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9240 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9241 .addReg(ARM::CPSR, RegState::Define)
9242 .addReg(NewVReg2, RegState::Kill)
9243 .addReg(NewVReg3)
9244 .add(predOps(ARMCC::AL));
9246 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9247 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9249 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
9250 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9251 .addReg(NewVReg4, RegState::Kill)
9252 .addImm(0)
9253 .addMemOperand(JTMMOLd)
9254 .add(predOps(ARMCC::AL));
9256 unsigned NewVReg6 = NewVReg5;
9257 if (IsPositionIndependent) {
9258 NewVReg6 = MRI->createVirtualRegister(TRC);
9259 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9260 .addReg(ARM::CPSR, RegState::Define)
9261 .addReg(NewVReg5, RegState::Kill)
9262 .addReg(NewVReg3)
9263 .add(predOps(ARMCC::AL));
9266 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9267 .addReg(NewVReg6, RegState::Kill)
9268 .addJumpTableIndex(MJTI);
9269 } else {
9270 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
9271 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9272 .addFrameIndex(FI)
9273 .addImm(4)
9274 .addMemOperand(FIMMOLd)
9275 .add(predOps(ARMCC::AL));
9277 if (NumLPads < 256) {
9278 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9279 .addReg(NewVReg1)
9280 .addImm(NumLPads)
9281 .add(predOps(ARMCC::AL));
9282 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9283 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9284 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9285 .addImm(NumLPads & 0xFFFF)
9286 .add(predOps(ARMCC::AL));
9288 unsigned VReg2 = VReg1;
9289 if ((NumLPads & 0xFFFF0000) != 0) {
9290 VReg2 = MRI->createVirtualRegister(TRC);
9291 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9292 .addReg(VReg1)
9293 .addImm(NumLPads >> 16)
9294 .add(predOps(ARMCC::AL));
9297 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9298 .addReg(NewVReg1)
9299 .addReg(VReg2)
9300 .add(predOps(ARMCC::AL));
9301 } else {
9302 MachineConstantPool *ConstantPool = MF->getConstantPool();
9303 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9304 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9306 // MachineConstantPool wants an explicit alignment.
9307 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9308 if (Align == 0)
9309 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9310 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9312 unsigned VReg1 = MRI->createVirtualRegister(TRC);
9313 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9314 .addReg(VReg1, RegState::Define)
9315 .addConstantPoolIndex(Idx)
9316 .addImm(0)
9317 .add(predOps(ARMCC::AL));
9318 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9319 .addReg(NewVReg1)
9320 .addReg(VReg1, RegState::Kill)
9321 .add(predOps(ARMCC::AL));
9324 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9325 .addMBB(TrapBB)
9326 .addImm(ARMCC::HI)
9327 .addReg(ARM::CPSR);
9329 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
9330 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9331 .addReg(NewVReg1)
9332 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9333 .add(predOps(ARMCC::AL))
9334 .add(condCodeOp());
9335 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
9336 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9337 .addJumpTableIndex(MJTI)
9338 .add(predOps(ARMCC::AL));
9340 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9341 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9342 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
9343 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9344 .addReg(NewVReg3, RegState::Kill)
9345 .addReg(NewVReg4)
9346 .addImm(0)
9347 .addMemOperand(JTMMOLd)
9348 .add(predOps(ARMCC::AL));
9350 if (IsPositionIndependent) {
9351 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9352 .addReg(NewVReg5, RegState::Kill)
9353 .addReg(NewVReg4)
9354 .addJumpTableIndex(MJTI);
9355 } else {
9356 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9357 .addReg(NewVReg5, RegState::Kill)
9358 .addJumpTableIndex(MJTI);
9362 // Add the jump table entries as successors to the MBB.
9363 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9364 for (std::vector<MachineBasicBlock*>::iterator
9365 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9366 MachineBasicBlock *CurMBB = *I;
9367 if (SeenMBBs.insert(CurMBB).second)
9368 DispContBB->addSuccessor(CurMBB);
9371 // N.B. the order the invoke BBs are processed in doesn't matter here.
9372 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9373 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9374 for (MachineBasicBlock *BB : InvokeBBs) {
9376 // Remove the landing pad successor from the invoke block and replace it
9377 // with the new dispatch block.
9378 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9379 BB->succ_end());
9380 while (!Successors.empty()) {
9381 MachineBasicBlock *SMBB = Successors.pop_back_val();
9382 if (SMBB->isEHPad()) {
9383 BB->removeSuccessor(SMBB);
9384 MBBLPads.push_back(SMBB);
9388 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9389 BB->normalizeSuccProbs();
9391 // Find the invoke call and mark all of the callee-saved registers as
9392 // 'implicit defined' so that they're spilled. This prevents code from
9393 // moving instructions to before the EH block, where they will never be
9394 // executed.
9395 for (MachineBasicBlock::reverse_iterator
9396 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9397 if (!II->isCall()) continue;
9399 DenseMap<unsigned, bool> DefRegs;
9400 for (MachineInstr::mop_iterator
9401 OI = II->operands_begin(), OE = II->operands_end();
9402 OI != OE; ++OI) {
9403 if (!OI->isReg()) continue;
9404 DefRegs[OI->getReg()] = true;
9407 MachineInstrBuilder MIB(*MF, &*II);
9409 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9410 unsigned Reg = SavedRegs[i];
9411 if (Subtarget->isThumb2() &&
9412 !ARM::tGPRRegClass.contains(Reg) &&
9413 !ARM::hGPRRegClass.contains(Reg))
9414 continue;
9415 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9416 continue;
9417 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9418 continue;
9419 if (!DefRegs[Reg])
9420 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9423 break;
9427 // Mark all former landing pads as non-landing pads. The dispatch is the only
9428 // landing pad now.
9429 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9430 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9431 (*I)->setIsEHPad(false);
9433 // The instruction is gone now.
9434 MI.eraseFromParent();
9437 static
9438 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9439 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9440 E = MBB->succ_end(); I != E; ++I)
9441 if (*I != Succ)
9442 return *I;
9443 llvm_unreachable("Expecting a BB with two successors!");
9446 /// Return the load opcode for a given load size. If load size >= 8,
9447 /// neon opcode will be returned.
9448 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9449 if (LdSize >= 8)
9450 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9451 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9452 if (IsThumb1)
9453 return LdSize == 4 ? ARM::tLDRi
9454 : LdSize == 2 ? ARM::tLDRHi
9455 : LdSize == 1 ? ARM::tLDRBi : 0;
9456 if (IsThumb2)
9457 return LdSize == 4 ? ARM::t2LDR_POST
9458 : LdSize == 2 ? ARM::t2LDRH_POST
9459 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9460 return LdSize == 4 ? ARM::LDR_POST_IMM
9461 : LdSize == 2 ? ARM::LDRH_POST
9462 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9465 /// Return the store opcode for a given store size. If store size >= 8,
9466 /// neon opcode will be returned.
9467 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9468 if (StSize >= 8)
9469 return StSize == 16 ? ARM::VST1q32wb_fixed
9470 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9471 if (IsThumb1)
9472 return StSize == 4 ? ARM::tSTRi
9473 : StSize == 2 ? ARM::tSTRHi
9474 : StSize == 1 ? ARM::tSTRBi : 0;
9475 if (IsThumb2)
9476 return StSize == 4 ? ARM::t2STR_POST
9477 : StSize == 2 ? ARM::t2STRH_POST
9478 : StSize == 1 ? ARM::t2STRB_POST : 0;
9479 return StSize == 4 ? ARM::STR_POST_IMM
9480 : StSize == 2 ? ARM::STRH_POST
9481 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9484 /// Emit a post-increment load operation with given size. The instructions
9485 /// will be added to BB at Pos.
9486 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9487 const TargetInstrInfo *TII, const DebugLoc &dl,
9488 unsigned LdSize, unsigned Data, unsigned AddrIn,
9489 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9490 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9491 assert(LdOpc != 0 && "Should have a load opcode");
9492 if (LdSize >= 8) {
9493 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9494 .addReg(AddrOut, RegState::Define)
9495 .addReg(AddrIn)
9496 .addImm(0)
9497 .add(predOps(ARMCC::AL));
9498 } else if (IsThumb1) {
9499 // load + update AddrIn
9500 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9501 .addReg(AddrIn)
9502 .addImm(0)
9503 .add(predOps(ARMCC::AL));
9504 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9505 .add(t1CondCodeOp())
9506 .addReg(AddrIn)
9507 .addImm(LdSize)
9508 .add(predOps(ARMCC::AL));
9509 } else if (IsThumb2) {
9510 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9511 .addReg(AddrOut, RegState::Define)
9512 .addReg(AddrIn)
9513 .addImm(LdSize)
9514 .add(predOps(ARMCC::AL));
9515 } else { // arm
9516 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9517 .addReg(AddrOut, RegState::Define)
9518 .addReg(AddrIn)
9519 .addReg(0)
9520 .addImm(LdSize)
9521 .add(predOps(ARMCC::AL));
9525 /// Emit a post-increment store operation with given size. The instructions
9526 /// will be added to BB at Pos.
9527 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9528 const TargetInstrInfo *TII, const DebugLoc &dl,
9529 unsigned StSize, unsigned Data, unsigned AddrIn,
9530 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9531 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9532 assert(StOpc != 0 && "Should have a store opcode");
9533 if (StSize >= 8) {
9534 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9535 .addReg(AddrIn)
9536 .addImm(0)
9537 .addReg(Data)
9538 .add(predOps(ARMCC::AL));
9539 } else if (IsThumb1) {
9540 // store + update AddrIn
9541 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9542 .addReg(Data)
9543 .addReg(AddrIn)
9544 .addImm(0)
9545 .add(predOps(ARMCC::AL));
9546 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9547 .add(t1CondCodeOp())
9548 .addReg(AddrIn)
9549 .addImm(StSize)
9550 .add(predOps(ARMCC::AL));
9551 } else if (IsThumb2) {
9552 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9553 .addReg(Data)
9554 .addReg(AddrIn)
9555 .addImm(StSize)
9556 .add(predOps(ARMCC::AL));
9557 } else { // arm
9558 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9559 .addReg(Data)
9560 .addReg(AddrIn)
9561 .addReg(0)
9562 .addImm(StSize)
9563 .add(predOps(ARMCC::AL));
9567 MachineBasicBlock *
9568 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9569 MachineBasicBlock *BB) const {
9570 // This pseudo instruction has 3 operands: dst, src, size
9571 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9572 // Otherwise, we will generate unrolled scalar copies.
9573 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9574 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9575 MachineFunction::iterator It = ++BB->getIterator();
9577 unsigned dest = MI.getOperand(0).getReg();
9578 unsigned src = MI.getOperand(1).getReg();
9579 unsigned SizeVal = MI.getOperand(2).getImm();
9580 unsigned Align = MI.getOperand(3).getImm();
9581 DebugLoc dl = MI.getDebugLoc();
9583 MachineFunction *MF = BB->getParent();
9584 MachineRegisterInfo &MRI = MF->getRegInfo();
9585 unsigned UnitSize = 0;
9586 const TargetRegisterClass *TRC = nullptr;
9587 const TargetRegisterClass *VecTRC = nullptr;
9589 bool IsThumb1 = Subtarget->isThumb1Only();
9590 bool IsThumb2 = Subtarget->isThumb2();
9591 bool IsThumb = Subtarget->isThumb();
9593 if (Align & 1) {
9594 UnitSize = 1;
9595 } else if (Align & 2) {
9596 UnitSize = 2;
9597 } else {
9598 // Check whether we can use NEON instructions.
9599 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9600 Subtarget->hasNEON()) {
9601 if ((Align % 16 == 0) && SizeVal >= 16)
9602 UnitSize = 16;
9603 else if ((Align % 8 == 0) && SizeVal >= 8)
9604 UnitSize = 8;
9606 // Can't use NEON instructions.
9607 if (UnitSize == 0)
9608 UnitSize = 4;
9611 // Select the correct opcode and register class for unit size load/store
9612 bool IsNeon = UnitSize >= 8;
9613 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9614 if (IsNeon)
9615 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9616 : UnitSize == 8 ? &ARM::DPRRegClass
9617 : nullptr;
9619 unsigned BytesLeft = SizeVal % UnitSize;
9620 unsigned LoopSize = SizeVal - BytesLeft;
9622 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9623 // Use LDR and STR to copy.
9624 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9625 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9626 unsigned srcIn = src;
9627 unsigned destIn = dest;
9628 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9629 unsigned srcOut = MRI.createVirtualRegister(TRC);
9630 unsigned destOut = MRI.createVirtualRegister(TRC);
9631 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9632 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9633 IsThumb1, IsThumb2);
9634 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9635 IsThumb1, IsThumb2);
9636 srcIn = srcOut;
9637 destIn = destOut;
9640 // Handle the leftover bytes with LDRB and STRB.
9641 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9642 // [destOut] = STRB_POST(scratch, destIn, 1)
9643 for (unsigned i = 0; i < BytesLeft; i++) {
9644 unsigned srcOut = MRI.createVirtualRegister(TRC);
9645 unsigned destOut = MRI.createVirtualRegister(TRC);
9646 unsigned scratch = MRI.createVirtualRegister(TRC);
9647 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9648 IsThumb1, IsThumb2);
9649 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9650 IsThumb1, IsThumb2);
9651 srcIn = srcOut;
9652 destIn = destOut;
9654 MI.eraseFromParent(); // The instruction is gone now.
9655 return BB;
9658 // Expand the pseudo op to a loop.
9659 // thisMBB:
9660 // ...
9661 // movw varEnd, # --> with thumb2
9662 // movt varEnd, #
9663 // ldrcp varEnd, idx --> without thumb2
9664 // fallthrough --> loopMBB
9665 // loopMBB:
9666 // PHI varPhi, varEnd, varLoop
9667 // PHI srcPhi, src, srcLoop
9668 // PHI destPhi, dst, destLoop
9669 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9670 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9671 // subs varLoop, varPhi, #UnitSize
9672 // bne loopMBB
9673 // fallthrough --> exitMBB
9674 // exitMBB:
9675 // epilogue to handle left-over bytes
9676 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9677 // [destOut] = STRB_POST(scratch, destLoop, 1)
9678 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9679 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9680 MF->insert(It, loopMBB);
9681 MF->insert(It, exitMBB);
9683 // Transfer the remainder of BB and its successor edges to exitMBB.
9684 exitMBB->splice(exitMBB->begin(), BB,
9685 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9686 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9688 // Load an immediate to varEnd.
9689 unsigned varEnd = MRI.createVirtualRegister(TRC);
9690 if (Subtarget->useMovt()) {
9691 unsigned Vtmp = varEnd;
9692 if ((LoopSize & 0xFFFF0000) != 0)
9693 Vtmp = MRI.createVirtualRegister(TRC);
9694 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9695 .addImm(LoopSize & 0xFFFF)
9696 .add(predOps(ARMCC::AL));
9698 if ((LoopSize & 0xFFFF0000) != 0)
9699 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9700 .addReg(Vtmp)
9701 .addImm(LoopSize >> 16)
9702 .add(predOps(ARMCC::AL));
9703 } else {
9704 MachineConstantPool *ConstantPool = MF->getConstantPool();
9705 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9706 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9708 // MachineConstantPool wants an explicit alignment.
9709 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9710 if (Align == 0)
9711 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9712 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9713 MachineMemOperand *CPMMO =
9714 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9715 MachineMemOperand::MOLoad, 4, 4);
9717 if (IsThumb)
9718 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9719 .addReg(varEnd, RegState::Define)
9720 .addConstantPoolIndex(Idx)
9721 .add(predOps(ARMCC::AL))
9722 .addMemOperand(CPMMO);
9723 else
9724 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9725 .addReg(varEnd, RegState::Define)
9726 .addConstantPoolIndex(Idx)
9727 .addImm(0)
9728 .add(predOps(ARMCC::AL))
9729 .addMemOperand(CPMMO);
9731 BB->addSuccessor(loopMBB);
9733 // Generate the loop body:
9734 // varPhi = PHI(varLoop, varEnd)
9735 // srcPhi = PHI(srcLoop, src)
9736 // destPhi = PHI(destLoop, dst)
9737 MachineBasicBlock *entryBB = BB;
9738 BB = loopMBB;
9739 unsigned varLoop = MRI.createVirtualRegister(TRC);
9740 unsigned varPhi = MRI.createVirtualRegister(TRC);
9741 unsigned srcLoop = MRI.createVirtualRegister(TRC);
9742 unsigned srcPhi = MRI.createVirtualRegister(TRC);
9743 unsigned destLoop = MRI.createVirtualRegister(TRC);
9744 unsigned destPhi = MRI.createVirtualRegister(TRC);
9746 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9747 .addReg(varLoop).addMBB(loopMBB)
9748 .addReg(varEnd).addMBB(entryBB);
9749 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9750 .addReg(srcLoop).addMBB(loopMBB)
9751 .addReg(src).addMBB(entryBB);
9752 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9753 .addReg(destLoop).addMBB(loopMBB)
9754 .addReg(dest).addMBB(entryBB);
9756 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9757 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9758 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9759 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9760 IsThumb1, IsThumb2);
9761 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9762 IsThumb1, IsThumb2);
9764 // Decrement loop variable by UnitSize.
9765 if (IsThumb1) {
9766 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9767 .add(t1CondCodeOp())
9768 .addReg(varPhi)
9769 .addImm(UnitSize)
9770 .add(predOps(ARMCC::AL));
9771 } else {
9772 MachineInstrBuilder MIB =
9773 BuildMI(*BB, BB->end(), dl,
9774 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9775 MIB.addReg(varPhi)
9776 .addImm(UnitSize)
9777 .add(predOps(ARMCC::AL))
9778 .add(condCodeOp());
9779 MIB->getOperand(5).setReg(ARM::CPSR);
9780 MIB->getOperand(5).setIsDef(true);
9782 BuildMI(*BB, BB->end(), dl,
9783 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9784 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9786 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9787 BB->addSuccessor(loopMBB);
9788 BB->addSuccessor(exitMBB);
9790 // Add epilogue to handle BytesLeft.
9791 BB = exitMBB;
9792 auto StartOfExit = exitMBB->begin();
9794 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9795 // [destOut] = STRB_POST(scratch, destLoop, 1)
9796 unsigned srcIn = srcLoop;
9797 unsigned destIn = destLoop;
9798 for (unsigned i = 0; i < BytesLeft; i++) {
9799 unsigned srcOut = MRI.createVirtualRegister(TRC);
9800 unsigned destOut = MRI.createVirtualRegister(TRC);
9801 unsigned scratch = MRI.createVirtualRegister(TRC);
9802 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9803 IsThumb1, IsThumb2);
9804 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9805 IsThumb1, IsThumb2);
9806 srcIn = srcOut;
9807 destIn = destOut;
9810 MI.eraseFromParent(); // The instruction is gone now.
9811 return BB;
9814 MachineBasicBlock *
9815 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9816 MachineBasicBlock *MBB) const {
9817 const TargetMachine &TM = getTargetMachine();
9818 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9819 DebugLoc DL = MI.getDebugLoc();
9821 assert(Subtarget->isTargetWindows() &&
9822 "__chkstk is only supported on Windows");
9823 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9825 // __chkstk takes the number of words to allocate on the stack in R4, and
9826 // returns the stack adjustment in number of bytes in R4. This will not
9827 // clober any other registers (other than the obvious lr).
9829 // Although, technically, IP should be considered a register which may be
9830 // clobbered, the call itself will not touch it. Windows on ARM is a pure
9831 // thumb-2 environment, so there is no interworking required. As a result, we
9832 // do not expect a veneer to be emitted by the linker, clobbering IP.
9834 // Each module receives its own copy of __chkstk, so no import thunk is
9835 // required, again, ensuring that IP is not clobbered.
9837 // Finally, although some linkers may theoretically provide a trampoline for
9838 // out of range calls (which is quite common due to a 32M range limitation of
9839 // branches for Thumb), we can generate the long-call version via
9840 // -mcmodel=large, alleviating the need for the trampoline which may clobber
9841 // IP.
9843 switch (TM.getCodeModel()) {
9844 case CodeModel::Tiny:
9845 llvm_unreachable("Tiny code model not available on ARM.");
9846 case CodeModel::Small:
9847 case CodeModel::Medium:
9848 case CodeModel::Kernel:
9849 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9850 .add(predOps(ARMCC::AL))
9851 .addExternalSymbol("__chkstk")
9852 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9853 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9854 .addReg(ARM::R12,
9855 RegState::Implicit | RegState::Define | RegState::Dead)
9856 .addReg(ARM::CPSR,
9857 RegState::Implicit | RegState::Define | RegState::Dead);
9858 break;
9859 case CodeModel::Large: {
9860 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9861 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9863 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9864 .addExternalSymbol("__chkstk");
9865 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9866 .add(predOps(ARMCC::AL))
9867 .addReg(Reg, RegState::Kill)
9868 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9869 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9870 .addReg(ARM::R12,
9871 RegState::Implicit | RegState::Define | RegState::Dead)
9872 .addReg(ARM::CPSR,
9873 RegState::Implicit | RegState::Define | RegState::Dead);
9874 break;
9878 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9879 .addReg(ARM::SP, RegState::Kill)
9880 .addReg(ARM::R4, RegState::Kill)
9881 .setMIFlags(MachineInstr::FrameSetup)
9882 .add(predOps(ARMCC::AL))
9883 .add(condCodeOp());
9885 MI.eraseFromParent();
9886 return MBB;
9889 MachineBasicBlock *
9890 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9891 MachineBasicBlock *MBB) const {
9892 DebugLoc DL = MI.getDebugLoc();
9893 MachineFunction *MF = MBB->getParent();
9894 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9896 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9897 MF->insert(++MBB->getIterator(), ContBB);
9898 ContBB->splice(ContBB->begin(), MBB,
9899 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9900 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9901 MBB->addSuccessor(ContBB);
9903 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9904 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9905 MF->push_back(TrapBB);
9906 MBB->addSuccessor(TrapBB);
9908 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9909 .addReg(MI.getOperand(0).getReg())
9910 .addImm(0)
9911 .add(predOps(ARMCC::AL));
9912 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9913 .addMBB(TrapBB)
9914 .addImm(ARMCC::EQ)
9915 .addReg(ARM::CPSR);
9917 MI.eraseFromParent();
9918 return ContBB;
9921 // The CPSR operand of SelectItr might be missing a kill marker
9922 // because there were multiple uses of CPSR, and ISel didn't know
9923 // which to mark. Figure out whether SelectItr should have had a
9924 // kill marker, and set it if it should. Returns the correct kill
9925 // marker value.
9926 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9927 MachineBasicBlock* BB,
9928 const TargetRegisterInfo* TRI) {
9929 // Scan forward through BB for a use/def of CPSR.
9930 MachineBasicBlock::iterator miI(std::next(SelectItr));
9931 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9932 const MachineInstr& mi = *miI;
9933 if (mi.readsRegister(ARM::CPSR))
9934 return false;
9935 if (mi.definesRegister(ARM::CPSR))
9936 break; // Should have kill-flag - update below.
9939 // If we hit the end of the block, check whether CPSR is live into a
9940 // successor.
9941 if (miI == BB->end()) {
9942 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9943 sEnd = BB->succ_end();
9944 sItr != sEnd; ++sItr) {
9945 MachineBasicBlock* succ = *sItr;
9946 if (succ->isLiveIn(ARM::CPSR))
9947 return false;
9951 // We found a def, or hit the end of the basic block and CPSR wasn't live
9952 // out. SelectMI should have a kill flag on CPSR.
9953 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9954 return true;
9957 MachineBasicBlock *
9958 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9959 MachineBasicBlock *BB) const {
9960 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9961 DebugLoc dl = MI.getDebugLoc();
9962 bool isThumb2 = Subtarget->isThumb2();
9963 switch (MI.getOpcode()) {
9964 default: {
9965 MI.print(errs());
9966 llvm_unreachable("Unexpected instr type to insert");
9969 // Thumb1 post-indexed loads are really just single-register LDMs.
9970 case ARM::tLDR_postidx: {
9971 MachineOperand Def(MI.getOperand(1));
9972 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9973 .add(Def) // Rn_wb
9974 .add(MI.getOperand(2)) // Rn
9975 .add(MI.getOperand(3)) // PredImm
9976 .add(MI.getOperand(4)) // PredReg
9977 .add(MI.getOperand(0)) // Rt
9978 .cloneMemRefs(MI);
9979 MI.eraseFromParent();
9980 return BB;
9983 // The Thumb2 pre-indexed stores have the same MI operands, they just
9984 // define them differently in the .td files from the isel patterns, so
9985 // they need pseudos.
9986 case ARM::t2STR_preidx:
9987 MI.setDesc(TII->get(ARM::t2STR_PRE));
9988 return BB;
9989 case ARM::t2STRB_preidx:
9990 MI.setDesc(TII->get(ARM::t2STRB_PRE));
9991 return BB;
9992 case ARM::t2STRH_preidx:
9993 MI.setDesc(TII->get(ARM::t2STRH_PRE));
9994 return BB;
9996 case ARM::STRi_preidx:
9997 case ARM::STRBi_preidx: {
9998 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9999 : ARM::STRB_PRE_IMM;
10000 // Decode the offset.
10001 unsigned Offset = MI.getOperand(4).getImm();
10002 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10003 Offset = ARM_AM::getAM2Offset(Offset);
10004 if (isSub)
10005 Offset = -Offset;
10007 MachineMemOperand *MMO = *MI.memoperands_begin();
10008 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10009 .add(MI.getOperand(0)) // Rn_wb
10010 .add(MI.getOperand(1)) // Rt
10011 .add(MI.getOperand(2)) // Rn
10012 .addImm(Offset) // offset (skip GPR==zero_reg)
10013 .add(MI.getOperand(5)) // pred
10014 .add(MI.getOperand(6))
10015 .addMemOperand(MMO);
10016 MI.eraseFromParent();
10017 return BB;
10019 case ARM::STRr_preidx:
10020 case ARM::STRBr_preidx:
10021 case ARM::STRH_preidx: {
10022 unsigned NewOpc;
10023 switch (MI.getOpcode()) {
10024 default: llvm_unreachable("unexpected opcode!");
10025 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10026 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10027 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10029 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10030 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10031 MIB.add(MI.getOperand(i));
10032 MI.eraseFromParent();
10033 return BB;
10036 case ARM::tMOVCCr_pseudo: {
10037 // To "insert" a SELECT_CC instruction, we actually have to insert the
10038 // diamond control-flow pattern. The incoming instruction knows the
10039 // destination vreg to set, the condition code register to branch on, the
10040 // true/false values to select between, and a branch opcode to use.
10041 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10042 MachineFunction::iterator It = ++BB->getIterator();
10044 // thisMBB:
10045 // ...
10046 // TrueVal = ...
10047 // cmpTY ccX, r1, r2
10048 // bCC copy1MBB
10049 // fallthrough --> copy0MBB
10050 MachineBasicBlock *thisMBB = BB;
10051 MachineFunction *F = BB->getParent();
10052 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10053 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10054 F->insert(It, copy0MBB);
10055 F->insert(It, sinkMBB);
10057 // Check whether CPSR is live past the tMOVCCr_pseudo.
10058 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10059 if (!MI.killsRegister(ARM::CPSR) &&
10060 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10061 copy0MBB->addLiveIn(ARM::CPSR);
10062 sinkMBB->addLiveIn(ARM::CPSR);
10065 // Transfer the remainder of BB and its successor edges to sinkMBB.
10066 sinkMBB->splice(sinkMBB->begin(), BB,
10067 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10068 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10070 BB->addSuccessor(copy0MBB);
10071 BB->addSuccessor(sinkMBB);
10073 BuildMI(BB, dl, TII->get(ARM::tBcc))
10074 .addMBB(sinkMBB)
10075 .addImm(MI.getOperand(3).getImm())
10076 .addReg(MI.getOperand(4).getReg());
10078 // copy0MBB:
10079 // %FalseValue = ...
10080 // # fallthrough to sinkMBB
10081 BB = copy0MBB;
10083 // Update machine-CFG edges
10084 BB->addSuccessor(sinkMBB);
10086 // sinkMBB:
10087 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10088 // ...
10089 BB = sinkMBB;
10090 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10091 .addReg(MI.getOperand(1).getReg())
10092 .addMBB(copy0MBB)
10093 .addReg(MI.getOperand(2).getReg())
10094 .addMBB(thisMBB);
10096 MI.eraseFromParent(); // The pseudo instruction is gone now.
10097 return BB;
10100 case ARM::BCCi64:
10101 case ARM::BCCZi64: {
10102 // If there is an unconditional branch to the other successor, remove it.
10103 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10105 // Compare both parts that make up the double comparison separately for
10106 // equality.
10107 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10109 unsigned LHS1 = MI.getOperand(1).getReg();
10110 unsigned LHS2 = MI.getOperand(2).getReg();
10111 if (RHSisZero) {
10112 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10113 .addReg(LHS1)
10114 .addImm(0)
10115 .add(predOps(ARMCC::AL));
10116 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10117 .addReg(LHS2).addImm(0)
10118 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10119 } else {
10120 unsigned RHS1 = MI.getOperand(3).getReg();
10121 unsigned RHS2 = MI.getOperand(4).getReg();
10122 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10123 .addReg(LHS1)
10124 .addReg(RHS1)
10125 .add(predOps(ARMCC::AL));
10126 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10127 .addReg(LHS2).addReg(RHS2)
10128 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10131 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10132 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10133 if (MI.getOperand(0).getImm() == ARMCC::NE)
10134 std::swap(destMBB, exitMBB);
10136 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10137 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10138 if (isThumb2)
10139 BuildMI(BB, dl, TII->get(ARM::t2B))
10140 .addMBB(exitMBB)
10141 .add(predOps(ARMCC::AL));
10142 else
10143 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10145 MI.eraseFromParent(); // The pseudo instruction is gone now.
10146 return BB;
10149 case ARM::Int_eh_sjlj_setjmp:
10150 case ARM::Int_eh_sjlj_setjmp_nofp:
10151 case ARM::tInt_eh_sjlj_setjmp:
10152 case ARM::t2Int_eh_sjlj_setjmp:
10153 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10154 return BB;
10156 case ARM::Int_eh_sjlj_setup_dispatch:
10157 EmitSjLjDispatchBlock(MI, BB);
10158 return BB;
10160 case ARM::ABS:
10161 case ARM::t2ABS: {
10162 // To insert an ABS instruction, we have to insert the
10163 // diamond control-flow pattern. The incoming instruction knows the
10164 // source vreg to test against 0, the destination vreg to set,
10165 // the condition code register to branch on, the
10166 // true/false values to select between, and a branch opcode to use.
10167 // It transforms
10168 // V1 = ABS V0
10169 // into
10170 // V2 = MOVS V0
10171 // BCC (branch to SinkBB if V0 >= 0)
10172 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10173 // SinkBB: V1 = PHI(V2, V3)
10174 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10175 MachineFunction::iterator BBI = ++BB->getIterator();
10176 MachineFunction *Fn = BB->getParent();
10177 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10178 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10179 Fn->insert(BBI, RSBBB);
10180 Fn->insert(BBI, SinkBB);
10182 unsigned int ABSSrcReg = MI.getOperand(1).getReg();
10183 unsigned int ABSDstReg = MI.getOperand(0).getReg();
10184 bool ABSSrcKIll = MI.getOperand(1).isKill();
10185 bool isThumb2 = Subtarget->isThumb2();
10186 MachineRegisterInfo &MRI = Fn->getRegInfo();
10187 // In Thumb mode S must not be specified if source register is the SP or
10188 // PC and if destination register is the SP, so restrict register class
10189 unsigned NewRsbDstReg =
10190 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10192 // Transfer the remainder of BB and its successor edges to sinkMBB.
10193 SinkBB->splice(SinkBB->begin(), BB,
10194 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10195 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10197 BB->addSuccessor(RSBBB);
10198 BB->addSuccessor(SinkBB);
10200 // fall through to SinkMBB
10201 RSBBB->addSuccessor(SinkBB);
10203 // insert a cmp at the end of BB
10204 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10205 .addReg(ABSSrcReg)
10206 .addImm(0)
10207 .add(predOps(ARMCC::AL));
10209 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10210 BuildMI(BB, dl,
10211 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10212 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10214 // insert rsbri in RSBBB
10215 // Note: BCC and rsbri will be converted into predicated rsbmi
10216 // by if-conversion pass
10217 BuildMI(*RSBBB, RSBBB->begin(), dl,
10218 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10219 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10220 .addImm(0)
10221 .add(predOps(ARMCC::AL))
10222 .add(condCodeOp());
10224 // insert PHI in SinkBB,
10225 // reuse ABSDstReg to not change uses of ABS instruction
10226 BuildMI(*SinkBB, SinkBB->begin(), dl,
10227 TII->get(ARM::PHI), ABSDstReg)
10228 .addReg(NewRsbDstReg).addMBB(RSBBB)
10229 .addReg(ABSSrcReg).addMBB(BB);
10231 // remove ABS instruction
10232 MI.eraseFromParent();
10234 // return last added BB
10235 return SinkBB;
10237 case ARM::COPY_STRUCT_BYVAL_I32:
10238 ++NumLoopByVals;
10239 return EmitStructByval(MI, BB);
10240 case ARM::WIN__CHKSTK:
10241 return EmitLowered__chkstk(MI, BB);
10242 case ARM::WIN__DBZCHK:
10243 return EmitLowered__dbzchk(MI, BB);
10247 /// Attaches vregs to MEMCPY that it will use as scratch registers
10248 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10249 /// instead of as a custom inserter because we need the use list from the SDNode.
10250 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10251 MachineInstr &MI, const SDNode *Node) {
10252 bool isThumb1 = Subtarget->isThumb1Only();
10254 DebugLoc DL = MI.getDebugLoc();
10255 MachineFunction *MF = MI.getParent()->getParent();
10256 MachineRegisterInfo &MRI = MF->getRegInfo();
10257 MachineInstrBuilder MIB(*MF, MI);
10259 // If the new dst/src is unused mark it as dead.
10260 if (!Node->hasAnyUseOfValue(0)) {
10261 MI.getOperand(0).setIsDead(true);
10263 if (!Node->hasAnyUseOfValue(1)) {
10264 MI.getOperand(1).setIsDead(true);
10267 // The MEMCPY both defines and kills the scratch registers.
10268 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10269 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10270 : &ARM::GPRRegClass);
10271 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10275 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10276 SDNode *Node) const {
10277 if (MI.getOpcode() == ARM::MEMCPY) {
10278 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10279 return;
10282 const MCInstrDesc *MCID = &MI.getDesc();
10283 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10284 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10285 // operand is still set to noreg. If needed, set the optional operand's
10286 // register to CPSR, and remove the redundant implicit def.
10288 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10290 // Rename pseudo opcodes.
10291 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10292 unsigned ccOutIdx;
10293 if (NewOpc) {
10294 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10295 MCID = &TII->get(NewOpc);
10297 assert(MCID->getNumOperands() ==
10298 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10299 && "converted opcode should be the same except for cc_out"
10300 " (and, on Thumb1, pred)");
10302 MI.setDesc(*MCID);
10304 // Add the optional cc_out operand
10305 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10307 // On Thumb1, move all input operands to the end, then add the predicate
10308 if (Subtarget->isThumb1Only()) {
10309 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10310 MI.addOperand(MI.getOperand(1));
10311 MI.RemoveOperand(1);
10314 // Restore the ties
10315 for (unsigned i = MI.getNumOperands(); i--;) {
10316 const MachineOperand& op = MI.getOperand(i);
10317 if (op.isReg() && op.isUse()) {
10318 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10319 if (DefIdx != -1)
10320 MI.tieOperands(DefIdx, i);
10324 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10325 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10326 ccOutIdx = 1;
10327 } else
10328 ccOutIdx = MCID->getNumOperands() - 1;
10329 } else
10330 ccOutIdx = MCID->getNumOperands() - 1;
10332 // Any ARM instruction that sets the 's' bit should specify an optional
10333 // "cc_out" operand in the last operand position.
10334 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10335 assert(!NewOpc && "Optional cc_out operand required");
10336 return;
10338 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10339 // since we already have an optional CPSR def.
10340 bool definesCPSR = false;
10341 bool deadCPSR = false;
10342 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10343 ++i) {
10344 const MachineOperand &MO = MI.getOperand(i);
10345 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10346 definesCPSR = true;
10347 if (MO.isDead())
10348 deadCPSR = true;
10349 MI.RemoveOperand(i);
10350 break;
10353 if (!definesCPSR) {
10354 assert(!NewOpc && "Optional cc_out operand required");
10355 return;
10357 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10358 if (deadCPSR) {
10359 assert(!MI.getOperand(ccOutIdx).getReg() &&
10360 "expect uninitialized optional cc_out operand");
10361 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10362 if (!Subtarget->isThumb1Only())
10363 return;
10366 // If this instruction was defined with an optional CPSR def and its dag node
10367 // had a live implicit CPSR def, then activate the optional CPSR def.
10368 MachineOperand &MO = MI.getOperand(ccOutIdx);
10369 MO.setReg(ARM::CPSR);
10370 MO.setIsDef(true);
10373 //===----------------------------------------------------------------------===//
10374 // ARM Optimization Hooks
10375 //===----------------------------------------------------------------------===//
10377 // Helper function that checks if N is a null or all ones constant.
10378 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10379 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10382 // Return true if N is conditionally 0 or all ones.
10383 // Detects these expressions where cc is an i1 value:
10385 // (select cc 0, y) [AllOnes=0]
10386 // (select cc y, 0) [AllOnes=0]
10387 // (zext cc) [AllOnes=0]
10388 // (sext cc) [AllOnes=0/1]
10389 // (select cc -1, y) [AllOnes=1]
10390 // (select cc y, -1) [AllOnes=1]
10392 // Invert is set when N is the null/all ones constant when CC is false.
10393 // OtherOp is set to the alternative value of N.
10394 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10395 SDValue &CC, bool &Invert,
10396 SDValue &OtherOp,
10397 SelectionDAG &DAG) {
10398 switch (N->getOpcode()) {
10399 default: return false;
10400 case ISD::SELECT: {
10401 CC = N->getOperand(0);
10402 SDValue N1 = N->getOperand(1);
10403 SDValue N2 = N->getOperand(2);
10404 if (isZeroOrAllOnes(N1, AllOnes)) {
10405 Invert = false;
10406 OtherOp = N2;
10407 return true;
10409 if (isZeroOrAllOnes(N2, AllOnes)) {
10410 Invert = true;
10411 OtherOp = N1;
10412 return true;
10414 return false;
10416 case ISD::ZERO_EXTEND:
10417 // (zext cc) can never be the all ones value.
10418 if (AllOnes)
10419 return false;
10420 LLVM_FALLTHROUGH;
10421 case ISD::SIGN_EXTEND: {
10422 SDLoc dl(N);
10423 EVT VT = N->getValueType(0);
10424 CC = N->getOperand(0);
10425 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10426 return false;
10427 Invert = !AllOnes;
10428 if (AllOnes)
10429 // When looking for an AllOnes constant, N is an sext, and the 'other'
10430 // value is 0.
10431 OtherOp = DAG.getConstant(0, dl, VT);
10432 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10433 // When looking for a 0 constant, N can be zext or sext.
10434 OtherOp = DAG.getConstant(1, dl, VT);
10435 else
10436 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10437 VT);
10438 return true;
10443 // Combine a constant select operand into its use:
10445 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10446 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10447 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10448 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10449 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10451 // The transform is rejected if the select doesn't have a constant operand that
10452 // is null, or all ones when AllOnes is set.
10454 // Also recognize sext/zext from i1:
10456 // (add (zext cc), x) -> (select cc (add x, 1), x)
10457 // (add (sext cc), x) -> (select cc (add x, -1), x)
10459 // These transformations eventually create predicated instructions.
10461 // @param N The node to transform.
10462 // @param Slct The N operand that is a select.
10463 // @param OtherOp The other N operand (x above).
10464 // @param DCI Context.
10465 // @param AllOnes Require the select constant to be all ones instead of null.
10466 // @returns The new node, or SDValue() on failure.
10467 static
10468 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10469 TargetLowering::DAGCombinerInfo &DCI,
10470 bool AllOnes = false) {
10471 SelectionDAG &DAG = DCI.DAG;
10472 EVT VT = N->getValueType(0);
10473 SDValue NonConstantVal;
10474 SDValue CCOp;
10475 bool SwapSelectOps;
10476 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10477 NonConstantVal, DAG))
10478 return SDValue();
10480 // Slct is now know to be the desired identity constant when CC is true.
10481 SDValue TrueVal = OtherOp;
10482 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10483 OtherOp, NonConstantVal);
10484 // Unless SwapSelectOps says CC should be false.
10485 if (SwapSelectOps)
10486 std::swap(TrueVal, FalseVal);
10488 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10489 CCOp, TrueVal, FalseVal);
10492 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10493 static
10494 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10495 TargetLowering::DAGCombinerInfo &DCI) {
10496 SDValue N0 = N->getOperand(0);
10497 SDValue N1 = N->getOperand(1);
10498 if (N0.getNode()->hasOneUse())
10499 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10500 return Result;
10501 if (N1.getNode()->hasOneUse())
10502 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10503 return Result;
10504 return SDValue();
10507 static bool IsVUZPShuffleNode(SDNode *N) {
10508 // VUZP shuffle node.
10509 if (N->getOpcode() == ARMISD::VUZP)
10510 return true;
10512 // "VUZP" on i32 is an alias for VTRN.
10513 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10514 return true;
10516 return false;
10519 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10520 TargetLowering::DAGCombinerInfo &DCI,
10521 const ARMSubtarget *Subtarget) {
10522 // Look for ADD(VUZP.0, VUZP.1).
10523 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10524 N0 == N1)
10525 return SDValue();
10527 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10528 if (!N->getValueType(0).is64BitVector())
10529 return SDValue();
10531 // Generate vpadd.
10532 SelectionDAG &DAG = DCI.DAG;
10533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10534 SDLoc dl(N);
10535 SDNode *Unzip = N0.getNode();
10536 EVT VT = N->getValueType(0);
10538 SmallVector<SDValue, 8> Ops;
10539 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10540 TLI.getPointerTy(DAG.getDataLayout())));
10541 Ops.push_back(Unzip->getOperand(0));
10542 Ops.push_back(Unzip->getOperand(1));
10544 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10547 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10548 TargetLowering::DAGCombinerInfo &DCI,
10549 const ARMSubtarget *Subtarget) {
10550 // Check for two extended operands.
10551 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10552 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10553 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10554 N1.getOpcode() == ISD::ZERO_EXTEND))
10555 return SDValue();
10557 SDValue N00 = N0.getOperand(0);
10558 SDValue N10 = N1.getOperand(0);
10560 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10561 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10562 N00 == N10)
10563 return SDValue();
10565 // We only recognize Q register paddl here; this can't be reached until
10566 // after type legalization.
10567 if (!N00.getValueType().is64BitVector() ||
10568 !N0.getValueType().is128BitVector())
10569 return SDValue();
10571 // Generate vpaddl.
10572 SelectionDAG &DAG = DCI.DAG;
10573 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10574 SDLoc dl(N);
10575 EVT VT = N->getValueType(0);
10577 SmallVector<SDValue, 8> Ops;
10578 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10579 unsigned Opcode;
10580 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10581 Opcode = Intrinsic::arm_neon_vpaddls;
10582 else
10583 Opcode = Intrinsic::arm_neon_vpaddlu;
10584 Ops.push_back(DAG.getConstant(Opcode, dl,
10585 TLI.getPointerTy(DAG.getDataLayout())));
10586 EVT ElemTy = N00.getValueType().getVectorElementType();
10587 unsigned NumElts = VT.getVectorNumElements();
10588 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10589 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10590 N00.getOperand(0), N00.getOperand(1));
10591 Ops.push_back(Concat);
10593 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10596 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10597 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10598 // much easier to match.
10599 static SDValue
10600 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10601 TargetLowering::DAGCombinerInfo &DCI,
10602 const ARMSubtarget *Subtarget) {
10603 // Only perform optimization if after legalize, and if NEON is available. We
10604 // also expected both operands to be BUILD_VECTORs.
10605 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10606 || N0.getOpcode() != ISD::BUILD_VECTOR
10607 || N1.getOpcode() != ISD::BUILD_VECTOR)
10608 return SDValue();
10610 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10611 EVT VT = N->getValueType(0);
10612 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10613 return SDValue();
10615 // Check that the vector operands are of the right form.
10616 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10617 // operands, where N is the size of the formed vector.
10618 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10619 // index such that we have a pair wise add pattern.
10621 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10622 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10623 return SDValue();
10624 SDValue Vec = N0->getOperand(0)->getOperand(0);
10625 SDNode *V = Vec.getNode();
10626 unsigned nextIndex = 0;
10628 // For each operands to the ADD which are BUILD_VECTORs,
10629 // check to see if each of their operands are an EXTRACT_VECTOR with
10630 // the same vector and appropriate index.
10631 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10632 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10633 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10635 SDValue ExtVec0 = N0->getOperand(i);
10636 SDValue ExtVec1 = N1->getOperand(i);
10638 // First operand is the vector, verify its the same.
10639 if (V != ExtVec0->getOperand(0).getNode() ||
10640 V != ExtVec1->getOperand(0).getNode())
10641 return SDValue();
10643 // Second is the constant, verify its correct.
10644 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10645 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10647 // For the constant, we want to see all the even or all the odd.
10648 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10649 || C1->getZExtValue() != nextIndex+1)
10650 return SDValue();
10652 // Increment index.
10653 nextIndex+=2;
10654 } else
10655 return SDValue();
10658 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10659 // we're using the entire input vector, otherwise there's a size/legality
10660 // mismatch somewhere.
10661 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10662 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10663 return SDValue();
10665 // Create VPADDL node.
10666 SelectionDAG &DAG = DCI.DAG;
10667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10669 SDLoc dl(N);
10671 // Build operand list.
10672 SmallVector<SDValue, 8> Ops;
10673 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10674 TLI.getPointerTy(DAG.getDataLayout())));
10676 // Input is the vector.
10677 Ops.push_back(Vec);
10679 // Get widened type and narrowed type.
10680 MVT widenType;
10681 unsigned numElem = VT.getVectorNumElements();
10683 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10684 switch (inputLaneType.getSimpleVT().SimpleTy) {
10685 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10686 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10687 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10688 default:
10689 llvm_unreachable("Invalid vector element type for padd optimization.");
10692 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10693 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10694 return DAG.getNode(ExtOp, dl, VT, tmp);
10697 static SDValue findMUL_LOHI(SDValue V) {
10698 if (V->getOpcode() == ISD::UMUL_LOHI ||
10699 V->getOpcode() == ISD::SMUL_LOHI)
10700 return V;
10701 return SDValue();
10704 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10705 TargetLowering::DAGCombinerInfo &DCI,
10706 const ARMSubtarget *Subtarget) {
10707 if (Subtarget->isThumb()) {
10708 if (!Subtarget->hasDSP())
10709 return SDValue();
10710 } else if (!Subtarget->hasV5TEOps())
10711 return SDValue();
10713 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10714 // accumulates the product into a 64-bit value. The 16-bit values will
10715 // be sign extended somehow or SRA'd into 32-bit values
10716 // (addc (adde (mul 16bit, 16bit), lo), hi)
10717 SDValue Mul = AddcNode->getOperand(0);
10718 SDValue Lo = AddcNode->getOperand(1);
10719 if (Mul.getOpcode() != ISD::MUL) {
10720 Lo = AddcNode->getOperand(0);
10721 Mul = AddcNode->getOperand(1);
10722 if (Mul.getOpcode() != ISD::MUL)
10723 return SDValue();
10726 SDValue SRA = AddeNode->getOperand(0);
10727 SDValue Hi = AddeNode->getOperand(1);
10728 if (SRA.getOpcode() != ISD::SRA) {
10729 SRA = AddeNode->getOperand(1);
10730 Hi = AddeNode->getOperand(0);
10731 if (SRA.getOpcode() != ISD::SRA)
10732 return SDValue();
10734 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10735 if (Const->getZExtValue() != 31)
10736 return SDValue();
10737 } else
10738 return SDValue();
10740 if (SRA.getOperand(0) != Mul)
10741 return SDValue();
10743 SelectionDAG &DAG = DCI.DAG;
10744 SDLoc dl(AddcNode);
10745 unsigned Opcode = 0;
10746 SDValue Op0;
10747 SDValue Op1;
10749 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10750 Opcode = ARMISD::SMLALBB;
10751 Op0 = Mul.getOperand(0);
10752 Op1 = Mul.getOperand(1);
10753 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10754 Opcode = ARMISD::SMLALBT;
10755 Op0 = Mul.getOperand(0);
10756 Op1 = Mul.getOperand(1).getOperand(0);
10757 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10758 Opcode = ARMISD::SMLALTB;
10759 Op0 = Mul.getOperand(0).getOperand(0);
10760 Op1 = Mul.getOperand(1);
10761 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10762 Opcode = ARMISD::SMLALTT;
10763 Op0 = Mul->getOperand(0).getOperand(0);
10764 Op1 = Mul->getOperand(1).getOperand(0);
10767 if (!Op0 || !Op1)
10768 return SDValue();
10770 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10771 Op0, Op1, Lo, Hi);
10772 // Replace the ADDs' nodes uses by the MLA node's values.
10773 SDValue HiMLALResult(SMLAL.getNode(), 1);
10774 SDValue LoMLALResult(SMLAL.getNode(), 0);
10776 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10777 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10779 // Return original node to notify the driver to stop replacing.
10780 SDValue resNode(AddcNode, 0);
10781 return resNode;
10784 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10785 TargetLowering::DAGCombinerInfo &DCI,
10786 const ARMSubtarget *Subtarget) {
10787 // Look for multiply add opportunities.
10788 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10789 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10790 // a glue link from the first add to the second add.
10791 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10792 // a S/UMLAL instruction.
10793 // UMUL_LOHI
10794 // / :lo \ :hi
10795 // V \ [no multiline comment]
10796 // loAdd -> ADDC |
10797 // \ :carry /
10798 // V V
10799 // ADDE <- hiAdd
10801 // In the special case where only the higher part of a signed result is used
10802 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10803 // a constant with the exact value of 0x80000000, we recognize we are dealing
10804 // with a "rounded multiply and add" (or subtract) and transform it into
10805 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10807 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10808 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10809 "Expect an ADDE or SUBE");
10811 assert(AddeSubeNode->getNumOperands() == 3 &&
10812 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10813 "ADDE node has the wrong inputs");
10815 // Check that we are chained to the right ADDC or SUBC node.
10816 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10817 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10818 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10819 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10820 AddcSubcNode->getOpcode() != ARMISD::SUBC))
10821 return SDValue();
10823 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10824 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10826 // Check if the two operands are from the same mul_lohi node.
10827 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10828 return SDValue();
10830 assert(AddcSubcNode->getNumValues() == 2 &&
10831 AddcSubcNode->getValueType(0) == MVT::i32 &&
10832 "Expect ADDC with two result values. First: i32");
10834 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10835 // maybe a SMLAL which multiplies two 16-bit values.
10836 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10837 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10838 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10839 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10840 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10841 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10843 // Check for the triangle shape.
10844 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10845 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10847 // Make sure that the ADDE/SUBE operands are not coming from the same node.
10848 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10849 return SDValue();
10851 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10852 bool IsLeftOperandMUL = false;
10853 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10854 if (MULOp == SDValue())
10855 MULOp = findMUL_LOHI(AddeSubeOp1);
10856 else
10857 IsLeftOperandMUL = true;
10858 if (MULOp == SDValue())
10859 return SDValue();
10861 // Figure out the right opcode.
10862 unsigned Opc = MULOp->getOpcode();
10863 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10865 // Figure out the high and low input values to the MLAL node.
10866 SDValue *HiAddSub = nullptr;
10867 SDValue *LoMul = nullptr;
10868 SDValue *LowAddSub = nullptr;
10870 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10871 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10872 return SDValue();
10874 if (IsLeftOperandMUL)
10875 HiAddSub = &AddeSubeOp1;
10876 else
10877 HiAddSub = &AddeSubeOp0;
10879 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10880 // whose low result is fed to the ADDC/SUBC we are checking.
10882 if (AddcSubcOp0 == MULOp.getValue(0)) {
10883 LoMul = &AddcSubcOp0;
10884 LowAddSub = &AddcSubcOp1;
10886 if (AddcSubcOp1 == MULOp.getValue(0)) {
10887 LoMul = &AddcSubcOp1;
10888 LowAddSub = &AddcSubcOp0;
10891 if (!LoMul)
10892 return SDValue();
10894 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10895 // the replacement below will create a cycle.
10896 if (AddcSubcNode == HiAddSub->getNode() ||
10897 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10898 return SDValue();
10900 // Create the merged node.
10901 SelectionDAG &DAG = DCI.DAG;
10903 // Start building operand list.
10904 SmallVector<SDValue, 8> Ops;
10905 Ops.push_back(LoMul->getOperand(0));
10906 Ops.push_back(LoMul->getOperand(1));
10908 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
10909 // the case, we must be doing signed multiplication and only use the higher
10910 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10911 // addition or subtraction with the value of 0x800000.
10912 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10913 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10914 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10915 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10916 0x80000000) {
10917 Ops.push_back(*HiAddSub);
10918 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10919 FinalOpc = ARMISD::SMMLSR;
10920 } else {
10921 FinalOpc = ARMISD::SMMLAR;
10923 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10924 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10926 return SDValue(AddeSubeNode, 0);
10927 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10928 // SMMLS is generated during instruction selection and the rest of this
10929 // function can not handle the case where AddcSubcNode is a SUBC.
10930 return SDValue();
10932 // Finish building the operand list for {U/S}MLAL
10933 Ops.push_back(*LowAddSub);
10934 Ops.push_back(*HiAddSub);
10936 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10937 DAG.getVTList(MVT::i32, MVT::i32), Ops);
10939 // Replace the ADDs' nodes uses by the MLA node's values.
10940 SDValue HiMLALResult(MLALNode.getNode(), 1);
10941 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10943 SDValue LoMLALResult(MLALNode.getNode(), 0);
10944 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10946 // Return original node to notify the driver to stop replacing.
10947 return SDValue(AddeSubeNode, 0);
10950 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10951 TargetLowering::DAGCombinerInfo &DCI,
10952 const ARMSubtarget *Subtarget) {
10953 // UMAAL is similar to UMLAL except that it adds two unsigned values.
10954 // While trying to combine for the other MLAL nodes, first search for the
10955 // chance to use UMAAL. Check if Addc uses a node which has already
10956 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10957 // as the addend, and it's handled in PerformUMLALCombine.
10959 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10960 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10962 // Check that we have a glued ADDC node.
10963 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10964 if (AddcNode->getOpcode() != ARMISD::ADDC)
10965 return SDValue();
10967 // Find the converted UMAAL or quit if it doesn't exist.
10968 SDNode *UmlalNode = nullptr;
10969 SDValue AddHi;
10970 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10971 UmlalNode = AddcNode->getOperand(0).getNode();
10972 AddHi = AddcNode->getOperand(1);
10973 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10974 UmlalNode = AddcNode->getOperand(1).getNode();
10975 AddHi = AddcNode->getOperand(0);
10976 } else {
10977 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10980 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10981 // the ADDC as well as Zero.
10982 if (!isNullConstant(UmlalNode->getOperand(3)))
10983 return SDValue();
10985 if ((isNullConstant(AddeNode->getOperand(0)) &&
10986 AddeNode->getOperand(1).getNode() == UmlalNode) ||
10987 (AddeNode->getOperand(0).getNode() == UmlalNode &&
10988 isNullConstant(AddeNode->getOperand(1)))) {
10989 SelectionDAG &DAG = DCI.DAG;
10990 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10991 UmlalNode->getOperand(2), AddHi };
10992 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10993 DAG.getVTList(MVT::i32, MVT::i32), Ops);
10995 // Replace the ADDs' nodes uses by the UMAAL node's values.
10996 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10997 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10999 // Return original node to notify the driver to stop replacing.
11000 return SDValue(AddeNode, 0);
11002 return SDValue();
11005 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11006 const ARMSubtarget *Subtarget) {
11007 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11008 return SDValue();
11010 // Check that we have a pair of ADDC and ADDE as operands.
11011 // Both addends of the ADDE must be zero.
11012 SDNode* AddcNode = N->getOperand(2).getNode();
11013 SDNode* AddeNode = N->getOperand(3).getNode();
11014 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11015 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11016 isNullConstant(AddeNode->getOperand(0)) &&
11017 isNullConstant(AddeNode->getOperand(1)) &&
11018 (AddeNode->getOperand(2).getNode() == AddcNode))
11019 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11020 DAG.getVTList(MVT::i32, MVT::i32),
11021 {N->getOperand(0), N->getOperand(1),
11022 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11023 else
11024 return SDValue();
11027 static SDValue PerformAddcSubcCombine(SDNode *N,
11028 TargetLowering::DAGCombinerInfo &DCI,
11029 const ARMSubtarget *Subtarget) {
11030 SelectionDAG &DAG(DCI.DAG);
11032 if (N->getOpcode() == ARMISD::SUBC) {
11033 // (SUBC (ADDE 0, 0, C), 1) -> C
11034 SDValue LHS = N->getOperand(0);
11035 SDValue RHS = N->getOperand(1);
11036 if (LHS->getOpcode() == ARMISD::ADDE &&
11037 isNullConstant(LHS->getOperand(0)) &&
11038 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11039 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11043 if (Subtarget->isThumb1Only()) {
11044 SDValue RHS = N->getOperand(1);
11045 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11046 int32_t imm = C->getSExtValue();
11047 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11048 SDLoc DL(N);
11049 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11050 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11051 : ARMISD::ADDC;
11052 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11057 return SDValue();
11060 static SDValue PerformAddeSubeCombine(SDNode *N,
11061 TargetLowering::DAGCombinerInfo &DCI,
11062 const ARMSubtarget *Subtarget) {
11063 if (Subtarget->isThumb1Only()) {
11064 SelectionDAG &DAG = DCI.DAG;
11065 SDValue RHS = N->getOperand(1);
11066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11067 int64_t imm = C->getSExtValue();
11068 if (imm < 0) {
11069 SDLoc DL(N);
11071 // The with-carry-in form matches bitwise not instead of the negation.
11072 // Effectively, the inverse interpretation of the carry flag already
11073 // accounts for part of the negation.
11074 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11076 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11077 : ARMISD::ADDE;
11078 return DAG.getNode(Opcode, DL, N->getVTList(),
11079 N->getOperand(0), RHS, N->getOperand(2));
11082 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11083 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11085 return SDValue();
11088 static SDValue PerformABSCombine(SDNode *N,
11089 TargetLowering::DAGCombinerInfo &DCI,
11090 const ARMSubtarget *Subtarget) {
11091 SDValue res;
11092 SelectionDAG &DAG = DCI.DAG;
11093 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11095 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11096 return SDValue();
11098 if (!TLI.expandABS(N, res, DAG))
11099 return SDValue();
11101 return res;
11104 /// PerformADDECombine - Target-specific dag combine transform from
11105 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11106 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11107 static SDValue PerformADDECombine(SDNode *N,
11108 TargetLowering::DAGCombinerInfo &DCI,
11109 const ARMSubtarget *Subtarget) {
11110 // Only ARM and Thumb2 support UMLAL/SMLAL.
11111 if (Subtarget->isThumb1Only())
11112 return PerformAddeSubeCombine(N, DCI, Subtarget);
11114 // Only perform the checks after legalize when the pattern is available.
11115 if (DCI.isBeforeLegalize()) return SDValue();
11117 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11120 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11121 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11122 /// called with the default operands, and if that fails, with commuted
11123 /// operands.
11124 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11125 TargetLowering::DAGCombinerInfo &DCI,
11126 const ARMSubtarget *Subtarget){
11127 // Attempt to create vpadd for this add.
11128 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11129 return Result;
11131 // Attempt to create vpaddl for this add.
11132 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11133 return Result;
11134 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11135 Subtarget))
11136 return Result;
11138 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11139 if (N0.getNode()->hasOneUse())
11140 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11141 return Result;
11142 return SDValue();
11145 bool
11146 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11147 CombineLevel Level) const {
11148 if (Level == BeforeLegalizeTypes)
11149 return true;
11151 if (N->getOpcode() != ISD::SHL)
11152 return true;
11154 if (Subtarget->isThumb1Only()) {
11155 // Avoid making expensive immediates by commuting shifts. (This logic
11156 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11157 // for free.)
11158 if (N->getOpcode() != ISD::SHL)
11159 return true;
11160 SDValue N1 = N->getOperand(0);
11161 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11162 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11163 return true;
11164 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11165 if (Const->getAPIntValue().ult(256))
11166 return false;
11167 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11168 Const->getAPIntValue().sgt(-256))
11169 return false;
11171 return true;
11174 // Turn off commute-with-shift transform after legalization, so it doesn't
11175 // conflict with PerformSHLSimplify. (We could try to detect when
11176 // PerformSHLSimplify would trigger more precisely, but it isn't
11177 // really necessary.)
11178 return false;
11181 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11182 const SDNode *N, CombineLevel Level) const {
11183 if (!Subtarget->isThumb1Only())
11184 return true;
11186 if (Level == BeforeLegalizeTypes)
11187 return true;
11189 return false;
11192 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11193 if (!Subtarget->hasNEON()) {
11194 if (Subtarget->isThumb1Only())
11195 return VT.getScalarSizeInBits() <= 32;
11196 return true;
11198 return VT.isScalarInteger();
11201 static SDValue PerformSHLSimplify(SDNode *N,
11202 TargetLowering::DAGCombinerInfo &DCI,
11203 const ARMSubtarget *ST) {
11204 // Allow the generic combiner to identify potential bswaps.
11205 if (DCI.isBeforeLegalize())
11206 return SDValue();
11208 // DAG combiner will fold:
11209 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11210 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11211 // Other code patterns that can be also be modified have the following form:
11212 // b + ((a << 1) | 510)
11213 // b + ((a << 1) & 510)
11214 // b + ((a << 1) ^ 510)
11215 // b + ((a << 1) + 510)
11217 // Many instructions can perform the shift for free, but it requires both
11218 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11219 // instruction will needed. So, unfold back to the original pattern if:
11220 // - if c1 and c2 are small enough that they don't require mov imms.
11221 // - the user(s) of the node can perform an shl
11223 // No shifted operands for 16-bit instructions.
11224 if (ST->isThumb() && ST->isThumb1Only())
11225 return SDValue();
11227 // Check that all the users could perform the shl themselves.
11228 for (auto U : N->uses()) {
11229 switch(U->getOpcode()) {
11230 default:
11231 return SDValue();
11232 case ISD::SUB:
11233 case ISD::ADD:
11234 case ISD::AND:
11235 case ISD::OR:
11236 case ISD::XOR:
11237 case ISD::SETCC:
11238 case ARMISD::CMP:
11239 // Check that the user isn't already using a constant because there
11240 // aren't any instructions that support an immediate operand and a
11241 // shifted operand.
11242 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11243 isa<ConstantSDNode>(U->getOperand(1)))
11244 return SDValue();
11246 // Check that it's not already using a shift.
11247 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11248 U->getOperand(1).getOpcode() == ISD::SHL)
11249 return SDValue();
11250 break;
11254 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11255 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11256 return SDValue();
11258 if (N->getOperand(0).getOpcode() != ISD::SHL)
11259 return SDValue();
11261 SDValue SHL = N->getOperand(0);
11263 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11264 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11265 if (!C1ShlC2 || !C2)
11266 return SDValue();
11268 APInt C2Int = C2->getAPIntValue();
11269 APInt C1Int = C1ShlC2->getAPIntValue();
11271 // Check that performing a lshr will not lose any information.
11272 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11273 C2Int.getBitWidth() - C2->getZExtValue());
11274 if ((C1Int & Mask) != C1Int)
11275 return SDValue();
11277 // Shift the first constant.
11278 C1Int.lshrInPlace(C2Int);
11280 // The immediates are encoded as an 8-bit value that can be rotated.
11281 auto LargeImm = [](const APInt &Imm) {
11282 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11283 return Imm.getBitWidth() - Zeros > 8;
11286 if (LargeImm(C1Int) || LargeImm(C2Int))
11287 return SDValue();
11289 SelectionDAG &DAG = DCI.DAG;
11290 SDLoc dl(N);
11291 SDValue X = SHL.getOperand(0);
11292 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11293 DAG.getConstant(C1Int, dl, MVT::i32));
11294 // Shift left to compensate for the lshr of C1Int.
11295 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11297 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11298 SHL.dump(); N->dump());
11299 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11300 return Res;
11304 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11306 static SDValue PerformADDCombine(SDNode *N,
11307 TargetLowering::DAGCombinerInfo &DCI,
11308 const ARMSubtarget *Subtarget) {
11309 SDValue N0 = N->getOperand(0);
11310 SDValue N1 = N->getOperand(1);
11312 // Only works one way, because it needs an immediate operand.
11313 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11314 return Result;
11316 // First try with the default operand order.
11317 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11318 return Result;
11320 // If that didn't work, try again with the operands commuted.
11321 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11324 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11326 static SDValue PerformSUBCombine(SDNode *N,
11327 TargetLowering::DAGCombinerInfo &DCI) {
11328 SDValue N0 = N->getOperand(0);
11329 SDValue N1 = N->getOperand(1);
11331 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11332 if (N1.getNode()->hasOneUse())
11333 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11334 return Result;
11336 return SDValue();
11339 /// PerformVMULCombine
11340 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11341 /// special multiplier accumulator forwarding.
11342 /// vmul d3, d0, d2
11343 /// vmla d3, d1, d2
11344 /// is faster than
11345 /// vadd d3, d0, d1
11346 /// vmul d3, d3, d2
11347 // However, for (A + B) * (A + B),
11348 // vadd d2, d0, d1
11349 // vmul d3, d0, d2
11350 // vmla d3, d1, d2
11351 // is slower than
11352 // vadd d2, d0, d1
11353 // vmul d3, d2, d2
11354 static SDValue PerformVMULCombine(SDNode *N,
11355 TargetLowering::DAGCombinerInfo &DCI,
11356 const ARMSubtarget *Subtarget) {
11357 if (!Subtarget->hasVMLxForwarding())
11358 return SDValue();
11360 SelectionDAG &DAG = DCI.DAG;
11361 SDValue N0 = N->getOperand(0);
11362 SDValue N1 = N->getOperand(1);
11363 unsigned Opcode = N0.getOpcode();
11364 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11365 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11366 Opcode = N1.getOpcode();
11367 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11368 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11369 return SDValue();
11370 std::swap(N0, N1);
11373 if (N0 == N1)
11374 return SDValue();
11376 EVT VT = N->getValueType(0);
11377 SDLoc DL(N);
11378 SDValue N00 = N0->getOperand(0);
11379 SDValue N01 = N0->getOperand(1);
11380 return DAG.getNode(Opcode, DL, VT,
11381 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11382 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11385 static SDValue PerformMULCombine(SDNode *N,
11386 TargetLowering::DAGCombinerInfo &DCI,
11387 const ARMSubtarget *Subtarget) {
11388 SelectionDAG &DAG = DCI.DAG;
11390 if (Subtarget->isThumb1Only())
11391 return SDValue();
11393 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11394 return SDValue();
11396 EVT VT = N->getValueType(0);
11397 if (VT.is64BitVector() || VT.is128BitVector())
11398 return PerformVMULCombine(N, DCI, Subtarget);
11399 if (VT != MVT::i32)
11400 return SDValue();
11402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11403 if (!C)
11404 return SDValue();
11406 int64_t MulAmt = C->getSExtValue();
11407 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11409 ShiftAmt = ShiftAmt & (32 - 1);
11410 SDValue V = N->getOperand(0);
11411 SDLoc DL(N);
11413 SDValue Res;
11414 MulAmt >>= ShiftAmt;
11416 if (MulAmt >= 0) {
11417 if (isPowerOf2_32(MulAmt - 1)) {
11418 // (mul x, 2^N + 1) => (add (shl x, N), x)
11419 Res = DAG.getNode(ISD::ADD, DL, VT,
11421 DAG.getNode(ISD::SHL, DL, VT,
11423 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11424 MVT::i32)));
11425 } else if (isPowerOf2_32(MulAmt + 1)) {
11426 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11427 Res = DAG.getNode(ISD::SUB, DL, VT,
11428 DAG.getNode(ISD::SHL, DL, VT,
11430 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11431 MVT::i32)),
11433 } else
11434 return SDValue();
11435 } else {
11436 uint64_t MulAmtAbs = -MulAmt;
11437 if (isPowerOf2_32(MulAmtAbs + 1)) {
11438 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11439 Res = DAG.getNode(ISD::SUB, DL, VT,
11441 DAG.getNode(ISD::SHL, DL, VT,
11443 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11444 MVT::i32)));
11445 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11446 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11447 Res = DAG.getNode(ISD::ADD, DL, VT,
11449 DAG.getNode(ISD::SHL, DL, VT,
11451 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11452 MVT::i32)));
11453 Res = DAG.getNode(ISD::SUB, DL, VT,
11454 DAG.getConstant(0, DL, MVT::i32), Res);
11455 } else
11456 return SDValue();
11459 if (ShiftAmt != 0)
11460 Res = DAG.getNode(ISD::SHL, DL, VT,
11461 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11463 // Do not add new nodes to DAG combiner worklist.
11464 DCI.CombineTo(N, Res, false);
11465 return SDValue();
11468 static SDValue CombineANDShift(SDNode *N,
11469 TargetLowering::DAGCombinerInfo &DCI,
11470 const ARMSubtarget *Subtarget) {
11471 // Allow DAGCombine to pattern-match before we touch the canonical form.
11472 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11473 return SDValue();
11475 if (N->getValueType(0) != MVT::i32)
11476 return SDValue();
11478 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11479 if (!N1C)
11480 return SDValue();
11482 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11483 // Don't transform uxtb/uxth.
11484 if (C1 == 255 || C1 == 65535)
11485 return SDValue();
11487 SDNode *N0 = N->getOperand(0).getNode();
11488 if (!N0->hasOneUse())
11489 return SDValue();
11491 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11492 return SDValue();
11494 bool LeftShift = N0->getOpcode() == ISD::SHL;
11496 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11497 if (!N01C)
11498 return SDValue();
11500 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11501 if (!C2 || C2 >= 32)
11502 return SDValue();
11504 // Clear irrelevant bits in the mask.
11505 if (LeftShift)
11506 C1 &= (-1U << C2);
11507 else
11508 C1 &= (-1U >> C2);
11510 SelectionDAG &DAG = DCI.DAG;
11511 SDLoc DL(N);
11513 // We have a pattern of the form "(and (shl x, c2) c1)" or
11514 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11515 // transform to a pair of shifts, to save materializing c1.
11517 // First pattern: right shift, then mask off leading bits.
11518 // FIXME: Use demanded bits?
11519 if (!LeftShift && isMask_32(C1)) {
11520 uint32_t C3 = countLeadingZeros(C1);
11521 if (C2 < C3) {
11522 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11523 DAG.getConstant(C3 - C2, DL, MVT::i32));
11524 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11525 DAG.getConstant(C3, DL, MVT::i32));
11529 // First pattern, reversed: left shift, then mask off trailing bits.
11530 if (LeftShift && isMask_32(~C1)) {
11531 uint32_t C3 = countTrailingZeros(C1);
11532 if (C2 < C3) {
11533 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11534 DAG.getConstant(C3 - C2, DL, MVT::i32));
11535 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11536 DAG.getConstant(C3, DL, MVT::i32));
11540 // Second pattern: left shift, then mask off leading bits.
11541 // FIXME: Use demanded bits?
11542 if (LeftShift && isShiftedMask_32(C1)) {
11543 uint32_t Trailing = countTrailingZeros(C1);
11544 uint32_t C3 = countLeadingZeros(C1);
11545 if (Trailing == C2 && C2 + C3 < 32) {
11546 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11547 DAG.getConstant(C2 + C3, DL, MVT::i32));
11548 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11549 DAG.getConstant(C3, DL, MVT::i32));
11553 // Second pattern, reversed: right shift, then mask off trailing bits.
11554 // FIXME: Handle other patterns of known/demanded bits.
11555 if (!LeftShift && isShiftedMask_32(C1)) {
11556 uint32_t Leading = countLeadingZeros(C1);
11557 uint32_t C3 = countTrailingZeros(C1);
11558 if (Leading == C2 && C2 + C3 < 32) {
11559 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11560 DAG.getConstant(C2 + C3, DL, MVT::i32));
11561 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11562 DAG.getConstant(C3, DL, MVT::i32));
11566 // FIXME: Transform "(and (shl x, c2) c1)" ->
11567 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11568 // c1.
11569 return SDValue();
11572 static SDValue PerformANDCombine(SDNode *N,
11573 TargetLowering::DAGCombinerInfo &DCI,
11574 const ARMSubtarget *Subtarget) {
11575 // Attempt to use immediate-form VBIC
11576 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11577 SDLoc dl(N);
11578 EVT VT = N->getValueType(0);
11579 SelectionDAG &DAG = DCI.DAG;
11581 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11582 return SDValue();
11584 APInt SplatBits, SplatUndef;
11585 unsigned SplatBitSize;
11586 bool HasAnyUndefs;
11587 if (BVN && Subtarget->hasNEON() &&
11588 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11589 if (SplatBitSize <= 64) {
11590 EVT VbicVT;
11591 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11592 SplatUndef.getZExtValue(), SplatBitSize,
11593 DAG, dl, VbicVT, VT.is128BitVector(),
11594 OtherModImm);
11595 if (Val.getNode()) {
11596 SDValue Input =
11597 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11598 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11599 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11604 if (!Subtarget->isThumb1Only()) {
11605 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11606 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11607 return Result;
11609 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11610 return Result;
11613 if (Subtarget->isThumb1Only())
11614 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11615 return Result;
11617 return SDValue();
11620 // Try combining OR nodes to SMULWB, SMULWT.
11621 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11622 TargetLowering::DAGCombinerInfo &DCI,
11623 const ARMSubtarget *Subtarget) {
11624 if (!Subtarget->hasV6Ops() ||
11625 (Subtarget->isThumb() &&
11626 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11627 return SDValue();
11629 SDValue SRL = OR->getOperand(0);
11630 SDValue SHL = OR->getOperand(1);
11632 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11633 SRL = OR->getOperand(1);
11634 SHL = OR->getOperand(0);
11636 if (!isSRL16(SRL) || !isSHL16(SHL))
11637 return SDValue();
11639 // The first operands to the shifts need to be the two results from the
11640 // same smul_lohi node.
11641 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11642 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11643 return SDValue();
11645 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11646 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11647 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11648 return SDValue();
11650 // Now we have:
11651 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11652 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11653 // For SMUWB the 16-bit value will signed extended somehow.
11654 // For SMULWT only the SRA is required.
11655 // Check both sides of SMUL_LOHI
11656 SDValue OpS16 = SMULLOHI->getOperand(0);
11657 SDValue OpS32 = SMULLOHI->getOperand(1);
11659 SelectionDAG &DAG = DCI.DAG;
11660 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11661 OpS16 = OpS32;
11662 OpS32 = SMULLOHI->getOperand(0);
11665 SDLoc dl(OR);
11666 unsigned Opcode = 0;
11667 if (isS16(OpS16, DAG))
11668 Opcode = ARMISD::SMULWB;
11669 else if (isSRA16(OpS16)) {
11670 Opcode = ARMISD::SMULWT;
11671 OpS16 = OpS16->getOperand(0);
11673 else
11674 return SDValue();
11676 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11677 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11678 return SDValue(OR, 0);
11681 static SDValue PerformORCombineToBFI(SDNode *N,
11682 TargetLowering::DAGCombinerInfo &DCI,
11683 const ARMSubtarget *Subtarget) {
11684 // BFI is only available on V6T2+
11685 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11686 return SDValue();
11688 EVT VT = N->getValueType(0);
11689 SDValue N0 = N->getOperand(0);
11690 SDValue N1 = N->getOperand(1);
11691 SelectionDAG &DAG = DCI.DAG;
11692 SDLoc DL(N);
11693 // 1) or (and A, mask), val => ARMbfi A, val, mask
11694 // iff (val & mask) == val
11696 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11697 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11698 // && mask == ~mask2
11699 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11700 // && ~mask == mask2
11701 // (i.e., copy a bitfield value into another bitfield of the same width)
11703 if (VT != MVT::i32)
11704 return SDValue();
11706 SDValue N00 = N0.getOperand(0);
11708 // The value and the mask need to be constants so we can verify this is
11709 // actually a bitfield set. If the mask is 0xffff, we can do better
11710 // via a movt instruction, so don't use BFI in that case.
11711 SDValue MaskOp = N0.getOperand(1);
11712 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11713 if (!MaskC)
11714 return SDValue();
11715 unsigned Mask = MaskC->getZExtValue();
11716 if (Mask == 0xffff)
11717 return SDValue();
11718 SDValue Res;
11719 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11720 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11721 if (N1C) {
11722 unsigned Val = N1C->getZExtValue();
11723 if ((Val & ~Mask) != Val)
11724 return SDValue();
11726 if (ARM::isBitFieldInvertedMask(Mask)) {
11727 Val >>= countTrailingZeros(~Mask);
11729 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11730 DAG.getConstant(Val, DL, MVT::i32),
11731 DAG.getConstant(Mask, DL, MVT::i32));
11733 DCI.CombineTo(N, Res, false);
11734 // Return value from the original node to inform the combiner than N is
11735 // now dead.
11736 return SDValue(N, 0);
11738 } else if (N1.getOpcode() == ISD::AND) {
11739 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11740 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11741 if (!N11C)
11742 return SDValue();
11743 unsigned Mask2 = N11C->getZExtValue();
11745 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11746 // as is to match.
11747 if (ARM::isBitFieldInvertedMask(Mask) &&
11748 (Mask == ~Mask2)) {
11749 // The pack halfword instruction works better for masks that fit it,
11750 // so use that when it's available.
11751 if (Subtarget->hasDSP() &&
11752 (Mask == 0xffff || Mask == 0xffff0000))
11753 return SDValue();
11754 // 2a
11755 unsigned amt = countTrailingZeros(Mask2);
11756 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11757 DAG.getConstant(amt, DL, MVT::i32));
11758 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11759 DAG.getConstant(Mask, DL, MVT::i32));
11760 DCI.CombineTo(N, Res, false);
11761 // Return value from the original node to inform the combiner than N is
11762 // now dead.
11763 return SDValue(N, 0);
11764 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11765 (~Mask == Mask2)) {
11766 // The pack halfword instruction works better for masks that fit it,
11767 // so use that when it's available.
11768 if (Subtarget->hasDSP() &&
11769 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11770 return SDValue();
11771 // 2b
11772 unsigned lsb = countTrailingZeros(Mask);
11773 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11774 DAG.getConstant(lsb, DL, MVT::i32));
11775 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11776 DAG.getConstant(Mask2, DL, MVT::i32));
11777 DCI.CombineTo(N, Res, false);
11778 // Return value from the original node to inform the combiner than N is
11779 // now dead.
11780 return SDValue(N, 0);
11784 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11785 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11786 ARM::isBitFieldInvertedMask(~Mask)) {
11787 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11788 // where lsb(mask) == #shamt and masked bits of B are known zero.
11789 SDValue ShAmt = N00.getOperand(1);
11790 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11791 unsigned LSB = countTrailingZeros(Mask);
11792 if (ShAmtC != LSB)
11793 return SDValue();
11795 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11796 DAG.getConstant(~Mask, DL, MVT::i32));
11798 DCI.CombineTo(N, Res, false);
11799 // Return value from the original node to inform the combiner than N is
11800 // now dead.
11801 return SDValue(N, 0);
11804 return SDValue();
11807 static bool isValidMVECond(unsigned CC, bool IsFloat) {
11808 switch (CC) {
11809 case ARMCC::EQ:
11810 case ARMCC::NE:
11811 case ARMCC::LE:
11812 case ARMCC::GT:
11813 case ARMCC::GE:
11814 case ARMCC::LT:
11815 return true;
11816 case ARMCC::HS:
11817 case ARMCC::HI:
11818 return !IsFloat;
11819 default:
11820 return false;
11824 static SDValue PerformORCombine_i1(SDNode *N,
11825 TargetLowering::DAGCombinerInfo &DCI,
11826 const ARMSubtarget *Subtarget) {
11827 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
11828 // together with predicates
11829 EVT VT = N->getValueType(0);
11830 SDValue N0 = N->getOperand(0);
11831 SDValue N1 = N->getOperand(1);
11833 ARMCC::CondCodes CondCode0 = ARMCC::AL;
11834 ARMCC::CondCodes CondCode1 = ARMCC::AL;
11835 if (N0->getOpcode() == ARMISD::VCMP)
11836 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
11837 ->getZExtValue();
11838 else if (N0->getOpcode() == ARMISD::VCMPZ)
11839 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
11840 ->getZExtValue();
11841 if (N1->getOpcode() == ARMISD::VCMP)
11842 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
11843 ->getZExtValue();
11844 else if (N1->getOpcode() == ARMISD::VCMPZ)
11845 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
11846 ->getZExtValue();
11848 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
11849 return SDValue();
11851 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
11852 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
11854 if (!isValidMVECond(Opposite0,
11855 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
11856 !isValidMVECond(Opposite1,
11857 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
11858 return SDValue();
11860 SmallVector<SDValue, 4> Ops0;
11861 Ops0.push_back(N0->getOperand(0));
11862 if (N0->getOpcode() == ARMISD::VCMP)
11863 Ops0.push_back(N0->getOperand(1));
11864 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
11865 SmallVector<SDValue, 4> Ops1;
11866 Ops1.push_back(N1->getOperand(0));
11867 if (N1->getOpcode() == ARMISD::VCMP)
11868 Ops1.push_back(N1->getOperand(1));
11869 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
11871 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
11872 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
11873 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
11874 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
11875 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
11878 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11879 static SDValue PerformORCombine(SDNode *N,
11880 TargetLowering::DAGCombinerInfo &DCI,
11881 const ARMSubtarget *Subtarget) {
11882 // Attempt to use immediate-form VORR
11883 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11884 SDLoc dl(N);
11885 EVT VT = N->getValueType(0);
11886 SelectionDAG &DAG = DCI.DAG;
11888 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11889 return SDValue();
11891 APInt SplatBits, SplatUndef;
11892 unsigned SplatBitSize;
11893 bool HasAnyUndefs;
11894 if (BVN && Subtarget->hasNEON() &&
11895 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11896 if (SplatBitSize <= 64) {
11897 EVT VorrVT;
11898 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
11899 SplatUndef.getZExtValue(), SplatBitSize,
11900 DAG, dl, VorrVT, VT.is128BitVector(),
11901 OtherModImm);
11902 if (Val.getNode()) {
11903 SDValue Input =
11904 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11905 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11906 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11911 if (!Subtarget->isThumb1Only()) {
11912 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11913 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11914 return Result;
11915 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11916 return Result;
11919 SDValue N0 = N->getOperand(0);
11920 SDValue N1 = N->getOperand(1);
11922 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11923 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11924 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11926 // The code below optimizes (or (and X, Y), Z).
11927 // The AND operand needs to have a single user to make these optimizations
11928 // profitable.
11929 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11930 return SDValue();
11932 APInt SplatUndef;
11933 unsigned SplatBitSize;
11934 bool HasAnyUndefs;
11936 APInt SplatBits0, SplatBits1;
11937 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11938 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11939 // Ensure that the second operand of both ands are constants
11940 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11941 HasAnyUndefs) && !HasAnyUndefs) {
11942 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11943 HasAnyUndefs) && !HasAnyUndefs) {
11944 // Ensure that the bit width of the constants are the same and that
11945 // the splat arguments are logical inverses as per the pattern we
11946 // are trying to simplify.
11947 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11948 SplatBits0 == ~SplatBits1) {
11949 // Canonicalize the vector type to make instruction selection
11950 // simpler.
11951 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11952 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11953 N0->getOperand(1),
11954 N0->getOperand(0),
11955 N1->getOperand(0));
11956 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11962 if (Subtarget->hasMVEIntegerOps() &&
11963 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
11964 return PerformORCombine_i1(N, DCI, Subtarget);
11966 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11967 // reasonable.
11968 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11969 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11970 return Res;
11973 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11974 return Result;
11976 return SDValue();
11979 static SDValue PerformXORCombine(SDNode *N,
11980 TargetLowering::DAGCombinerInfo &DCI,
11981 const ARMSubtarget *Subtarget) {
11982 EVT VT = N->getValueType(0);
11983 SelectionDAG &DAG = DCI.DAG;
11985 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11986 return SDValue();
11988 if (!Subtarget->isThumb1Only()) {
11989 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11990 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11991 return Result;
11993 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11994 return Result;
11997 return SDValue();
12000 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12001 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12002 // their position in "to" (Rd).
12003 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12004 assert(N->getOpcode() == ARMISD::BFI);
12006 SDValue From = N->getOperand(1);
12007 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12008 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12010 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12011 // #C in the base of the SHR.
12012 if (From->getOpcode() == ISD::SRL &&
12013 isa<ConstantSDNode>(From->getOperand(1))) {
12014 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12015 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12016 FromMask <<= Shift.getLimitedValue(31);
12017 From = From->getOperand(0);
12020 return From;
12023 // If A and B contain one contiguous set of bits, does A | B == A . B?
12025 // Neither A nor B must be zero.
12026 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12027 unsigned LastActiveBitInA = A.countTrailingZeros();
12028 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12029 return LastActiveBitInA - 1 == FirstActiveBitInB;
12032 static SDValue FindBFIToCombineWith(SDNode *N) {
12033 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12034 // if one exists.
12035 APInt ToMask, FromMask;
12036 SDValue From = ParseBFI(N, ToMask, FromMask);
12037 SDValue To = N->getOperand(0);
12039 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12040 // aren't compatible, but not if they set the same bit in their destination as
12041 // we do (or that of any BFI we're going to combine with).
12042 SDValue V = To;
12043 APInt CombinedToMask = ToMask;
12044 while (V.getOpcode() == ARMISD::BFI) {
12045 APInt NewToMask, NewFromMask;
12046 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12047 if (NewFrom != From) {
12048 // This BFI has a different base. Keep going.
12049 CombinedToMask |= NewToMask;
12050 V = V.getOperand(0);
12051 continue;
12054 // Do the written bits conflict with any we've seen so far?
12055 if ((NewToMask & CombinedToMask).getBoolValue())
12056 // Conflicting bits - bail out because going further is unsafe.
12057 return SDValue();
12059 // Are the new bits contiguous when combined with the old bits?
12060 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12061 BitsProperlyConcatenate(FromMask, NewFromMask))
12062 return V;
12063 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12064 BitsProperlyConcatenate(NewFromMask, FromMask))
12065 return V;
12067 // We've seen a write to some bits, so track it.
12068 CombinedToMask |= NewToMask;
12069 // Keep going...
12070 V = V.getOperand(0);
12073 return SDValue();
12076 static SDValue PerformBFICombine(SDNode *N,
12077 TargetLowering::DAGCombinerInfo &DCI) {
12078 SDValue N1 = N->getOperand(1);
12079 if (N1.getOpcode() == ISD::AND) {
12080 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12081 // the bits being cleared by the AND are not demanded by the BFI.
12082 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12083 if (!N11C)
12084 return SDValue();
12085 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12086 unsigned LSB = countTrailingZeros(~InvMask);
12087 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12088 assert(Width <
12089 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12090 "undefined behavior");
12091 unsigned Mask = (1u << Width) - 1;
12092 unsigned Mask2 = N11C->getZExtValue();
12093 if ((Mask & (~Mask2)) == 0)
12094 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12095 N->getOperand(0), N1.getOperand(0),
12096 N->getOperand(2));
12097 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12098 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12099 // Keep track of any consecutive bits set that all come from the same base
12100 // value. We can combine these together into a single BFI.
12101 SDValue CombineBFI = FindBFIToCombineWith(N);
12102 if (CombineBFI == SDValue())
12103 return SDValue();
12105 // We've found a BFI.
12106 APInt ToMask1, FromMask1;
12107 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12109 APInt ToMask2, FromMask2;
12110 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12111 assert(From1 == From2);
12112 (void)From2;
12114 // First, unlink CombineBFI.
12115 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12116 // Then create a new BFI, combining the two together.
12117 APInt NewFromMask = FromMask1 | FromMask2;
12118 APInt NewToMask = ToMask1 | ToMask2;
12120 EVT VT = N->getValueType(0);
12121 SDLoc dl(N);
12123 if (NewFromMask[0] == 0)
12124 From1 = DCI.DAG.getNode(
12125 ISD::SRL, dl, VT, From1,
12126 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12127 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12128 DCI.DAG.getConstant(~NewToMask, dl, VT));
12130 return SDValue();
12133 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12134 /// ARMISD::VMOVRRD.
12135 static SDValue PerformVMOVRRDCombine(SDNode *N,
12136 TargetLowering::DAGCombinerInfo &DCI,
12137 const ARMSubtarget *Subtarget) {
12138 // vmovrrd(vmovdrr x, y) -> x,y
12139 SDValue InDouble = N->getOperand(0);
12140 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12141 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12143 // vmovrrd(load f64) -> (load i32), (load i32)
12144 SDNode *InNode = InDouble.getNode();
12145 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12146 InNode->getValueType(0) == MVT::f64 &&
12147 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12148 !cast<LoadSDNode>(InNode)->isVolatile()) {
12149 // TODO: Should this be done for non-FrameIndex operands?
12150 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12152 SelectionDAG &DAG = DCI.DAG;
12153 SDLoc DL(LD);
12154 SDValue BasePtr = LD->getBasePtr();
12155 SDValue NewLD1 =
12156 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12157 LD->getAlignment(), LD->getMemOperand()->getFlags());
12159 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12160 DAG.getConstant(4, DL, MVT::i32));
12162 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12163 LD->getPointerInfo().getWithOffset(4),
12164 std::min(4U, LD->getAlignment()),
12165 LD->getMemOperand()->getFlags());
12167 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12168 if (DCI.DAG.getDataLayout().isBigEndian())
12169 std::swap (NewLD1, NewLD2);
12170 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12171 return Result;
12174 return SDValue();
12177 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12178 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12179 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12180 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12181 SDValue Op0 = N->getOperand(0);
12182 SDValue Op1 = N->getOperand(1);
12183 if (Op0.getOpcode() == ISD::BITCAST)
12184 Op0 = Op0.getOperand(0);
12185 if (Op1.getOpcode() == ISD::BITCAST)
12186 Op1 = Op1.getOperand(0);
12187 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12188 Op0.getNode() == Op1.getNode() &&
12189 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12190 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12191 N->getValueType(0), Op0.getOperand(0));
12192 return SDValue();
12195 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12196 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12197 /// i64 vector to have f64 elements, since the value can then be loaded
12198 /// directly into a VFP register.
12199 static bool hasNormalLoadOperand(SDNode *N) {
12200 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12201 for (unsigned i = 0; i < NumElts; ++i) {
12202 SDNode *Elt = N->getOperand(i).getNode();
12203 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12204 return true;
12206 return false;
12209 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12210 /// ISD::BUILD_VECTOR.
12211 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12212 TargetLowering::DAGCombinerInfo &DCI,
12213 const ARMSubtarget *Subtarget) {
12214 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12215 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12216 // into a pair of GPRs, which is fine when the value is used as a scalar,
12217 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12218 SelectionDAG &DAG = DCI.DAG;
12219 if (N->getNumOperands() == 2)
12220 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12221 return RV;
12223 // Load i64 elements as f64 values so that type legalization does not split
12224 // them up into i32 values.
12225 EVT VT = N->getValueType(0);
12226 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12227 return SDValue();
12228 SDLoc dl(N);
12229 SmallVector<SDValue, 8> Ops;
12230 unsigned NumElts = VT.getVectorNumElements();
12231 for (unsigned i = 0; i < NumElts; ++i) {
12232 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12233 Ops.push_back(V);
12234 // Make the DAGCombiner fold the bitcast.
12235 DCI.AddToWorklist(V.getNode());
12237 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12238 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12239 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12242 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12243 static SDValue
12244 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12245 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12246 // At that time, we may have inserted bitcasts from integer to float.
12247 // If these bitcasts have survived DAGCombine, change the lowering of this
12248 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12249 // force to use floating point types.
12251 // Make sure we can change the type of the vector.
12252 // This is possible iff:
12253 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12254 // 1.1. Vector is used only once.
12255 // 1.2. Use is a bit convert to an integer type.
12256 // 2. The size of its operands are 32-bits (64-bits are not legal).
12257 EVT VT = N->getValueType(0);
12258 EVT EltVT = VT.getVectorElementType();
12260 // Check 1.1. and 2.
12261 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12262 return SDValue();
12264 // By construction, the input type must be float.
12265 assert(EltVT == MVT::f32 && "Unexpected type!");
12267 // Check 1.2.
12268 SDNode *Use = *N->use_begin();
12269 if (Use->getOpcode() != ISD::BITCAST ||
12270 Use->getValueType(0).isFloatingPoint())
12271 return SDValue();
12273 // Check profitability.
12274 // Model is, if more than half of the relevant operands are bitcast from
12275 // i32, turn the build_vector into a sequence of insert_vector_elt.
12276 // Relevant operands are everything that is not statically
12277 // (i.e., at compile time) bitcasted.
12278 unsigned NumOfBitCastedElts = 0;
12279 unsigned NumElts = VT.getVectorNumElements();
12280 unsigned NumOfRelevantElts = NumElts;
12281 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12282 SDValue Elt = N->getOperand(Idx);
12283 if (Elt->getOpcode() == ISD::BITCAST) {
12284 // Assume only bit cast to i32 will go away.
12285 if (Elt->getOperand(0).getValueType() == MVT::i32)
12286 ++NumOfBitCastedElts;
12287 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12288 // Constants are statically casted, thus do not count them as
12289 // relevant operands.
12290 --NumOfRelevantElts;
12293 // Check if more than half of the elements require a non-free bitcast.
12294 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12295 return SDValue();
12297 SelectionDAG &DAG = DCI.DAG;
12298 // Create the new vector type.
12299 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12300 // Check if the type is legal.
12301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12302 if (!TLI.isTypeLegal(VecVT))
12303 return SDValue();
12305 // Combine:
12306 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12307 // => BITCAST INSERT_VECTOR_ELT
12308 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12309 // (BITCAST EN), N.
12310 SDValue Vec = DAG.getUNDEF(VecVT);
12311 SDLoc dl(N);
12312 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12313 SDValue V = N->getOperand(Idx);
12314 if (V.isUndef())
12315 continue;
12316 if (V.getOpcode() == ISD::BITCAST &&
12317 V->getOperand(0).getValueType() == MVT::i32)
12318 // Fold obvious case.
12319 V = V.getOperand(0);
12320 else {
12321 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12322 // Make the DAGCombiner fold the bitcasts.
12323 DCI.AddToWorklist(V.getNode());
12325 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12326 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12328 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12329 // Make the DAGCombiner fold the bitcasts.
12330 DCI.AddToWorklist(Vec.getNode());
12331 return Vec;
12334 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12335 /// ISD::INSERT_VECTOR_ELT.
12336 static SDValue PerformInsertEltCombine(SDNode *N,
12337 TargetLowering::DAGCombinerInfo &DCI) {
12338 // Bitcast an i64 load inserted into a vector to f64.
12339 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12340 EVT VT = N->getValueType(0);
12341 SDNode *Elt = N->getOperand(1).getNode();
12342 if (VT.getVectorElementType() != MVT::i64 ||
12343 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12344 return SDValue();
12346 SelectionDAG &DAG = DCI.DAG;
12347 SDLoc dl(N);
12348 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12349 VT.getVectorNumElements());
12350 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12351 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12352 // Make the DAGCombiner fold the bitcasts.
12353 DCI.AddToWorklist(Vec.getNode());
12354 DCI.AddToWorklist(V.getNode());
12355 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12356 Vec, V, N->getOperand(2));
12357 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12360 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12361 /// ISD::VECTOR_SHUFFLE.
12362 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12363 // The LLVM shufflevector instruction does not require the shuffle mask
12364 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12365 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12366 // operands do not match the mask length, they are extended by concatenating
12367 // them with undef vectors. That is probably the right thing for other
12368 // targets, but for NEON it is better to concatenate two double-register
12369 // size vector operands into a single quad-register size vector. Do that
12370 // transformation here:
12371 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12372 // shuffle(concat(v1, v2), undef)
12373 SDValue Op0 = N->getOperand(0);
12374 SDValue Op1 = N->getOperand(1);
12375 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12376 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12377 Op0.getNumOperands() != 2 ||
12378 Op1.getNumOperands() != 2)
12379 return SDValue();
12380 SDValue Concat0Op1 = Op0.getOperand(1);
12381 SDValue Concat1Op1 = Op1.getOperand(1);
12382 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12383 return SDValue();
12384 // Skip the transformation if any of the types are illegal.
12385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12386 EVT VT = N->getValueType(0);
12387 if (!TLI.isTypeLegal(VT) ||
12388 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12389 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12390 return SDValue();
12392 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12393 Op0.getOperand(0), Op1.getOperand(0));
12394 // Translate the shuffle mask.
12395 SmallVector<int, 16> NewMask;
12396 unsigned NumElts = VT.getVectorNumElements();
12397 unsigned HalfElts = NumElts/2;
12398 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12399 for (unsigned n = 0; n < NumElts; ++n) {
12400 int MaskElt = SVN->getMaskElt(n);
12401 int NewElt = -1;
12402 if (MaskElt < (int)HalfElts)
12403 NewElt = MaskElt;
12404 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12405 NewElt = HalfElts + MaskElt - NumElts;
12406 NewMask.push_back(NewElt);
12408 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12409 DAG.getUNDEF(VT), NewMask);
12412 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12413 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12414 /// base address updates.
12415 /// For generic load/stores, the memory type is assumed to be a vector.
12416 /// The caller is assumed to have checked legality.
12417 static SDValue CombineBaseUpdate(SDNode *N,
12418 TargetLowering::DAGCombinerInfo &DCI) {
12419 SelectionDAG &DAG = DCI.DAG;
12420 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12421 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12422 const bool isStore = N->getOpcode() == ISD::STORE;
12423 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12424 SDValue Addr = N->getOperand(AddrOpIdx);
12425 MemSDNode *MemN = cast<MemSDNode>(N);
12426 SDLoc dl(N);
12428 // Search for a use of the address operand that is an increment.
12429 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12430 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12431 SDNode *User = *UI;
12432 if (User->getOpcode() != ISD::ADD ||
12433 UI.getUse().getResNo() != Addr.getResNo())
12434 continue;
12436 // Check that the add is independent of the load/store. Otherwise, folding
12437 // it would create a cycle. We can avoid searching through Addr as it's a
12438 // predecessor to both.
12439 SmallPtrSet<const SDNode *, 32> Visited;
12440 SmallVector<const SDNode *, 16> Worklist;
12441 Visited.insert(Addr.getNode());
12442 Worklist.push_back(N);
12443 Worklist.push_back(User);
12444 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12445 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12446 continue;
12448 // Find the new opcode for the updating load/store.
12449 bool isLoadOp = true;
12450 bool isLaneOp = false;
12451 unsigned NewOpc = 0;
12452 unsigned NumVecs = 0;
12453 if (isIntrinsic) {
12454 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12455 switch (IntNo) {
12456 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12457 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12458 NumVecs = 1; break;
12459 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12460 NumVecs = 2; break;
12461 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12462 NumVecs = 3; break;
12463 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12464 NumVecs = 4; break;
12465 case Intrinsic::arm_neon_vld2dup:
12466 case Intrinsic::arm_neon_vld3dup:
12467 case Intrinsic::arm_neon_vld4dup:
12468 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12469 // combining base updates for such intrinsics.
12470 continue;
12471 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12472 NumVecs = 2; isLaneOp = true; break;
12473 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12474 NumVecs = 3; isLaneOp = true; break;
12475 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12476 NumVecs = 4; isLaneOp = true; break;
12477 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12478 NumVecs = 1; isLoadOp = false; break;
12479 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12480 NumVecs = 2; isLoadOp = false; break;
12481 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12482 NumVecs = 3; isLoadOp = false; break;
12483 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12484 NumVecs = 4; isLoadOp = false; break;
12485 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12486 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12487 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12488 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12489 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12490 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12492 } else {
12493 isLaneOp = true;
12494 switch (N->getOpcode()) {
12495 default: llvm_unreachable("unexpected opcode for Neon base update");
12496 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12497 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12498 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12499 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12500 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12501 NumVecs = 1; isLaneOp = false; break;
12502 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12503 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12507 // Find the size of memory referenced by the load/store.
12508 EVT VecTy;
12509 if (isLoadOp) {
12510 VecTy = N->getValueType(0);
12511 } else if (isIntrinsic) {
12512 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12513 } else {
12514 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12515 VecTy = N->getOperand(1).getValueType();
12518 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12519 if (isLaneOp)
12520 NumBytes /= VecTy.getVectorNumElements();
12522 // If the increment is a constant, it must match the memory ref size.
12523 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12524 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12525 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12526 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12527 // separate instructions that make it harder to use a non-constant update.
12528 continue;
12531 // OK, we found an ADD we can fold into the base update.
12532 // Now, create a _UPD node, taking care of not breaking alignment.
12534 EVT AlignedVecTy = VecTy;
12535 unsigned Alignment = MemN->getAlignment();
12537 // If this is a less-than-standard-aligned load/store, change the type to
12538 // match the standard alignment.
12539 // The alignment is overlooked when selecting _UPD variants; and it's
12540 // easier to introduce bitcasts here than fix that.
12541 // There are 3 ways to get to this base-update combine:
12542 // - intrinsics: they are assumed to be properly aligned (to the standard
12543 // alignment of the memory type), so we don't need to do anything.
12544 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12545 // intrinsics, so, likewise, there's nothing to do.
12546 // - generic load/store instructions: the alignment is specified as an
12547 // explicit operand, rather than implicitly as the standard alignment
12548 // of the memory type (like the intrisics). We need to change the
12549 // memory type to match the explicit alignment. That way, we don't
12550 // generate non-standard-aligned ARMISD::VLDx nodes.
12551 if (isa<LSBaseSDNode>(N)) {
12552 if (Alignment == 0)
12553 Alignment = 1;
12554 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12555 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12556 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12557 assert(!isLaneOp && "Unexpected generic load/store lane.");
12558 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12559 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12561 // Don't set an explicit alignment on regular load/stores that we want
12562 // to transform to VLD/VST 1_UPD nodes.
12563 // This matches the behavior of regular load/stores, which only get an
12564 // explicit alignment if the MMO alignment is larger than the standard
12565 // alignment of the memory type.
12566 // Intrinsics, however, always get an explicit alignment, set to the
12567 // alignment of the MMO.
12568 Alignment = 1;
12571 // Create the new updating load/store node.
12572 // First, create an SDVTList for the new updating node's results.
12573 EVT Tys[6];
12574 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12575 unsigned n;
12576 for (n = 0; n < NumResultVecs; ++n)
12577 Tys[n] = AlignedVecTy;
12578 Tys[n++] = MVT::i32;
12579 Tys[n] = MVT::Other;
12580 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12582 // Then, gather the new node's operands.
12583 SmallVector<SDValue, 8> Ops;
12584 Ops.push_back(N->getOperand(0)); // incoming chain
12585 Ops.push_back(N->getOperand(AddrOpIdx));
12586 Ops.push_back(Inc);
12588 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12589 // Try to match the intrinsic's signature
12590 Ops.push_back(StN->getValue());
12591 } else {
12592 // Loads (and of course intrinsics) match the intrinsics' signature,
12593 // so just add all but the alignment operand.
12594 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12595 Ops.push_back(N->getOperand(i));
12598 // For all node types, the alignment operand is always the last one.
12599 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12601 // If this is a non-standard-aligned STORE, the penultimate operand is the
12602 // stored value. Bitcast it to the aligned type.
12603 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12604 SDValue &StVal = Ops[Ops.size()-2];
12605 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12608 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12609 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12610 MemN->getMemOperand());
12612 // Update the uses.
12613 SmallVector<SDValue, 5> NewResults;
12614 for (unsigned i = 0; i < NumResultVecs; ++i)
12615 NewResults.push_back(SDValue(UpdN.getNode(), i));
12617 // If this is an non-standard-aligned LOAD, the first result is the loaded
12618 // value. Bitcast it to the expected result type.
12619 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12620 SDValue &LdVal = NewResults[0];
12621 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12624 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12625 DCI.CombineTo(N, NewResults);
12626 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12628 break;
12630 return SDValue();
12633 static SDValue PerformVLDCombine(SDNode *N,
12634 TargetLowering::DAGCombinerInfo &DCI) {
12635 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12636 return SDValue();
12638 return CombineBaseUpdate(N, DCI);
12641 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12642 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12643 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12644 /// return true.
12645 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12646 SelectionDAG &DAG = DCI.DAG;
12647 EVT VT = N->getValueType(0);
12648 // vldN-dup instructions only support 64-bit vectors for N > 1.
12649 if (!VT.is64BitVector())
12650 return false;
12652 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12653 SDNode *VLD = N->getOperand(0).getNode();
12654 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12655 return false;
12656 unsigned NumVecs = 0;
12657 unsigned NewOpc = 0;
12658 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12659 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12660 NumVecs = 2;
12661 NewOpc = ARMISD::VLD2DUP;
12662 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12663 NumVecs = 3;
12664 NewOpc = ARMISD::VLD3DUP;
12665 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12666 NumVecs = 4;
12667 NewOpc = ARMISD::VLD4DUP;
12668 } else {
12669 return false;
12672 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12673 // numbers match the load.
12674 unsigned VLDLaneNo =
12675 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12676 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12677 UI != UE; ++UI) {
12678 // Ignore uses of the chain result.
12679 if (UI.getUse().getResNo() == NumVecs)
12680 continue;
12681 SDNode *User = *UI;
12682 if (User->getOpcode() != ARMISD::VDUPLANE ||
12683 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12684 return false;
12687 // Create the vldN-dup node.
12688 EVT Tys[5];
12689 unsigned n;
12690 for (n = 0; n < NumVecs; ++n)
12691 Tys[n] = VT;
12692 Tys[n] = MVT::Other;
12693 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12694 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12695 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12696 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12697 Ops, VLDMemInt->getMemoryVT(),
12698 VLDMemInt->getMemOperand());
12700 // Update the uses.
12701 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12702 UI != UE; ++UI) {
12703 unsigned ResNo = UI.getUse().getResNo();
12704 // Ignore uses of the chain result.
12705 if (ResNo == NumVecs)
12706 continue;
12707 SDNode *User = *UI;
12708 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12711 // Now the vldN-lane intrinsic is dead except for its chain result.
12712 // Update uses of the chain.
12713 std::vector<SDValue> VLDDupResults;
12714 for (unsigned n = 0; n < NumVecs; ++n)
12715 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12716 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12717 DCI.CombineTo(VLD, VLDDupResults);
12719 return true;
12722 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12723 /// ARMISD::VDUPLANE.
12724 static SDValue PerformVDUPLANECombine(SDNode *N,
12725 TargetLowering::DAGCombinerInfo &DCI) {
12726 SDValue Op = N->getOperand(0);
12728 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12729 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12730 if (CombineVLDDUP(N, DCI))
12731 return SDValue(N, 0);
12733 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12734 // redundant. Ignore bit_converts for now; element sizes are checked below.
12735 while (Op.getOpcode() == ISD::BITCAST)
12736 Op = Op.getOperand(0);
12737 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12738 return SDValue();
12740 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12741 unsigned EltSize = Op.getScalarValueSizeInBits();
12742 // The canonical VMOV for a zero vector uses a 32-bit element size.
12743 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12744 unsigned EltBits;
12745 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12746 EltSize = 8;
12747 EVT VT = N->getValueType(0);
12748 if (EltSize > VT.getScalarSizeInBits())
12749 return SDValue();
12751 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12754 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12755 static SDValue PerformVDUPCombine(SDNode *N,
12756 TargetLowering::DAGCombinerInfo &DCI,
12757 const ARMSubtarget *Subtarget) {
12758 SelectionDAG &DAG = DCI.DAG;
12759 SDValue Op = N->getOperand(0);
12761 if (!Subtarget->hasNEON())
12762 return SDValue();
12764 // Match VDUP(LOAD) -> VLD1DUP.
12765 // We match this pattern here rather than waiting for isel because the
12766 // transform is only legal for unindexed loads.
12767 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12768 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12769 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12770 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12771 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12772 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12773 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12774 Ops, LD->getMemoryVT(),
12775 LD->getMemOperand());
12776 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12777 return VLDDup;
12780 return SDValue();
12783 static SDValue PerformLOADCombine(SDNode *N,
12784 TargetLowering::DAGCombinerInfo &DCI) {
12785 EVT VT = N->getValueType(0);
12787 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12788 if (ISD::isNormalLoad(N) && VT.isVector() &&
12789 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12790 return CombineBaseUpdate(N, DCI);
12792 return SDValue();
12795 /// PerformSTORECombine - Target-specific dag combine xforms for
12796 /// ISD::STORE.
12797 static SDValue PerformSTORECombine(SDNode *N,
12798 TargetLowering::DAGCombinerInfo &DCI) {
12799 StoreSDNode *St = cast<StoreSDNode>(N);
12800 if (St->isVolatile())
12801 return SDValue();
12803 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12804 // pack all of the elements in one place. Next, store to memory in fewer
12805 // chunks.
12806 SDValue StVal = St->getValue();
12807 EVT VT = StVal.getValueType();
12808 if (St->isTruncatingStore() && VT.isVector()) {
12809 SelectionDAG &DAG = DCI.DAG;
12810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12811 EVT StVT = St->getMemoryVT();
12812 unsigned NumElems = VT.getVectorNumElements();
12813 assert(StVT != VT && "Cannot truncate to the same type");
12814 unsigned FromEltSz = VT.getScalarSizeInBits();
12815 unsigned ToEltSz = StVT.getScalarSizeInBits();
12817 // From, To sizes and ElemCount must be pow of two
12818 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
12820 // We are going to use the original vector elt for storing.
12821 // Accumulated smaller vector elements must be a multiple of the store size.
12822 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
12824 unsigned SizeRatio = FromEltSz / ToEltSz;
12825 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
12827 // Create a type on which we perform the shuffle.
12828 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
12829 NumElems*SizeRatio);
12830 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
12832 SDLoc DL(St);
12833 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
12834 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
12835 for (unsigned i = 0; i < NumElems; ++i)
12836 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
12837 ? (i + 1) * SizeRatio - 1
12838 : i * SizeRatio;
12840 // Can't shuffle using an illegal type.
12841 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
12843 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
12844 DAG.getUNDEF(WideVec.getValueType()),
12845 ShuffleVec);
12846 // At this point all of the data is stored at the bottom of the
12847 // register. We now need to save it to mem.
12849 // Find the largest store unit
12850 MVT StoreType = MVT::i8;
12851 for (MVT Tp : MVT::integer_valuetypes()) {
12852 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
12853 StoreType = Tp;
12855 // Didn't find a legal store type.
12856 if (!TLI.isTypeLegal(StoreType))
12857 return SDValue();
12859 // Bitcast the original vector into a vector of store-size units
12860 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
12861 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
12862 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
12863 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
12864 SmallVector<SDValue, 8> Chains;
12865 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
12866 TLI.getPointerTy(DAG.getDataLayout()));
12867 SDValue BasePtr = St->getBasePtr();
12869 // Perform one or more big stores into memory.
12870 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
12871 for (unsigned I = 0; I < E; I++) {
12872 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
12873 StoreType, ShuffWide,
12874 DAG.getIntPtrConstant(I, DL));
12875 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12876 St->getPointerInfo(), St->getAlignment(),
12877 St->getMemOperand()->getFlags());
12878 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12879 Increment);
12880 Chains.push_back(Ch);
12882 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12885 if (!ISD::isNormalStore(St))
12886 return SDValue();
12888 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12889 // ARM stores of arguments in the same cache line.
12890 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12891 StVal.getNode()->hasOneUse()) {
12892 SelectionDAG &DAG = DCI.DAG;
12893 bool isBigEndian = DAG.getDataLayout().isBigEndian();
12894 SDLoc DL(St);
12895 SDValue BasePtr = St->getBasePtr();
12896 SDValue NewST1 = DAG.getStore(
12897 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12898 BasePtr, St->getPointerInfo(), St->getAlignment(),
12899 St->getMemOperand()->getFlags());
12901 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12902 DAG.getConstant(4, DL, MVT::i32));
12903 return DAG.getStore(NewST1.getValue(0), DL,
12904 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12905 OffsetPtr, St->getPointerInfo(),
12906 std::min(4U, St->getAlignment() / 2),
12907 St->getMemOperand()->getFlags());
12910 if (StVal.getValueType() == MVT::i64 &&
12911 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12913 // Bitcast an i64 store extracted from a vector to f64.
12914 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12915 SelectionDAG &DAG = DCI.DAG;
12916 SDLoc dl(StVal);
12917 SDValue IntVec = StVal.getOperand(0);
12918 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12919 IntVec.getValueType().getVectorNumElements());
12920 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12921 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12922 Vec, StVal.getOperand(1));
12923 dl = SDLoc(N);
12924 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12925 // Make the DAGCombiner fold the bitcasts.
12926 DCI.AddToWorklist(Vec.getNode());
12927 DCI.AddToWorklist(ExtElt.getNode());
12928 DCI.AddToWorklist(V.getNode());
12929 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12930 St->getPointerInfo(), St->getAlignment(),
12931 St->getMemOperand()->getFlags(), St->getAAInfo());
12934 // If this is a legal vector store, try to combine it into a VST1_UPD.
12935 if (ISD::isNormalStore(N) && VT.isVector() &&
12936 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12937 return CombineBaseUpdate(N, DCI);
12939 return SDValue();
12942 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12943 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12944 /// when the VMUL has a constant operand that is a power of 2.
12946 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12947 /// vmul.f32 d16, d17, d16
12948 /// vcvt.s32.f32 d16, d16
12949 /// becomes:
12950 /// vcvt.s32.f32 d16, d16, #3
12951 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12952 const ARMSubtarget *Subtarget) {
12953 if (!Subtarget->hasNEON())
12954 return SDValue();
12956 SDValue Op = N->getOperand(0);
12957 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12958 Op.getOpcode() != ISD::FMUL)
12959 return SDValue();
12961 SDValue ConstVec = Op->getOperand(1);
12962 if (!isa<BuildVectorSDNode>(ConstVec))
12963 return SDValue();
12965 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12966 uint32_t FloatBits = FloatTy.getSizeInBits();
12967 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12968 uint32_t IntBits = IntTy.getSizeInBits();
12969 unsigned NumLanes = Op.getValueType().getVectorNumElements();
12970 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
12971 // These instructions only exist converting from f32 to i32. We can handle
12972 // smaller integers by generating an extra truncate, but larger ones would
12973 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
12974 // these intructions only support v2i32/v4i32 types.
12975 return SDValue();
12978 BitVector UndefElements;
12979 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12980 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12981 if (C == -1 || C == 0 || C > 32)
12982 return SDValue();
12984 SDLoc dl(N);
12985 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12986 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12987 Intrinsic::arm_neon_vcvtfp2fxu;
12988 SDValue FixConv = DAG.getNode(
12989 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12990 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12991 DAG.getConstant(C, dl, MVT::i32));
12993 if (IntBits < FloatBits)
12994 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12996 return FixConv;
12999 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13000 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13001 /// when the VDIV has a constant operand that is a power of 2.
13003 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13004 /// vcvt.f32.s32 d16, d16
13005 /// vdiv.f32 d16, d17, d16
13006 /// becomes:
13007 /// vcvt.f32.s32 d16, d16, #3
13008 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13009 const ARMSubtarget *Subtarget) {
13010 if (!Subtarget->hasNEON())
13011 return SDValue();
13013 SDValue Op = N->getOperand(0);
13014 unsigned OpOpcode = Op.getNode()->getOpcode();
13015 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13016 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13017 return SDValue();
13019 SDValue ConstVec = N->getOperand(1);
13020 if (!isa<BuildVectorSDNode>(ConstVec))
13021 return SDValue();
13023 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13024 uint32_t FloatBits = FloatTy.getSizeInBits();
13025 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13026 uint32_t IntBits = IntTy.getSizeInBits();
13027 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13028 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13029 // These instructions only exist converting from i32 to f32. We can handle
13030 // smaller integers by generating an extra extend, but larger ones would
13031 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13032 // these intructions only support v2i32/v4i32 types.
13033 return SDValue();
13036 BitVector UndefElements;
13037 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13038 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13039 if (C == -1 || C == 0 || C > 32)
13040 return SDValue();
13042 SDLoc dl(N);
13043 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13044 SDValue ConvInput = Op.getOperand(0);
13045 if (IntBits < FloatBits)
13046 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13047 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13048 ConvInput);
13050 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13051 Intrinsic::arm_neon_vcvtfxu2fp;
13052 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13053 Op.getValueType(),
13054 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13055 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13058 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13059 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13060 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13061 switch (IntNo) {
13062 default:
13063 // Don't do anything for most intrinsics.
13064 break;
13066 // Vector shifts: check for immediate versions and lower them.
13067 // Note: This is done during DAG combining instead of DAG legalizing because
13068 // the build_vectors for 64-bit vector element shift counts are generally
13069 // not legal, and it is hard to see their values after they get legalized to
13070 // loads from a constant pool.
13071 case Intrinsic::arm_neon_vshifts:
13072 case Intrinsic::arm_neon_vshiftu:
13073 case Intrinsic::arm_neon_vrshifts:
13074 case Intrinsic::arm_neon_vrshiftu:
13075 case Intrinsic::arm_neon_vrshiftn:
13076 case Intrinsic::arm_neon_vqshifts:
13077 case Intrinsic::arm_neon_vqshiftu:
13078 case Intrinsic::arm_neon_vqshiftsu:
13079 case Intrinsic::arm_neon_vqshiftns:
13080 case Intrinsic::arm_neon_vqshiftnu:
13081 case Intrinsic::arm_neon_vqshiftnsu:
13082 case Intrinsic::arm_neon_vqrshiftns:
13083 case Intrinsic::arm_neon_vqrshiftnu:
13084 case Intrinsic::arm_neon_vqrshiftnsu: {
13085 EVT VT = N->getOperand(1).getValueType();
13086 int64_t Cnt;
13087 unsigned VShiftOpc = 0;
13089 switch (IntNo) {
13090 case Intrinsic::arm_neon_vshifts:
13091 case Intrinsic::arm_neon_vshiftu:
13092 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13093 VShiftOpc = ARMISD::VSHLIMM;
13094 break;
13096 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13097 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13098 : ARMISD::VSHRuIMM);
13099 break;
13101 return SDValue();
13103 case Intrinsic::arm_neon_vrshifts:
13104 case Intrinsic::arm_neon_vrshiftu:
13105 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13106 break;
13107 return SDValue();
13109 case Intrinsic::arm_neon_vqshifts:
13110 case Intrinsic::arm_neon_vqshiftu:
13111 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13112 break;
13113 return SDValue();
13115 case Intrinsic::arm_neon_vqshiftsu:
13116 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13117 break;
13118 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13120 case Intrinsic::arm_neon_vrshiftn:
13121 case Intrinsic::arm_neon_vqshiftns:
13122 case Intrinsic::arm_neon_vqshiftnu:
13123 case Intrinsic::arm_neon_vqshiftnsu:
13124 case Intrinsic::arm_neon_vqrshiftns:
13125 case Intrinsic::arm_neon_vqrshiftnu:
13126 case Intrinsic::arm_neon_vqrshiftnsu:
13127 // Narrowing shifts require an immediate right shift.
13128 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13129 break;
13130 llvm_unreachable("invalid shift count for narrowing vector shift "
13131 "intrinsic");
13133 default:
13134 llvm_unreachable("unhandled vector shift");
13137 switch (IntNo) {
13138 case Intrinsic::arm_neon_vshifts:
13139 case Intrinsic::arm_neon_vshiftu:
13140 // Opcode already set above.
13141 break;
13142 case Intrinsic::arm_neon_vrshifts:
13143 VShiftOpc = ARMISD::VRSHRsIMM;
13144 break;
13145 case Intrinsic::arm_neon_vrshiftu:
13146 VShiftOpc = ARMISD::VRSHRuIMM;
13147 break;
13148 case Intrinsic::arm_neon_vrshiftn:
13149 VShiftOpc = ARMISD::VRSHRNIMM;
13150 break;
13151 case Intrinsic::arm_neon_vqshifts:
13152 VShiftOpc = ARMISD::VQSHLsIMM;
13153 break;
13154 case Intrinsic::arm_neon_vqshiftu:
13155 VShiftOpc = ARMISD::VQSHLuIMM;
13156 break;
13157 case Intrinsic::arm_neon_vqshiftsu:
13158 VShiftOpc = ARMISD::VQSHLsuIMM;
13159 break;
13160 case Intrinsic::arm_neon_vqshiftns:
13161 VShiftOpc = ARMISD::VQSHRNsIMM;
13162 break;
13163 case Intrinsic::arm_neon_vqshiftnu:
13164 VShiftOpc = ARMISD::VQSHRNuIMM;
13165 break;
13166 case Intrinsic::arm_neon_vqshiftnsu:
13167 VShiftOpc = ARMISD::VQSHRNsuIMM;
13168 break;
13169 case Intrinsic::arm_neon_vqrshiftns:
13170 VShiftOpc = ARMISD::VQRSHRNsIMM;
13171 break;
13172 case Intrinsic::arm_neon_vqrshiftnu:
13173 VShiftOpc = ARMISD::VQRSHRNuIMM;
13174 break;
13175 case Intrinsic::arm_neon_vqrshiftnsu:
13176 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13177 break;
13180 SDLoc dl(N);
13181 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13182 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13185 case Intrinsic::arm_neon_vshiftins: {
13186 EVT VT = N->getOperand(1).getValueType();
13187 int64_t Cnt;
13188 unsigned VShiftOpc = 0;
13190 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13191 VShiftOpc = ARMISD::VSLIIMM;
13192 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13193 VShiftOpc = ARMISD::VSRIIMM;
13194 else {
13195 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13198 SDLoc dl(N);
13199 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13200 N->getOperand(1), N->getOperand(2),
13201 DAG.getConstant(Cnt, dl, MVT::i32));
13204 case Intrinsic::arm_neon_vqrshifts:
13205 case Intrinsic::arm_neon_vqrshiftu:
13206 // No immediate versions of these to check for.
13207 break;
13210 return SDValue();
13213 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13214 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13215 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13216 /// vector element shift counts are generally not legal, and it is hard to see
13217 /// their values after they get legalized to loads from a constant pool.
13218 static SDValue PerformShiftCombine(SDNode *N,
13219 TargetLowering::DAGCombinerInfo &DCI,
13220 const ARMSubtarget *ST) {
13221 SelectionDAG &DAG = DCI.DAG;
13222 EVT VT = N->getValueType(0);
13223 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13224 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13225 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13226 SDValue N1 = N->getOperand(1);
13227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13228 SDValue N0 = N->getOperand(0);
13229 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13230 DAG.MaskedValueIsZero(N0.getOperand(0),
13231 APInt::getHighBitsSet(32, 16)))
13232 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13236 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13237 N->getOperand(0)->getOpcode() == ISD::AND &&
13238 N->getOperand(0)->hasOneUse()) {
13239 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13240 return SDValue();
13241 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13242 // usually show up because instcombine prefers to canonicalize it to
13243 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13244 // out of GEP lowering in some cases.
13245 SDValue N0 = N->getOperand(0);
13246 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13247 if (!ShiftAmtNode)
13248 return SDValue();
13249 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13250 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13251 if (!AndMaskNode)
13252 return SDValue();
13253 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13254 // Don't transform uxtb/uxth.
13255 if (AndMask == 255 || AndMask == 65535)
13256 return SDValue();
13257 if (isMask_32(AndMask)) {
13258 uint32_t MaskedBits = countLeadingZeros(AndMask);
13259 if (MaskedBits > ShiftAmt) {
13260 SDLoc DL(N);
13261 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13262 DAG.getConstant(MaskedBits, DL, MVT::i32));
13263 return DAG.getNode(
13264 ISD::SRL, DL, MVT::i32, SHL,
13265 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13270 // Nothing to be done for scalar shifts.
13271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13272 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13273 return SDValue();
13274 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13275 return SDValue();
13277 int64_t Cnt;
13279 switch (N->getOpcode()) {
13280 default: llvm_unreachable("unexpected shift opcode");
13282 case ISD::SHL:
13283 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13284 SDLoc dl(N);
13285 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13286 DAG.getConstant(Cnt, dl, MVT::i32));
13288 break;
13290 case ISD::SRA:
13291 case ISD::SRL:
13292 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13293 unsigned VShiftOpc =
13294 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13295 SDLoc dl(N);
13296 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13297 DAG.getConstant(Cnt, dl, MVT::i32));
13300 return SDValue();
13303 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13304 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13305 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13306 const ARMSubtarget *ST) {
13307 SDValue N0 = N->getOperand(0);
13309 // Check for sign- and zero-extensions of vector extract operations of 8-
13310 // and 16-bit vector elements. NEON supports these directly. They are
13311 // handled during DAG combining because type legalization will promote them
13312 // to 32-bit types and it is messy to recognize the operations after that.
13313 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13314 SDValue Vec = N0.getOperand(0);
13315 SDValue Lane = N0.getOperand(1);
13316 EVT VT = N->getValueType(0);
13317 EVT EltVT = N0.getValueType();
13318 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13320 if (VT == MVT::i32 &&
13321 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13322 TLI.isTypeLegal(Vec.getValueType()) &&
13323 isa<ConstantSDNode>(Lane)) {
13325 unsigned Opc = 0;
13326 switch (N->getOpcode()) {
13327 default: llvm_unreachable("unexpected opcode");
13328 case ISD::SIGN_EXTEND:
13329 Opc = ARMISD::VGETLANEs;
13330 break;
13331 case ISD::ZERO_EXTEND:
13332 case ISD::ANY_EXTEND:
13333 Opc = ARMISD::VGETLANEu;
13334 break;
13336 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13340 return SDValue();
13343 static const APInt *isPowerOf2Constant(SDValue V) {
13344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13345 if (!C)
13346 return nullptr;
13347 const APInt *CV = &C->getAPIntValue();
13348 return CV->isPowerOf2() ? CV : nullptr;
13351 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13352 // If we have a CMOV, OR and AND combination such as:
13353 // if (x & CN)
13354 // y |= CM;
13356 // And:
13357 // * CN is a single bit;
13358 // * All bits covered by CM are known zero in y
13360 // Then we can convert this into a sequence of BFI instructions. This will
13361 // always be a win if CM is a single bit, will always be no worse than the
13362 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13363 // three bits (due to the extra IT instruction).
13365 SDValue Op0 = CMOV->getOperand(0);
13366 SDValue Op1 = CMOV->getOperand(1);
13367 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13368 auto CC = CCNode->getAPIntValue().getLimitedValue();
13369 SDValue CmpZ = CMOV->getOperand(4);
13371 // The compare must be against zero.
13372 if (!isNullConstant(CmpZ->getOperand(1)))
13373 return SDValue();
13375 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13376 SDValue And = CmpZ->getOperand(0);
13377 if (And->getOpcode() != ISD::AND)
13378 return SDValue();
13379 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13380 if (!AndC)
13381 return SDValue();
13382 SDValue X = And->getOperand(0);
13384 if (CC == ARMCC::EQ) {
13385 // We're performing an "equal to zero" compare. Swap the operands so we
13386 // canonicalize on a "not equal to zero" compare.
13387 std::swap(Op0, Op1);
13388 } else {
13389 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13392 if (Op1->getOpcode() != ISD::OR)
13393 return SDValue();
13395 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13396 if (!OrC)
13397 return SDValue();
13398 SDValue Y = Op1->getOperand(0);
13400 if (Op0 != Y)
13401 return SDValue();
13403 // Now, is it profitable to continue?
13404 APInt OrCI = OrC->getAPIntValue();
13405 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13406 if (OrCI.countPopulation() > Heuristic)
13407 return SDValue();
13409 // Lastly, can we determine that the bits defined by OrCI
13410 // are zero in Y?
13411 KnownBits Known = DAG.computeKnownBits(Y);
13412 if ((OrCI & Known.Zero) != OrCI)
13413 return SDValue();
13415 // OK, we can do the combine.
13416 SDValue V = Y;
13417 SDLoc dl(X);
13418 EVT VT = X.getValueType();
13419 unsigned BitInX = AndC->logBase2();
13421 if (BitInX != 0) {
13422 // We must shift X first.
13423 X = DAG.getNode(ISD::SRL, dl, VT, X,
13424 DAG.getConstant(BitInX, dl, VT));
13427 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13428 BitInY < NumActiveBits; ++BitInY) {
13429 if (OrCI[BitInY] == 0)
13430 continue;
13431 APInt Mask(VT.getSizeInBits(), 0);
13432 Mask.setBit(BitInY);
13433 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13434 // Confusingly, the operand is an *inverted* mask.
13435 DAG.getConstant(~Mask, dl, VT));
13438 return V;
13441 // Given N, the value controlling the conditional branch, search for the loop
13442 // intrinsic, returning it, along with how the value is used. We need to handle
13443 // patterns such as the following:
13444 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13445 // (brcond (setcc (loop.decrement), 0, eq), exit)
13446 // (brcond (setcc (loop.decrement), 0, ne), header)
13447 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13448 bool &Negate) {
13449 switch (N->getOpcode()) {
13450 default:
13451 break;
13452 case ISD::XOR: {
13453 if (!isa<ConstantSDNode>(N.getOperand(1)))
13454 return SDValue();
13455 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13456 return SDValue();
13457 Negate = !Negate;
13458 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13460 case ISD::SETCC: {
13461 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13462 if (!Const)
13463 return SDValue();
13464 if (Const->isNullValue())
13465 Imm = 0;
13466 else if (Const->isOne())
13467 Imm = 1;
13468 else
13469 return SDValue();
13470 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13471 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13473 case ISD::INTRINSIC_W_CHAIN: {
13474 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13475 if (IntOp != Intrinsic::test_set_loop_iterations &&
13476 IntOp != Intrinsic::loop_decrement_reg)
13477 return SDValue();
13478 return N;
13481 return SDValue();
13484 static SDValue PerformHWLoopCombine(SDNode *N,
13485 TargetLowering::DAGCombinerInfo &DCI,
13486 const ARMSubtarget *ST) {
13488 // The hwloop intrinsics that we're interested are used for control-flow,
13489 // either for entering or exiting the loop:
13490 // - test.set.loop.iterations will test whether its operand is zero. If it
13491 // is zero, the proceeding branch should not enter the loop.
13492 // - loop.decrement.reg also tests whether its operand is zero. If it is
13493 // zero, the proceeding branch should not branch back to the beginning of
13494 // the loop.
13495 // So here, we need to check that how the brcond is using the result of each
13496 // of the intrinsics to ensure that we're branching to the right place at the
13497 // right time.
13499 ISD::CondCode CC;
13500 SDValue Cond;
13501 int Imm = 1;
13502 bool Negate = false;
13503 SDValue Chain = N->getOperand(0);
13504 SDValue Dest;
13506 if (N->getOpcode() == ISD::BRCOND) {
13507 CC = ISD::SETEQ;
13508 Cond = N->getOperand(1);
13509 Dest = N->getOperand(2);
13510 } else {
13511 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13512 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13513 Cond = N->getOperand(2);
13514 Dest = N->getOperand(4);
13515 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13516 if (!Const->isOne() && !Const->isNullValue())
13517 return SDValue();
13518 Imm = Const->getZExtValue();
13519 } else
13520 return SDValue();
13523 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13524 if (!Int)
13525 return SDValue();
13527 if (Negate)
13528 CC = ISD::getSetCCInverse(CC, true);
13530 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13531 return (CC == ISD::SETEQ && Imm == 0) ||
13532 (CC == ISD::SETNE && Imm == 1) ||
13533 (CC == ISD::SETLT && Imm == 1) ||
13534 (CC == ISD::SETULT && Imm == 1);
13537 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13538 return (CC == ISD::SETEQ && Imm == 1) ||
13539 (CC == ISD::SETNE && Imm == 0) ||
13540 (CC == ISD::SETGT && Imm == 0) ||
13541 (CC == ISD::SETUGT && Imm == 0) ||
13542 (CC == ISD::SETGE && Imm == 1) ||
13543 (CC == ISD::SETUGE && Imm == 1);
13546 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13547 "unsupported condition");
13549 SDLoc dl(Int);
13550 SelectionDAG &DAG = DCI.DAG;
13551 SDValue Elements = Int.getOperand(2);
13552 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13553 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13554 && "expected single br user");
13555 SDNode *Br = *N->use_begin();
13556 SDValue OtherTarget = Br->getOperand(1);
13558 // Update the unconditional branch to branch to the given Dest.
13559 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13560 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13561 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13562 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13565 if (IntOp == Intrinsic::test_set_loop_iterations) {
13566 SDValue Res;
13567 // We expect this 'instruction' to branch when the counter is zero.
13568 if (IsTrueIfZero(CC, Imm)) {
13569 SDValue Ops[] = { Chain, Elements, Dest };
13570 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13571 } else {
13572 // The logic is the reverse of what we need for WLS, so find the other
13573 // basic block target: the target of the proceeding br.
13574 UpdateUncondBr(Br, Dest, DAG);
13576 SDValue Ops[] = { Chain, Elements, OtherTarget };
13577 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13579 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13580 return Res;
13581 } else {
13582 SDValue Size = DAG.getTargetConstant(
13583 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13584 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13585 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13586 DAG.getVTList(MVT::i32, MVT::Other), Args);
13587 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13589 // We expect this instruction to branch when the count is not zero.
13590 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13592 // Update the unconditional branch to target the loop preheader if we've
13593 // found the condition has been reversed.
13594 if (Target == OtherTarget)
13595 UpdateUncondBr(Br, Dest, DAG);
13597 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13598 SDValue(LoopDec.getNode(), 1), Chain);
13600 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13601 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13603 return SDValue();
13606 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13607 SDValue
13608 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13609 SDValue Cmp = N->getOperand(4);
13610 if (Cmp.getOpcode() != ARMISD::CMPZ)
13611 // Only looking at NE cases.
13612 return SDValue();
13614 EVT VT = N->getValueType(0);
13615 SDLoc dl(N);
13616 SDValue LHS = Cmp.getOperand(0);
13617 SDValue RHS = Cmp.getOperand(1);
13618 SDValue Chain = N->getOperand(0);
13619 SDValue BB = N->getOperand(1);
13620 SDValue ARMcc = N->getOperand(2);
13621 ARMCC::CondCodes CC =
13622 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13624 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13625 // -> (brcond Chain BB CC CPSR Cmp)
13626 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13627 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13628 LHS->getOperand(0)->hasOneUse()) {
13629 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13630 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13631 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13632 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13633 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13634 (LHS01C && LHS01C->getZExtValue() == 1) &&
13635 (LHS1C && LHS1C->getZExtValue() == 1) &&
13636 (RHSC && RHSC->getZExtValue() == 0)) {
13637 return DAG.getNode(
13638 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13639 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13643 return SDValue();
13646 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13647 SDValue
13648 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13649 SDValue Cmp = N->getOperand(4);
13650 if (Cmp.getOpcode() != ARMISD::CMPZ)
13651 // Only looking at EQ and NE cases.
13652 return SDValue();
13654 EVT VT = N->getValueType(0);
13655 SDLoc dl(N);
13656 SDValue LHS = Cmp.getOperand(0);
13657 SDValue RHS = Cmp.getOperand(1);
13658 SDValue FalseVal = N->getOperand(0);
13659 SDValue TrueVal = N->getOperand(1);
13660 SDValue ARMcc = N->getOperand(2);
13661 ARMCC::CondCodes CC =
13662 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13664 // BFI is only available on V6T2+.
13665 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13666 SDValue R = PerformCMOVToBFICombine(N, DAG);
13667 if (R)
13668 return R;
13671 // Simplify
13672 // mov r1, r0
13673 // cmp r1, x
13674 // mov r0, y
13675 // moveq r0, x
13676 // to
13677 // cmp r0, x
13678 // movne r0, y
13680 // mov r1, r0
13681 // cmp r1, x
13682 // mov r0, x
13683 // movne r0, y
13684 // to
13685 // cmp r0, x
13686 // movne r0, y
13687 /// FIXME: Turn this into a target neutral optimization?
13688 SDValue Res;
13689 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13690 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13691 N->getOperand(3), Cmp);
13692 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13693 SDValue ARMcc;
13694 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13695 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13696 N->getOperand(3), NewCmp);
13699 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13700 // -> (cmov F T CC CPSR Cmp)
13701 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13702 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13703 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13704 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13705 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13706 (LHS1C && LHS1C->getZExtValue() == 1) &&
13707 (RHSC && RHSC->getZExtValue() == 0)) {
13708 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13709 LHS->getOperand(2), LHS->getOperand(3),
13710 LHS->getOperand(4));
13714 if (!VT.isInteger())
13715 return SDValue();
13717 // Materialize a boolean comparison for integers so we can avoid branching.
13718 if (isNullConstant(FalseVal)) {
13719 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13720 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13721 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13722 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13723 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13724 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13725 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13726 DAG.getConstant(5, dl, MVT::i32));
13727 } else {
13728 // CMOV 0, 1, ==, (CMPZ x, y) ->
13729 // (ADDCARRY (SUB x, y), t:0, t:1)
13730 // where t = (SUBCARRY 0, (SUB x, y), 0)
13732 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13733 // x != y. In other words, a carry C == 1 when x == y, C == 0
13734 // otherwise.
13735 // The final ADDCARRY computes
13736 // x - y + (0 - (x - y)) + C == C
13737 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13738 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13739 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13740 // ISD::SUBCARRY returns a borrow but we want the carry here
13741 // actually.
13742 SDValue Carry =
13743 DAG.getNode(ISD::SUB, dl, MVT::i32,
13744 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13745 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13747 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13748 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13749 // This seems pointless but will allow us to combine it further below.
13750 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13751 SDValue Sub =
13752 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13753 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13754 Sub.getValue(1), SDValue());
13755 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13756 N->getOperand(3), CPSRGlue.getValue(1));
13757 FalseVal = Sub;
13759 } else if (isNullConstant(TrueVal)) {
13760 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13761 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13762 // This seems pointless but will allow us to combine it further below
13763 // Note that we change == for != as this is the dual for the case above.
13764 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13765 SDValue Sub =
13766 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13767 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13768 Sub.getValue(1), SDValue());
13769 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13770 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13771 N->getOperand(3), CPSRGlue.getValue(1));
13772 FalseVal = Sub;
13776 // On Thumb1, the DAG above may be further combined if z is a power of 2
13777 // (z == 2 ^ K).
13778 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13779 // t1 = (USUBO (SUB x, y), 1)
13780 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13781 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13783 // This also handles the special case of comparing against zero; it's
13784 // essentially, the same pattern, except there's no SUBS:
13785 // CMOV x, z, !=, (CMPZ x, 0) ->
13786 // t1 = (USUBO x, 1)
13787 // t2 = (SUBCARRY x, t1:0, t1:1)
13788 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13789 const APInt *TrueConst;
13790 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13791 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13792 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13793 (FalseVal == LHS && isNullConstant(RHS))) &&
13794 (TrueConst = isPowerOf2Constant(TrueVal))) {
13795 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13796 unsigned ShiftAmount = TrueConst->logBase2();
13797 if (ShiftAmount)
13798 TrueVal = DAG.getConstant(1, dl, VT);
13799 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13800 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13802 if (ShiftAmount)
13803 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13804 DAG.getConstant(ShiftAmount, dl, MVT::i32));
13807 if (Res.getNode()) {
13808 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
13809 // Capture demanded bits information that would be otherwise lost.
13810 if (Known.Zero == 0xfffffffe)
13811 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13812 DAG.getValueType(MVT::i1));
13813 else if (Known.Zero == 0xffffff00)
13814 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13815 DAG.getValueType(MVT::i8));
13816 else if (Known.Zero == 0xffff0000)
13817 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
13818 DAG.getValueType(MVT::i16));
13821 return Res;
13824 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
13825 DAGCombinerInfo &DCI) const {
13826 switch (N->getOpcode()) {
13827 default: break;
13828 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
13829 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
13830 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
13831 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
13832 case ISD::SUB: return PerformSUBCombine(N, DCI);
13833 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
13834 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
13835 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
13836 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
13837 case ISD::BRCOND:
13838 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
13839 case ARMISD::ADDC:
13840 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
13841 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
13842 case ARMISD::BFI: return PerformBFICombine(N, DCI);
13843 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
13844 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
13845 case ISD::STORE: return PerformSTORECombine(N, DCI);
13846 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
13847 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
13848 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
13849 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
13850 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
13851 case ISD::FP_TO_SINT:
13852 case ISD::FP_TO_UINT:
13853 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
13854 case ISD::FDIV:
13855 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
13856 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
13857 case ISD::SHL:
13858 case ISD::SRA:
13859 case ISD::SRL:
13860 return PerformShiftCombine(N, DCI, Subtarget);
13861 case ISD::SIGN_EXTEND:
13862 case ISD::ZERO_EXTEND:
13863 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
13864 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
13865 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
13866 case ISD::LOAD: return PerformLOADCombine(N, DCI);
13867 case ARMISD::VLD1DUP:
13868 case ARMISD::VLD2DUP:
13869 case ARMISD::VLD3DUP:
13870 case ARMISD::VLD4DUP:
13871 return PerformVLDCombine(N, DCI);
13872 case ARMISD::BUILD_VECTOR:
13873 return PerformARMBUILD_VECTORCombine(N, DCI);
13874 case ARMISD::SMULWB: {
13875 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13876 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13877 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13878 return SDValue();
13879 break;
13881 case ARMISD::SMULWT: {
13882 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13883 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13884 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
13885 return SDValue();
13886 break;
13888 case ARMISD::SMLALBB: {
13889 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13890 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
13891 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13892 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13893 return SDValue();
13894 break;
13896 case ARMISD::SMLALBT: {
13897 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
13898 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13899 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
13900 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13901 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
13902 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
13903 return SDValue();
13904 break;
13906 case ARMISD::SMLALTB: {
13907 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
13908 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
13909 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
13910 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
13911 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
13912 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
13913 return SDValue();
13914 break;
13916 case ARMISD::SMLALTT: {
13917 unsigned BitWidth = N->getValueType(0).getSizeInBits();
13918 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
13919 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
13920 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
13921 return SDValue();
13922 break;
13924 case ISD::INTRINSIC_VOID:
13925 case ISD::INTRINSIC_W_CHAIN:
13926 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13927 case Intrinsic::arm_neon_vld1:
13928 case Intrinsic::arm_neon_vld1x2:
13929 case Intrinsic::arm_neon_vld1x3:
13930 case Intrinsic::arm_neon_vld1x4:
13931 case Intrinsic::arm_neon_vld2:
13932 case Intrinsic::arm_neon_vld3:
13933 case Intrinsic::arm_neon_vld4:
13934 case Intrinsic::arm_neon_vld2lane:
13935 case Intrinsic::arm_neon_vld3lane:
13936 case Intrinsic::arm_neon_vld4lane:
13937 case Intrinsic::arm_neon_vld2dup:
13938 case Intrinsic::arm_neon_vld3dup:
13939 case Intrinsic::arm_neon_vld4dup:
13940 case Intrinsic::arm_neon_vst1:
13941 case Intrinsic::arm_neon_vst1x2:
13942 case Intrinsic::arm_neon_vst1x3:
13943 case Intrinsic::arm_neon_vst1x4:
13944 case Intrinsic::arm_neon_vst2:
13945 case Intrinsic::arm_neon_vst3:
13946 case Intrinsic::arm_neon_vst4:
13947 case Intrinsic::arm_neon_vst2lane:
13948 case Intrinsic::arm_neon_vst3lane:
13949 case Intrinsic::arm_neon_vst4lane:
13950 return PerformVLDCombine(N, DCI);
13951 default: break;
13953 break;
13955 return SDValue();
13958 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
13959 EVT VT) const {
13960 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
13963 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
13964 unsigned Alignment,
13965 MachineMemOperand::Flags,
13966 bool *Fast) const {
13967 // Depends what it gets converted into if the type is weird.
13968 if (!VT.isSimple())
13969 return false;
13971 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
13972 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
13973 auto Ty = VT.getSimpleVT().SimpleTy;
13975 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
13976 // Unaligned access can use (for example) LRDB, LRDH, LDR
13977 if (AllowsUnaligned) {
13978 if (Fast)
13979 *Fast = Subtarget->hasV7Ops();
13980 return true;
13984 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
13985 // For any little-endian targets with neon, we can support unaligned ld/st
13986 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
13987 // A big-endian target may also explicitly support unaligned accesses
13988 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
13989 if (Fast)
13990 *Fast = true;
13991 return true;
13995 if (!Subtarget->hasMVEIntegerOps())
13996 return false;
13998 // These are for predicates
13999 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14000 if (Fast)
14001 *Fast = true;
14002 return true;
14005 if (Ty != MVT::v16i8 && Ty != MVT::v8i16 && Ty != MVT::v8f16 &&
14006 Ty != MVT::v4i32 && Ty != MVT::v4f32 && Ty != MVT::v2i64 &&
14007 Ty != MVT::v2f64 &&
14008 // These are for truncated stores
14009 Ty != MVT::v4i8 && Ty != MVT::v8i8 && Ty != MVT::v4i16)
14010 return false;
14012 if (Subtarget->isLittle()) {
14013 // In little-endian MVE, the store instructions VSTRB.U8,
14014 // VSTRH.U16 and VSTRW.U32 all store the vector register in
14015 // exactly the same format, and differ only in the range of
14016 // their immediate offset field and the required alignment.
14018 // In particular, VSTRB.U8 can store a vector at byte alignment.
14019 // So at this stage we can simply say that loads/stores of all
14020 // 128-bit wide vector types are permitted at any alignment,
14021 // because we know at least _one_ instruction can manage that.
14023 // Later on we might find that some of those loads are better
14024 // generated as VLDRW.U32 if alignment permits, to take
14025 // advantage of the larger immediate range. But for the moment,
14026 // all that matters is that if we don't lower the load then
14027 // _some_ instruction can handle it.
14028 if (Fast)
14029 *Fast = true;
14030 return true;
14031 } else {
14032 // In big-endian MVE, those instructions aren't so similar
14033 // after all, because they reorder the bytes of the vector
14034 // differently. So this time we can only store a particular
14035 // kind of vector if its alignment is at least the element
14036 // type. And we can't store vectors of i64 or f64 at all
14037 // without having to do some postprocessing, because there's
14038 // no VSTRD.U64.
14039 if (Ty == MVT::v16i8 ||
14040 ((Ty == MVT::v8i16 || Ty == MVT::v8f16) && Alignment >= 2) ||
14041 ((Ty == MVT::v4i32 || Ty == MVT::v4f32) && Alignment >= 4)) {
14042 if (Fast)
14043 *Fast = true;
14044 return true;
14048 return false;
14051 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14052 unsigned AlignCheck) {
14053 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14054 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14057 EVT ARMTargetLowering::getOptimalMemOpType(
14058 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14059 bool ZeroMemset, bool MemcpyStrSrc,
14060 const AttributeList &FuncAttributes) const {
14061 // See if we can use NEON instructions for this...
14062 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14063 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14064 bool Fast;
14065 if (Size >= 16 &&
14066 (memOpAlign(SrcAlign, DstAlign, 16) ||
14067 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14068 MachineMemOperand::MONone, &Fast) &&
14069 Fast))) {
14070 return MVT::v2f64;
14071 } else if (Size >= 8 &&
14072 (memOpAlign(SrcAlign, DstAlign, 8) ||
14073 (allowsMisalignedMemoryAccesses(
14074 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14075 Fast))) {
14076 return MVT::f64;
14080 // Let the target-independent logic figure it out.
14081 return MVT::Other;
14084 // 64-bit integers are split into their high and low parts and held in two
14085 // different registers, so the trunc is free since the low register can just
14086 // be used.
14087 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14088 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14089 return false;
14090 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14091 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14092 return (SrcBits == 64 && DestBits == 32);
14095 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14096 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14097 !DstVT.isInteger())
14098 return false;
14099 unsigned SrcBits = SrcVT.getSizeInBits();
14100 unsigned DestBits = DstVT.getSizeInBits();
14101 return (SrcBits == 64 && DestBits == 32);
14104 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14105 if (Val.getOpcode() != ISD::LOAD)
14106 return false;
14108 EVT VT1 = Val.getValueType();
14109 if (!VT1.isSimple() || !VT1.isInteger() ||
14110 !VT2.isSimple() || !VT2.isInteger())
14111 return false;
14113 switch (VT1.getSimpleVT().SimpleTy) {
14114 default: break;
14115 case MVT::i1:
14116 case MVT::i8:
14117 case MVT::i16:
14118 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14119 return true;
14122 return false;
14125 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14126 if (!VT.isSimple())
14127 return false;
14129 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14130 // negate values directly (fneg is free). So, we don't want to let the DAG
14131 // combiner rewrite fneg into xors and some other instructions. For f16 and
14132 // FullFP16 argument passing, some bitcast nodes may be introduced,
14133 // triggering this DAG combine rewrite, so we are avoiding that with this.
14134 switch (VT.getSimpleVT().SimpleTy) {
14135 default: break;
14136 case MVT::f16:
14137 return Subtarget->hasFullFP16();
14140 return false;
14143 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14144 /// of the vector elements.
14145 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14146 auto areExtDoubled = [](Instruction *Ext) {
14147 return Ext->getType()->getScalarSizeInBits() ==
14148 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14151 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14152 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14153 !areExtDoubled(cast<Instruction>(Ext1)) ||
14154 !areExtDoubled(cast<Instruction>(Ext2)))
14155 return false;
14157 return true;
14160 /// Check if sinking \p I's operands to I's basic block is profitable, because
14161 /// the operands can be folded into a target instruction, e.g.
14162 /// sext/zext can be folded into vsubl.
14163 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14164 SmallVectorImpl<Use *> &Ops) const {
14165 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14166 return false;
14168 switch (I->getOpcode()) {
14169 case Instruction::Sub:
14170 case Instruction::Add: {
14171 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14172 return false;
14173 Ops.push_back(&I->getOperandUse(0));
14174 Ops.push_back(&I->getOperandUse(1));
14175 return true;
14177 default:
14178 return false;
14180 return false;
14183 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14184 EVT VT = ExtVal.getValueType();
14186 if (!isTypeLegal(VT))
14187 return false;
14189 // Don't create a loadext if we can fold the extension into a wide/long
14190 // instruction.
14191 // If there's more than one user instruction, the loadext is desirable no
14192 // matter what. There can be two uses by the same instruction.
14193 if (ExtVal->use_empty() ||
14194 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14195 return true;
14197 SDNode *U = *ExtVal->use_begin();
14198 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14199 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14200 return false;
14202 return true;
14205 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14206 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14207 return false;
14209 if (!isTypeLegal(EVT::getEVT(Ty1)))
14210 return false;
14212 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14214 // Assuming the caller doesn't have a zeroext or signext return parameter,
14215 // truncation all the way down to i1 is valid.
14216 return true;
14219 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14220 const AddrMode &AM, Type *Ty,
14221 unsigned AS) const {
14222 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14223 if (Subtarget->hasFPAO())
14224 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14225 return 0;
14227 return -1;
14230 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14231 if (V < 0)
14232 return false;
14234 unsigned Scale = 1;
14235 switch (VT.getSimpleVT().SimpleTy) {
14236 case MVT::i1:
14237 case MVT::i8:
14238 // Scale == 1;
14239 break;
14240 case MVT::i16:
14241 // Scale == 2;
14242 Scale = 2;
14243 break;
14244 default:
14245 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14246 // Scale == 4;
14247 Scale = 4;
14248 break;
14251 if ((V & (Scale - 1)) != 0)
14252 return false;
14253 return isUInt<5>(V / Scale);
14256 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14257 const ARMSubtarget *Subtarget) {
14258 if (!VT.isInteger() && !VT.isFloatingPoint())
14259 return false;
14260 if (VT.isVector() && Subtarget->hasNEON())
14261 return false;
14262 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14263 !Subtarget->hasMVEFloatOps())
14264 return false;
14266 bool IsNeg = false;
14267 if (V < 0) {
14268 IsNeg = true;
14269 V = -V;
14272 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14274 // MVE: size * imm7
14275 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14276 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14277 case MVT::i32:
14278 case MVT::f32:
14279 return isShiftedUInt<7,2>(V);
14280 case MVT::i16:
14281 case MVT::f16:
14282 return isShiftedUInt<7,1>(V);
14283 case MVT::i8:
14284 return isUInt<7>(V);
14285 default:
14286 return false;
14290 // half VLDR: 2 * imm8
14291 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14292 return isShiftedUInt<8, 1>(V);
14293 // VLDR and LDRD: 4 * imm8
14294 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14295 return isShiftedUInt<8, 2>(V);
14297 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14298 // + imm12 or - imm8
14299 if (IsNeg)
14300 return isUInt<8>(V);
14301 return isUInt<12>(V);
14304 return false;
14307 /// isLegalAddressImmediate - Return true if the integer value can be used
14308 /// as the offset of the target addressing mode for load / store of the
14309 /// given type.
14310 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14311 const ARMSubtarget *Subtarget) {
14312 if (V == 0)
14313 return true;
14315 if (!VT.isSimple())
14316 return false;
14318 if (Subtarget->isThumb1Only())
14319 return isLegalT1AddressImmediate(V, VT);
14320 else if (Subtarget->isThumb2())
14321 return isLegalT2AddressImmediate(V, VT, Subtarget);
14323 // ARM mode.
14324 if (V < 0)
14325 V = - V;
14326 switch (VT.getSimpleVT().SimpleTy) {
14327 default: return false;
14328 case MVT::i1:
14329 case MVT::i8:
14330 case MVT::i32:
14331 // +- imm12
14332 return isUInt<12>(V);
14333 case MVT::i16:
14334 // +- imm8
14335 return isUInt<8>(V);
14336 case MVT::f32:
14337 case MVT::f64:
14338 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14339 return false;
14340 return isShiftedUInt<8, 2>(V);
14344 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14345 EVT VT) const {
14346 int Scale = AM.Scale;
14347 if (Scale < 0)
14348 return false;
14350 switch (VT.getSimpleVT().SimpleTy) {
14351 default: return false;
14352 case MVT::i1:
14353 case MVT::i8:
14354 case MVT::i16:
14355 case MVT::i32:
14356 if (Scale == 1)
14357 return true;
14358 // r + r << imm
14359 Scale = Scale & ~1;
14360 return Scale == 2 || Scale == 4 || Scale == 8;
14361 case MVT::i64:
14362 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14363 // version in Thumb mode.
14364 // r + r
14365 if (Scale == 1)
14366 return true;
14367 // r * 2 (this can be lowered to r + r).
14368 if (!AM.HasBaseReg && Scale == 2)
14369 return true;
14370 return false;
14371 case MVT::isVoid:
14372 // Note, we allow "void" uses (basically, uses that aren't loads or
14373 // stores), because arm allows folding a scale into many arithmetic
14374 // operations. This should be made more precise and revisited later.
14376 // Allow r << imm, but the imm has to be a multiple of two.
14377 if (Scale & 1) return false;
14378 return isPowerOf2_32(Scale);
14382 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14383 EVT VT) const {
14384 const int Scale = AM.Scale;
14386 // Negative scales are not supported in Thumb1.
14387 if (Scale < 0)
14388 return false;
14390 // Thumb1 addressing modes do not support register scaling excepting the
14391 // following cases:
14392 // 1. Scale == 1 means no scaling.
14393 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14394 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14397 /// isLegalAddressingMode - Return true if the addressing mode represented
14398 /// by AM is legal for this target, for a load/store of the specified type.
14399 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14400 const AddrMode &AM, Type *Ty,
14401 unsigned AS, Instruction *I) const {
14402 EVT VT = getValueType(DL, Ty, true);
14403 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14404 return false;
14406 // Can never fold addr of global into load/store.
14407 if (AM.BaseGV)
14408 return false;
14410 switch (AM.Scale) {
14411 case 0: // no scale reg, must be "r+i" or "r", or "i".
14412 break;
14413 default:
14414 // ARM doesn't support any R+R*scale+imm addr modes.
14415 if (AM.BaseOffs)
14416 return false;
14418 if (!VT.isSimple())
14419 return false;
14421 if (Subtarget->isThumb1Only())
14422 return isLegalT1ScaledAddressingMode(AM, VT);
14424 if (Subtarget->isThumb2())
14425 return isLegalT2ScaledAddressingMode(AM, VT);
14427 int Scale = AM.Scale;
14428 switch (VT.getSimpleVT().SimpleTy) {
14429 default: return false;
14430 case MVT::i1:
14431 case MVT::i8:
14432 case MVT::i32:
14433 if (Scale < 0) Scale = -Scale;
14434 if (Scale == 1)
14435 return true;
14436 // r + r << imm
14437 return isPowerOf2_32(Scale & ~1);
14438 case MVT::i16:
14439 case MVT::i64:
14440 // r +/- r
14441 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14442 return true;
14443 // r * 2 (this can be lowered to r + r).
14444 if (!AM.HasBaseReg && Scale == 2)
14445 return true;
14446 return false;
14448 case MVT::isVoid:
14449 // Note, we allow "void" uses (basically, uses that aren't loads or
14450 // stores), because arm allows folding a scale into many arithmetic
14451 // operations. This should be made more precise and revisited later.
14453 // Allow r << imm, but the imm has to be a multiple of two.
14454 if (Scale & 1) return false;
14455 return isPowerOf2_32(Scale);
14458 return true;
14461 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14462 /// icmp immediate, that is the target has icmp instructions which can compare
14463 /// a register against the immediate without having to materialize the
14464 /// immediate into a register.
14465 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14466 // Thumb2 and ARM modes can use cmn for negative immediates.
14467 if (!Subtarget->isThumb())
14468 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14469 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14470 if (Subtarget->isThumb2())
14471 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14472 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14473 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14474 return Imm >= 0 && Imm <= 255;
14477 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14478 /// *or sub* immediate, that is the target has add or sub instructions which can
14479 /// add a register with the immediate without having to materialize the
14480 /// immediate into a register.
14481 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14482 // Same encoding for add/sub, just flip the sign.
14483 int64_t AbsImm = std::abs(Imm);
14484 if (!Subtarget->isThumb())
14485 return ARM_AM::getSOImmVal(AbsImm) != -1;
14486 if (Subtarget->isThumb2())
14487 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14488 // Thumb1 only has 8-bit unsigned immediate.
14489 return AbsImm >= 0 && AbsImm <= 255;
14492 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14493 bool isSEXTLoad, SDValue &Base,
14494 SDValue &Offset, bool &isInc,
14495 SelectionDAG &DAG) {
14496 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14497 return false;
14499 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14500 // AddressingMode 3
14501 Base = Ptr->getOperand(0);
14502 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14503 int RHSC = (int)RHS->getZExtValue();
14504 if (RHSC < 0 && RHSC > -256) {
14505 assert(Ptr->getOpcode() == ISD::ADD);
14506 isInc = false;
14507 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14508 return true;
14511 isInc = (Ptr->getOpcode() == ISD::ADD);
14512 Offset = Ptr->getOperand(1);
14513 return true;
14514 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14515 // AddressingMode 2
14516 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14517 int RHSC = (int)RHS->getZExtValue();
14518 if (RHSC < 0 && RHSC > -0x1000) {
14519 assert(Ptr->getOpcode() == ISD::ADD);
14520 isInc = false;
14521 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14522 Base = Ptr->getOperand(0);
14523 return true;
14527 if (Ptr->getOpcode() == ISD::ADD) {
14528 isInc = true;
14529 ARM_AM::ShiftOpc ShOpcVal=
14530 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14531 if (ShOpcVal != ARM_AM::no_shift) {
14532 Base = Ptr->getOperand(1);
14533 Offset = Ptr->getOperand(0);
14534 } else {
14535 Base = Ptr->getOperand(0);
14536 Offset = Ptr->getOperand(1);
14538 return true;
14541 isInc = (Ptr->getOpcode() == ISD::ADD);
14542 Base = Ptr->getOperand(0);
14543 Offset = Ptr->getOperand(1);
14544 return true;
14547 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14548 return false;
14551 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14552 bool isSEXTLoad, SDValue &Base,
14553 SDValue &Offset, bool &isInc,
14554 SelectionDAG &DAG) {
14555 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14556 return false;
14558 Base = Ptr->getOperand(0);
14559 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14560 int RHSC = (int)RHS->getZExtValue();
14561 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14562 assert(Ptr->getOpcode() == ISD::ADD);
14563 isInc = false;
14564 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14565 return true;
14566 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14567 isInc = Ptr->getOpcode() == ISD::ADD;
14568 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14569 return true;
14573 return false;
14576 /// getPreIndexedAddressParts - returns true by value, base pointer and
14577 /// offset pointer and addressing mode by reference if the node's address
14578 /// can be legally represented as pre-indexed load / store address.
14579 bool
14580 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14581 SDValue &Offset,
14582 ISD::MemIndexedMode &AM,
14583 SelectionDAG &DAG) const {
14584 if (Subtarget->isThumb1Only())
14585 return false;
14587 EVT VT;
14588 SDValue Ptr;
14589 bool isSEXTLoad = false;
14590 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14591 Ptr = LD->getBasePtr();
14592 VT = LD->getMemoryVT();
14593 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14594 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14595 Ptr = ST->getBasePtr();
14596 VT = ST->getMemoryVT();
14597 } else
14598 return false;
14600 bool isInc;
14601 bool isLegal = false;
14602 if (Subtarget->isThumb2())
14603 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14604 Offset, isInc, DAG);
14605 else
14606 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14607 Offset, isInc, DAG);
14608 if (!isLegal)
14609 return false;
14611 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14612 return true;
14615 /// getPostIndexedAddressParts - returns true by value, base pointer and
14616 /// offset pointer and addressing mode by reference if this node can be
14617 /// combined with a load / store to form a post-indexed load / store.
14618 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14619 SDValue &Base,
14620 SDValue &Offset,
14621 ISD::MemIndexedMode &AM,
14622 SelectionDAG &DAG) const {
14623 EVT VT;
14624 SDValue Ptr;
14625 bool isSEXTLoad = false, isNonExt;
14626 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14627 VT = LD->getMemoryVT();
14628 Ptr = LD->getBasePtr();
14629 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14630 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14631 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14632 VT = ST->getMemoryVT();
14633 Ptr = ST->getBasePtr();
14634 isNonExt = !ST->isTruncatingStore();
14635 } else
14636 return false;
14638 if (Subtarget->isThumb1Only()) {
14639 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14640 // must be non-extending/truncating, i32, with an offset of 4.
14641 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14642 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14643 return false;
14644 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14645 if (!RHS || RHS->getZExtValue() != 4)
14646 return false;
14648 Offset = Op->getOperand(1);
14649 Base = Op->getOperand(0);
14650 AM = ISD::POST_INC;
14651 return true;
14654 bool isInc;
14655 bool isLegal = false;
14656 if (Subtarget->isThumb2())
14657 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14658 isInc, DAG);
14659 else
14660 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14661 isInc, DAG);
14662 if (!isLegal)
14663 return false;
14665 if (Ptr != Base) {
14666 // Swap base ptr and offset to catch more post-index load / store when
14667 // it's legal. In Thumb2 mode, offset must be an immediate.
14668 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14669 !Subtarget->isThumb2())
14670 std::swap(Base, Offset);
14672 // Post-indexed load / store update the base pointer.
14673 if (Ptr != Base)
14674 return false;
14677 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14678 return true;
14681 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14682 KnownBits &Known,
14683 const APInt &DemandedElts,
14684 const SelectionDAG &DAG,
14685 unsigned Depth) const {
14686 unsigned BitWidth = Known.getBitWidth();
14687 Known.resetAll();
14688 switch (Op.getOpcode()) {
14689 default: break;
14690 case ARMISD::ADDC:
14691 case ARMISD::ADDE:
14692 case ARMISD::SUBC:
14693 case ARMISD::SUBE:
14694 // Special cases when we convert a carry to a boolean.
14695 if (Op.getResNo() == 0) {
14696 SDValue LHS = Op.getOperand(0);
14697 SDValue RHS = Op.getOperand(1);
14698 // (ADDE 0, 0, C) will give us a single bit.
14699 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14700 isNullConstant(RHS)) {
14701 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14702 return;
14705 break;
14706 case ARMISD::CMOV: {
14707 // Bits are known zero/one if known on the LHS and RHS.
14708 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14709 if (Known.isUnknown())
14710 return;
14712 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14713 Known.Zero &= KnownRHS.Zero;
14714 Known.One &= KnownRHS.One;
14715 return;
14717 case ISD::INTRINSIC_W_CHAIN: {
14718 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14719 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14720 switch (IntID) {
14721 default: return;
14722 case Intrinsic::arm_ldaex:
14723 case Intrinsic::arm_ldrex: {
14724 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14725 unsigned MemBits = VT.getScalarSizeInBits();
14726 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14727 return;
14731 case ARMISD::BFI: {
14732 // Conservatively, we can recurse down the first operand
14733 // and just mask out all affected bits.
14734 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14736 // The operand to BFI is already a mask suitable for removing the bits it
14737 // sets.
14738 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14739 const APInt &Mask = CI->getAPIntValue();
14740 Known.Zero &= Mask;
14741 Known.One &= Mask;
14742 return;
14744 case ARMISD::VGETLANEs:
14745 case ARMISD::VGETLANEu: {
14746 const SDValue &SrcSV = Op.getOperand(0);
14747 EVT VecVT = SrcSV.getValueType();
14748 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14749 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14750 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14751 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14752 "VGETLANE index out of bounds");
14753 unsigned Idx = Pos->getZExtValue();
14754 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14755 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
14757 EVT VT = Op.getValueType();
14758 const unsigned DstSz = VT.getScalarSizeInBits();
14759 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
14760 (void)SrcSz;
14761 assert(SrcSz == Known.getBitWidth());
14762 assert(DstSz > SrcSz);
14763 if (Op.getOpcode() == ARMISD::VGETLANEs)
14764 Known = Known.sext(DstSz);
14765 else {
14766 Known = Known.zext(DstSz, true /* extended bits are known zero */);
14768 assert(DstSz == Known.getBitWidth());
14769 break;
14774 bool
14775 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
14776 const APInt &DemandedAPInt,
14777 TargetLoweringOpt &TLO) const {
14778 // Delay optimization, so we don't have to deal with illegal types, or block
14779 // optimizations.
14780 if (!TLO.LegalOps)
14781 return false;
14783 // Only optimize AND for now.
14784 if (Op.getOpcode() != ISD::AND)
14785 return false;
14787 EVT VT = Op.getValueType();
14789 // Ignore vectors.
14790 if (VT.isVector())
14791 return false;
14793 assert(VT == MVT::i32 && "Unexpected integer type");
14795 // Make sure the RHS really is a constant.
14796 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14797 if (!C)
14798 return false;
14800 unsigned Mask = C->getZExtValue();
14802 unsigned Demanded = DemandedAPInt.getZExtValue();
14803 unsigned ShrunkMask = Mask & Demanded;
14804 unsigned ExpandedMask = Mask | ~Demanded;
14806 // If the mask is all zeros, let the target-independent code replace the
14807 // result with zero.
14808 if (ShrunkMask == 0)
14809 return false;
14811 // If the mask is all ones, erase the AND. (Currently, the target-independent
14812 // code won't do this, so we have to do it explicitly to avoid an infinite
14813 // loop in obscure cases.)
14814 if (ExpandedMask == ~0U)
14815 return TLO.CombineTo(Op, Op.getOperand(0));
14817 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
14818 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
14820 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
14821 if (NewMask == Mask)
14822 return true;
14823 SDLoc DL(Op);
14824 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
14825 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
14826 return TLO.CombineTo(Op, NewOp);
14829 // Prefer uxtb mask.
14830 if (IsLegalMask(0xFF))
14831 return UseMask(0xFF);
14833 // Prefer uxth mask.
14834 if (IsLegalMask(0xFFFF))
14835 return UseMask(0xFFFF);
14837 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
14838 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14839 if (ShrunkMask < 256)
14840 return UseMask(ShrunkMask);
14842 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
14843 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
14844 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
14845 return UseMask(ExpandedMask);
14847 // Potential improvements:
14849 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
14850 // We could try to prefer Thumb1 immediates which can be lowered to a
14851 // two-instruction sequence.
14852 // We could try to recognize more legal ARM/Thumb2 immediates here.
14854 return false;
14858 //===----------------------------------------------------------------------===//
14859 // ARM Inline Assembly Support
14860 //===----------------------------------------------------------------------===//
14862 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
14863 // Looking for "rev" which is V6+.
14864 if (!Subtarget->hasV6Ops())
14865 return false;
14867 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14868 std::string AsmStr = IA->getAsmString();
14869 SmallVector<StringRef, 4> AsmPieces;
14870 SplitString(AsmStr, AsmPieces, ";\n");
14872 switch (AsmPieces.size()) {
14873 default: return false;
14874 case 1:
14875 AsmStr = AsmPieces[0];
14876 AsmPieces.clear();
14877 SplitString(AsmStr, AsmPieces, " \t,");
14879 // rev $0, $1
14880 if (AsmPieces.size() == 3 &&
14881 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
14882 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
14883 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14884 if (Ty && Ty->getBitWidth() == 32)
14885 return IntrinsicLowering::LowerToByteSwap(CI);
14887 break;
14890 return false;
14893 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
14894 // At this point, we have to lower this constraint to something else, so we
14895 // lower it to an "r" or "w". However, by doing this we will force the result
14896 // to be in register, while the X constraint is much more permissive.
14898 // Although we are correct (we are free to emit anything, without
14899 // constraints), we might break use cases that would expect us to be more
14900 // efficient and emit something else.
14901 if (!Subtarget->hasVFP2Base())
14902 return "r";
14903 if (ConstraintVT.isFloatingPoint())
14904 return "w";
14905 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
14906 (ConstraintVT.getSizeInBits() == 64 ||
14907 ConstraintVT.getSizeInBits() == 128))
14908 return "w";
14910 return "r";
14913 /// getConstraintType - Given a constraint letter, return the type of
14914 /// constraint it is for this target.
14915 ARMTargetLowering::ConstraintType
14916 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
14917 if (Constraint.size() == 1) {
14918 switch (Constraint[0]) {
14919 default: break;
14920 case 'l': return C_RegisterClass;
14921 case 'w': return C_RegisterClass;
14922 case 'h': return C_RegisterClass;
14923 case 'x': return C_RegisterClass;
14924 case 't': return C_RegisterClass;
14925 case 'j': return C_Other; // Constant for movw.
14926 // An address with a single base register. Due to the way we
14927 // currently handle addresses it is the same as an 'r' memory constraint.
14928 case 'Q': return C_Memory;
14930 } else if (Constraint.size() == 2) {
14931 switch (Constraint[0]) {
14932 default: break;
14933 case 'T': return C_RegisterClass;
14934 // All 'U+' constraints are addresses.
14935 case 'U': return C_Memory;
14938 return TargetLowering::getConstraintType(Constraint);
14941 /// Examine constraint type and operand type and determine a weight value.
14942 /// This object must already have been set up with the operand type
14943 /// and the current alternative constraint selected.
14944 TargetLowering::ConstraintWeight
14945 ARMTargetLowering::getSingleConstraintMatchWeight(
14946 AsmOperandInfo &info, const char *constraint) const {
14947 ConstraintWeight weight = CW_Invalid;
14948 Value *CallOperandVal = info.CallOperandVal;
14949 // If we don't have a value, we can't do a match,
14950 // but allow it at the lowest weight.
14951 if (!CallOperandVal)
14952 return CW_Default;
14953 Type *type = CallOperandVal->getType();
14954 // Look at the constraint type.
14955 switch (*constraint) {
14956 default:
14957 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14958 break;
14959 case 'l':
14960 if (type->isIntegerTy()) {
14961 if (Subtarget->isThumb())
14962 weight = CW_SpecificReg;
14963 else
14964 weight = CW_Register;
14966 break;
14967 case 'w':
14968 if (type->isFloatingPointTy())
14969 weight = CW_Register;
14970 break;
14972 return weight;
14975 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
14977 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
14978 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
14979 switch (Constraint.size()) {
14980 case 1:
14981 // GCC ARM Constraint Letters
14982 switch (Constraint[0]) {
14983 case 'l': // Low regs or general regs.
14984 if (Subtarget->isThumb())
14985 return RCPair(0U, &ARM::tGPRRegClass);
14986 return RCPair(0U, &ARM::GPRRegClass);
14987 case 'h': // High regs or no regs.
14988 if (Subtarget->isThumb())
14989 return RCPair(0U, &ARM::hGPRRegClass);
14990 break;
14991 case 'r':
14992 if (Subtarget->isThumb1Only())
14993 return RCPair(0U, &ARM::tGPRRegClass);
14994 return RCPair(0U, &ARM::GPRRegClass);
14995 case 'w':
14996 if (VT == MVT::Other)
14997 break;
14998 if (VT == MVT::f32)
14999 return RCPair(0U, &ARM::SPRRegClass);
15000 if (VT.getSizeInBits() == 64)
15001 return RCPair(0U, &ARM::DPRRegClass);
15002 if (VT.getSizeInBits() == 128)
15003 return RCPair(0U, &ARM::QPRRegClass);
15004 break;
15005 case 'x':
15006 if (VT == MVT::Other)
15007 break;
15008 if (VT == MVT::f32)
15009 return RCPair(0U, &ARM::SPR_8RegClass);
15010 if (VT.getSizeInBits() == 64)
15011 return RCPair(0U, &ARM::DPR_8RegClass);
15012 if (VT.getSizeInBits() == 128)
15013 return RCPair(0U, &ARM::QPR_8RegClass);
15014 break;
15015 case 't':
15016 if (VT == MVT::Other)
15017 break;
15018 if (VT == MVT::f32 || VT == MVT::i32)
15019 return RCPair(0U, &ARM::SPRRegClass);
15020 if (VT.getSizeInBits() == 64)
15021 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15022 if (VT.getSizeInBits() == 128)
15023 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15024 break;
15026 break;
15028 case 2:
15029 if (Constraint[0] == 'T') {
15030 switch (Constraint[1]) {
15031 default:
15032 break;
15033 case 'e':
15034 return RCPair(0U, &ARM::tGPREvenRegClass);
15035 case 'o':
15036 return RCPair(0U, &ARM::tGPROddRegClass);
15039 break;
15041 default:
15042 break;
15045 if (StringRef("{cc}").equals_lower(Constraint))
15046 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15048 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15051 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15052 /// vector. If it is invalid, don't add anything to Ops.
15053 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15054 std::string &Constraint,
15055 std::vector<SDValue>&Ops,
15056 SelectionDAG &DAG) const {
15057 SDValue Result;
15059 // Currently only support length 1 constraints.
15060 if (Constraint.length() != 1) return;
15062 char ConstraintLetter = Constraint[0];
15063 switch (ConstraintLetter) {
15064 default: break;
15065 case 'j':
15066 case 'I': case 'J': case 'K': case 'L':
15067 case 'M': case 'N': case 'O':
15068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15069 if (!C)
15070 return;
15072 int64_t CVal64 = C->getSExtValue();
15073 int CVal = (int) CVal64;
15074 // None of these constraints allow values larger than 32 bits. Check
15075 // that the value fits in an int.
15076 if (CVal != CVal64)
15077 return;
15079 switch (ConstraintLetter) {
15080 case 'j':
15081 // Constant suitable for movw, must be between 0 and
15082 // 65535.
15083 if (Subtarget->hasV6T2Ops())
15084 if (CVal >= 0 && CVal <= 65535)
15085 break;
15086 return;
15087 case 'I':
15088 if (Subtarget->isThumb1Only()) {
15089 // This must be a constant between 0 and 255, for ADD
15090 // immediates.
15091 if (CVal >= 0 && CVal <= 255)
15092 break;
15093 } else if (Subtarget->isThumb2()) {
15094 // A constant that can be used as an immediate value in a
15095 // data-processing instruction.
15096 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15097 break;
15098 } else {
15099 // A constant that can be used as an immediate value in a
15100 // data-processing instruction.
15101 if (ARM_AM::getSOImmVal(CVal) != -1)
15102 break;
15104 return;
15106 case 'J':
15107 if (Subtarget->isThumb1Only()) {
15108 // This must be a constant between -255 and -1, for negated ADD
15109 // immediates. This can be used in GCC with an "n" modifier that
15110 // prints the negated value, for use with SUB instructions. It is
15111 // not useful otherwise but is implemented for compatibility.
15112 if (CVal >= -255 && CVal <= -1)
15113 break;
15114 } else {
15115 // This must be a constant between -4095 and 4095. It is not clear
15116 // what this constraint is intended for. Implemented for
15117 // compatibility with GCC.
15118 if (CVal >= -4095 && CVal <= 4095)
15119 break;
15121 return;
15123 case 'K':
15124 if (Subtarget->isThumb1Only()) {
15125 // A 32-bit value where only one byte has a nonzero value. Exclude
15126 // zero to match GCC. This constraint is used by GCC internally for
15127 // constants that can be loaded with a move/shift combination.
15128 // It is not useful otherwise but is implemented for compatibility.
15129 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15130 break;
15131 } else if (Subtarget->isThumb2()) {
15132 // A constant whose bitwise inverse can be used as an immediate
15133 // value in a data-processing instruction. This can be used in GCC
15134 // with a "B" modifier that prints the inverted value, for use with
15135 // BIC and MVN instructions. It is not useful otherwise but is
15136 // implemented for compatibility.
15137 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15138 break;
15139 } else {
15140 // A constant whose bitwise inverse can be used as an immediate
15141 // value in a data-processing instruction. This can be used in GCC
15142 // with a "B" modifier that prints the inverted value, for use with
15143 // BIC and MVN instructions. It is not useful otherwise but is
15144 // implemented for compatibility.
15145 if (ARM_AM::getSOImmVal(~CVal) != -1)
15146 break;
15148 return;
15150 case 'L':
15151 if (Subtarget->isThumb1Only()) {
15152 // This must be a constant between -7 and 7,
15153 // for 3-operand ADD/SUB immediate instructions.
15154 if (CVal >= -7 && CVal < 7)
15155 break;
15156 } else if (Subtarget->isThumb2()) {
15157 // A constant whose negation can be used as an immediate value in a
15158 // data-processing instruction. This can be used in GCC with an "n"
15159 // modifier that prints the negated value, for use with SUB
15160 // instructions. It is not useful otherwise but is implemented for
15161 // compatibility.
15162 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15163 break;
15164 } else {
15165 // A constant whose negation can be used as an immediate value in a
15166 // data-processing instruction. This can be used in GCC with an "n"
15167 // modifier that prints the negated value, for use with SUB
15168 // instructions. It is not useful otherwise but is implemented for
15169 // compatibility.
15170 if (ARM_AM::getSOImmVal(-CVal) != -1)
15171 break;
15173 return;
15175 case 'M':
15176 if (Subtarget->isThumb1Only()) {
15177 // This must be a multiple of 4 between 0 and 1020, for
15178 // ADD sp + immediate.
15179 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15180 break;
15181 } else {
15182 // A power of two or a constant between 0 and 32. This is used in
15183 // GCC for the shift amount on shifted register operands, but it is
15184 // useful in general for any shift amounts.
15185 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15186 break;
15188 return;
15190 case 'N':
15191 if (Subtarget->isThumb()) { // FIXME thumb2
15192 // This must be a constant between 0 and 31, for shift amounts.
15193 if (CVal >= 0 && CVal <= 31)
15194 break;
15196 return;
15198 case 'O':
15199 if (Subtarget->isThumb()) { // FIXME thumb2
15200 // This must be a multiple of 4 between -508 and 508, for
15201 // ADD/SUB sp = sp + immediate.
15202 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15203 break;
15205 return;
15207 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15208 break;
15211 if (Result.getNode()) {
15212 Ops.push_back(Result);
15213 return;
15215 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15218 static RTLIB::Libcall getDivRemLibcall(
15219 const SDNode *N, MVT::SimpleValueType SVT) {
15220 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15221 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15222 "Unhandled Opcode in getDivRemLibcall");
15223 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15224 N->getOpcode() == ISD::SREM;
15225 RTLIB::Libcall LC;
15226 switch (SVT) {
15227 default: llvm_unreachable("Unexpected request for libcall!");
15228 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15229 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15230 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15231 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15233 return LC;
15236 static TargetLowering::ArgListTy getDivRemArgList(
15237 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15238 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15239 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15240 "Unhandled Opcode in getDivRemArgList");
15241 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15242 N->getOpcode() == ISD::SREM;
15243 TargetLowering::ArgListTy Args;
15244 TargetLowering::ArgListEntry Entry;
15245 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15246 EVT ArgVT = N->getOperand(i).getValueType();
15247 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15248 Entry.Node = N->getOperand(i);
15249 Entry.Ty = ArgTy;
15250 Entry.IsSExt = isSigned;
15251 Entry.IsZExt = !isSigned;
15252 Args.push_back(Entry);
15254 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15255 std::swap(Args[0], Args[1]);
15256 return Args;
15259 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15260 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15261 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15262 Subtarget->isTargetWindows()) &&
15263 "Register-based DivRem lowering only");
15264 unsigned Opcode = Op->getOpcode();
15265 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15266 "Invalid opcode for Div/Rem lowering");
15267 bool isSigned = (Opcode == ISD::SDIVREM);
15268 EVT VT = Op->getValueType(0);
15269 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15270 SDLoc dl(Op);
15272 // If the target has hardware divide, use divide + multiply + subtract:
15273 // div = a / b
15274 // rem = a - b * div
15275 // return {div, rem}
15276 // This should be lowered into UDIV/SDIV + MLS later on.
15277 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15278 : Subtarget->hasDivideInARMMode();
15279 if (hasDivide && Op->getValueType(0).isSimple() &&
15280 Op->getSimpleValueType(0) == MVT::i32) {
15281 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15282 const SDValue Dividend = Op->getOperand(0);
15283 const SDValue Divisor = Op->getOperand(1);
15284 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15285 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15286 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15288 SDValue Values[2] = {Div, Rem};
15289 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15292 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15293 VT.getSimpleVT().SimpleTy);
15294 SDValue InChain = DAG.getEntryNode();
15296 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15297 DAG.getContext(),
15298 Subtarget);
15300 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15301 getPointerTy(DAG.getDataLayout()));
15303 Type *RetTy = StructType::get(Ty, Ty);
15305 if (Subtarget->isTargetWindows())
15306 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15308 TargetLowering::CallLoweringInfo CLI(DAG);
15309 CLI.setDebugLoc(dl).setChain(InChain)
15310 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15311 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15313 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15314 return CallInfo.first;
15317 // Lowers REM using divmod helpers
15318 // see RTABI section 4.2/4.3
15319 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15320 // Build return types (div and rem)
15321 std::vector<Type*> RetTyParams;
15322 Type *RetTyElement;
15324 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15325 default: llvm_unreachable("Unexpected request for libcall!");
15326 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15327 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15328 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15329 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15332 RetTyParams.push_back(RetTyElement);
15333 RetTyParams.push_back(RetTyElement);
15334 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15335 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15337 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15338 SimpleTy);
15339 SDValue InChain = DAG.getEntryNode();
15340 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15341 Subtarget);
15342 bool isSigned = N->getOpcode() == ISD::SREM;
15343 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15344 getPointerTy(DAG.getDataLayout()));
15346 if (Subtarget->isTargetWindows())
15347 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15349 // Lower call
15350 CallLoweringInfo CLI(DAG);
15351 CLI.setChain(InChain)
15352 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15353 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15354 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15356 // Return second (rem) result operand (first contains div)
15357 SDNode *ResNode = CallResult.first.getNode();
15358 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15359 return ResNode->getOperand(1);
15362 SDValue
15363 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15364 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15365 SDLoc DL(Op);
15367 // Get the inputs.
15368 SDValue Chain = Op.getOperand(0);
15369 SDValue Size = Op.getOperand(1);
15371 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15372 "no-stack-arg-probe")) {
15373 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15374 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15375 Chain = SP.getValue(1);
15376 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15377 if (Align)
15378 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15379 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15380 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15381 SDValue Ops[2] = { SP, Chain };
15382 return DAG.getMergeValues(Ops, DL);
15385 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15386 DAG.getConstant(2, DL, MVT::i32));
15388 SDValue Flag;
15389 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15390 Flag = Chain.getValue(1);
15392 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15393 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15395 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15396 Chain = NewSP.getValue(1);
15398 SDValue Ops[2] = { NewSP, Chain };
15399 return DAG.getMergeValues(Ops, DL);
15402 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15403 SDValue SrcVal = Op.getOperand(0);
15404 const unsigned DstSz = Op.getValueType().getSizeInBits();
15405 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15406 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15407 "Unexpected type for custom-lowering FP_EXTEND");
15409 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15410 "With both FP DP and 16, any FP conversion is legal!");
15412 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15413 "With FP16, 16 to 32 conversion is legal!");
15415 // Either we are converting from 16 -> 64, without FP16 and/or
15416 // FP.double-precision or without Armv8-fp. So we must do it in two
15417 // steps.
15418 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15419 // without FP16. So we must do a function call.
15420 SDLoc Loc(Op);
15421 RTLIB::Libcall LC;
15422 if (SrcSz == 16) {
15423 // Instruction from 16 -> 32
15424 if (Subtarget->hasFP16())
15425 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15426 // Lib call from 16 -> 32
15427 else {
15428 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15429 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15430 "Unexpected type for custom-lowering FP_EXTEND");
15431 SrcVal =
15432 makeLibCall(DAG, LC, MVT::f32, SrcVal, /*isSigned*/ false, Loc).first;
15436 if (DstSz != 64)
15437 return SrcVal;
15438 // For sure now SrcVal is 32 bits
15439 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15440 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15442 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15443 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15444 "Unexpected type for custom-lowering FP_EXTEND");
15445 return makeLibCall(DAG, LC, MVT::f64, SrcVal, /*isSigned*/ false, Loc).first;
15448 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15449 SDValue SrcVal = Op.getOperand(0);
15450 EVT SrcVT = SrcVal.getValueType();
15451 EVT DstVT = Op.getValueType();
15452 const unsigned DstSz = Op.getValueType().getSizeInBits();
15453 const unsigned SrcSz = SrcVT.getSizeInBits();
15454 (void)DstSz;
15455 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15456 "Unexpected type for custom-lowering FP_ROUND");
15458 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15459 "With both FP DP and 16, any FP conversion is legal!");
15461 SDLoc Loc(Op);
15463 // Instruction from 32 -> 16 if hasFP16 is valid
15464 if (SrcSz == 32 && Subtarget->hasFP16())
15465 return Op;
15467 // Lib call from 32 -> 16 / 64 -> [32, 16]
15468 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15469 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15470 "Unexpected type for custom-lowering FP_ROUND");
15471 return makeLibCall(DAG, LC, DstVT, SrcVal, /*isSigned*/ false, Loc).first;
15474 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15475 SelectionDAG &DAG) const {
15476 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15477 MVT HalfT = MVT::i32;
15478 SDLoc dl(N);
15479 SDValue Hi, Lo, Tmp;
15481 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15482 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15483 return ;
15485 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15486 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15488 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15489 DAG.getConstant(0, dl, HalfT));
15490 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15491 DAG.getConstant(1, dl, HalfT));
15493 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15494 DAG.getConstant(OpTypeBits - 1, dl,
15495 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15496 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15497 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15498 SDValue(Lo.getNode(), 1));
15499 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15500 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15502 Results.push_back(Lo);
15503 Results.push_back(Hi);
15506 bool
15507 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15508 // The ARM target isn't yet aware of offsets.
15509 return false;
15512 bool ARM::isBitFieldInvertedMask(unsigned v) {
15513 if (v == 0xffffffff)
15514 return false;
15516 // there can be 1's on either or both "outsides", all the "inside"
15517 // bits must be 0's
15518 return isShiftedMask_32(~v);
15521 /// isFPImmLegal - Returns true if the target can instruction select the
15522 /// specified FP immediate natively. If false, the legalizer will
15523 /// materialize the FP immediate as a load from a constant pool.
15524 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15525 bool ForCodeSize) const {
15526 if (!Subtarget->hasVFP3Base())
15527 return false;
15528 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15529 return ARM_AM::getFP16Imm(Imm) != -1;
15530 if (VT == MVT::f32)
15531 return ARM_AM::getFP32Imm(Imm) != -1;
15532 if (VT == MVT::f64 && Subtarget->hasFP64())
15533 return ARM_AM::getFP64Imm(Imm) != -1;
15534 return false;
15537 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15538 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15539 /// specified in the intrinsic calls.
15540 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15541 const CallInst &I,
15542 MachineFunction &MF,
15543 unsigned Intrinsic) const {
15544 switch (Intrinsic) {
15545 case Intrinsic::arm_neon_vld1:
15546 case Intrinsic::arm_neon_vld2:
15547 case Intrinsic::arm_neon_vld3:
15548 case Intrinsic::arm_neon_vld4:
15549 case Intrinsic::arm_neon_vld2lane:
15550 case Intrinsic::arm_neon_vld3lane:
15551 case Intrinsic::arm_neon_vld4lane:
15552 case Intrinsic::arm_neon_vld2dup:
15553 case Intrinsic::arm_neon_vld3dup:
15554 case Intrinsic::arm_neon_vld4dup: {
15555 Info.opc = ISD::INTRINSIC_W_CHAIN;
15556 // Conservatively set memVT to the entire set of vectors loaded.
15557 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15558 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15559 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15560 Info.ptrVal = I.getArgOperand(0);
15561 Info.offset = 0;
15562 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15563 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
15564 // volatile loads with NEON intrinsics not supported
15565 Info.flags = MachineMemOperand::MOLoad;
15566 return true;
15568 case Intrinsic::arm_neon_vld1x2:
15569 case Intrinsic::arm_neon_vld1x3:
15570 case Intrinsic::arm_neon_vld1x4: {
15571 Info.opc = ISD::INTRINSIC_W_CHAIN;
15572 // Conservatively set memVT to the entire set of vectors loaded.
15573 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15574 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15575 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15576 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15577 Info.offset = 0;
15578 Info.align = 0;
15579 // volatile loads with NEON intrinsics not supported
15580 Info.flags = MachineMemOperand::MOLoad;
15581 return true;
15583 case Intrinsic::arm_neon_vst1:
15584 case Intrinsic::arm_neon_vst2:
15585 case Intrinsic::arm_neon_vst3:
15586 case Intrinsic::arm_neon_vst4:
15587 case Intrinsic::arm_neon_vst2lane:
15588 case Intrinsic::arm_neon_vst3lane:
15589 case Intrinsic::arm_neon_vst4lane: {
15590 Info.opc = ISD::INTRINSIC_VOID;
15591 // Conservatively set memVT to the entire set of vectors stored.
15592 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15593 unsigned NumElts = 0;
15594 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15595 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15596 if (!ArgTy->isVectorTy())
15597 break;
15598 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15600 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15601 Info.ptrVal = I.getArgOperand(0);
15602 Info.offset = 0;
15603 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15604 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
15605 // volatile stores with NEON intrinsics not supported
15606 Info.flags = MachineMemOperand::MOStore;
15607 return true;
15609 case Intrinsic::arm_neon_vst1x2:
15610 case Intrinsic::arm_neon_vst1x3:
15611 case Intrinsic::arm_neon_vst1x4: {
15612 Info.opc = ISD::INTRINSIC_VOID;
15613 // Conservatively set memVT to the entire set of vectors stored.
15614 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15615 unsigned NumElts = 0;
15616 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15617 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15618 if (!ArgTy->isVectorTy())
15619 break;
15620 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15622 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15623 Info.ptrVal = I.getArgOperand(0);
15624 Info.offset = 0;
15625 Info.align = 0;
15626 // volatile stores with NEON intrinsics not supported
15627 Info.flags = MachineMemOperand::MOStore;
15628 return true;
15630 case Intrinsic::arm_ldaex:
15631 case Intrinsic::arm_ldrex: {
15632 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15633 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15634 Info.opc = ISD::INTRINSIC_W_CHAIN;
15635 Info.memVT = MVT::getVT(PtrTy->getElementType());
15636 Info.ptrVal = I.getArgOperand(0);
15637 Info.offset = 0;
15638 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15639 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15640 return true;
15642 case Intrinsic::arm_stlex:
15643 case Intrinsic::arm_strex: {
15644 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15645 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15646 Info.opc = ISD::INTRINSIC_W_CHAIN;
15647 Info.memVT = MVT::getVT(PtrTy->getElementType());
15648 Info.ptrVal = I.getArgOperand(1);
15649 Info.offset = 0;
15650 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
15651 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15652 return true;
15654 case Intrinsic::arm_stlexd:
15655 case Intrinsic::arm_strexd:
15656 Info.opc = ISD::INTRINSIC_W_CHAIN;
15657 Info.memVT = MVT::i64;
15658 Info.ptrVal = I.getArgOperand(2);
15659 Info.offset = 0;
15660 Info.align = 8;
15661 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15662 return true;
15664 case Intrinsic::arm_ldaexd:
15665 case Intrinsic::arm_ldrexd:
15666 Info.opc = ISD::INTRINSIC_W_CHAIN;
15667 Info.memVT = MVT::i64;
15668 Info.ptrVal = I.getArgOperand(0);
15669 Info.offset = 0;
15670 Info.align = 8;
15671 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15672 return true;
15674 default:
15675 break;
15678 return false;
15681 /// Returns true if it is beneficial to convert a load of a constant
15682 /// to just the constant itself.
15683 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15684 Type *Ty) const {
15685 assert(Ty->isIntegerTy());
15687 unsigned Bits = Ty->getPrimitiveSizeInBits();
15688 if (Bits == 0 || Bits > 32)
15689 return false;
15690 return true;
15693 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15694 unsigned Index) const {
15695 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15696 return false;
15698 return (Index == 0 || Index == ResVT.getVectorNumElements());
15701 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15702 ARM_MB::MemBOpt Domain) const {
15703 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15705 // First, if the target has no DMB, see what fallback we can use.
15706 if (!Subtarget->hasDataBarrier()) {
15707 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15708 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15709 // here.
15710 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15711 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15712 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15713 Builder.getInt32(0), Builder.getInt32(7),
15714 Builder.getInt32(10), Builder.getInt32(5)};
15715 return Builder.CreateCall(MCR, args);
15716 } else {
15717 // Instead of using barriers, atomic accesses on these subtargets use
15718 // libcalls.
15719 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15721 } else {
15722 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15723 // Only a full system barrier exists in the M-class architectures.
15724 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15725 Constant *CDomain = Builder.getInt32(Domain);
15726 return Builder.CreateCall(DMB, CDomain);
15730 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15731 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15732 Instruction *Inst,
15733 AtomicOrdering Ord) const {
15734 switch (Ord) {
15735 case AtomicOrdering::NotAtomic:
15736 case AtomicOrdering::Unordered:
15737 llvm_unreachable("Invalid fence: unordered/non-atomic");
15738 case AtomicOrdering::Monotonic:
15739 case AtomicOrdering::Acquire:
15740 return nullptr; // Nothing to do
15741 case AtomicOrdering::SequentiallyConsistent:
15742 if (!Inst->hasAtomicStore())
15743 return nullptr; // Nothing to do
15744 LLVM_FALLTHROUGH;
15745 case AtomicOrdering::Release:
15746 case AtomicOrdering::AcquireRelease:
15747 if (Subtarget->preferISHSTBarriers())
15748 return makeDMB(Builder, ARM_MB::ISHST);
15749 // FIXME: add a comment with a link to documentation justifying this.
15750 else
15751 return makeDMB(Builder, ARM_MB::ISH);
15753 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
15756 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
15757 Instruction *Inst,
15758 AtomicOrdering Ord) const {
15759 switch (Ord) {
15760 case AtomicOrdering::NotAtomic:
15761 case AtomicOrdering::Unordered:
15762 llvm_unreachable("Invalid fence: unordered/not-atomic");
15763 case AtomicOrdering::Monotonic:
15764 case AtomicOrdering::Release:
15765 return nullptr; // Nothing to do
15766 case AtomicOrdering::Acquire:
15767 case AtomicOrdering::AcquireRelease:
15768 case AtomicOrdering::SequentiallyConsistent:
15769 return makeDMB(Builder, ARM_MB::ISH);
15771 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
15774 // Loads and stores less than 64-bits are already atomic; ones above that
15775 // are doomed anyway, so defer to the default libcall and blame the OS when
15776 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15777 // anything for those.
15778 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15779 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15780 return (Size == 64) && !Subtarget->isMClass();
15783 // Loads and stores less than 64-bits are already atomic; ones above that
15784 // are doomed anyway, so defer to the default libcall and blame the OS when
15785 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
15786 // anything for those.
15787 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
15788 // guarantee, see DDI0406C ARM architecture reference manual,
15789 // sections A8.8.72-74 LDRD)
15790 TargetLowering::AtomicExpansionKind
15791 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15792 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15793 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
15794 : AtomicExpansionKind::None;
15797 // For the real atomic operations, we have ldrex/strex up to 32 bits,
15798 // and up to 64 bits on the non-M profiles
15799 TargetLowering::AtomicExpansionKind
15800 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15801 if (AI->isFloatingPointOperation())
15802 return AtomicExpansionKind::CmpXChg;
15804 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15805 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15806 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
15807 ? AtomicExpansionKind::LLSC
15808 : AtomicExpansionKind::None;
15811 TargetLowering::AtomicExpansionKind
15812 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
15813 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15814 // implement cmpxchg without spilling. If the address being exchanged is also
15815 // on the stack and close enough to the spill slot, this can lead to a
15816 // situation where the monitor always gets cleared and the atomic operation
15817 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15818 bool HasAtomicCmpXchg =
15819 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
15820 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
15821 return AtomicExpansionKind::LLSC;
15822 return AtomicExpansionKind::None;
15825 bool ARMTargetLowering::shouldInsertFencesForAtomic(
15826 const Instruction *I) const {
15827 return InsertFencesForAtomic;
15830 // This has so far only been implemented for MachO.
15831 bool ARMTargetLowering::useLoadStackGuardNode() const {
15832 return Subtarget->isTargetMachO();
15835 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
15836 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15837 return TargetLowering::insertSSPDeclarations(M);
15839 // MSVC CRT has a global variable holding security cookie.
15840 M.getOrInsertGlobal("__security_cookie",
15841 Type::getInt8PtrTy(M.getContext()));
15843 // MSVC CRT has a function to validate security cookie.
15844 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15845 "__security_check_cookie", Type::getVoidTy(M.getContext()),
15846 Type::getInt8PtrTy(M.getContext()));
15847 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
15848 F->addAttribute(1, Attribute::AttrKind::InReg);
15851 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
15852 // MSVC CRT has a global variable holding security cookie.
15853 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15854 return M.getGlobalVariable("__security_cookie");
15855 return TargetLowering::getSDagStackGuard(M);
15858 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
15859 // MSVC CRT has a function to validate security cookie.
15860 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15861 return M.getFunction("__security_check_cookie");
15862 return TargetLowering::getSSPStackGuardCheck(M);
15865 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
15866 unsigned &Cost) const {
15867 // If we do not have NEON, vector types are not natively supported.
15868 if (!Subtarget->hasNEON())
15869 return false;
15871 // Floating point values and vector values map to the same register file.
15872 // Therefore, although we could do a store extract of a vector type, this is
15873 // better to leave at float as we have more freedom in the addressing mode for
15874 // those.
15875 if (VectorTy->isFPOrFPVectorTy())
15876 return false;
15878 // If the index is unknown at compile time, this is very expensive to lower
15879 // and it is not possible to combine the store with the extract.
15880 if (!isa<ConstantInt>(Idx))
15881 return false;
15883 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
15884 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
15885 // We can do a store + vector extract on any vector that fits perfectly in a D
15886 // or Q register.
15887 if (BitWidth == 64 || BitWidth == 128) {
15888 Cost = 0;
15889 return true;
15891 return false;
15894 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
15895 return Subtarget->hasV6T2Ops();
15898 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
15899 return Subtarget->hasV6T2Ops();
15902 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
15903 return !Subtarget->hasMinSize();
15906 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15907 AtomicOrdering Ord) const {
15908 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15909 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15910 bool IsAcquire = isAcquireOrStronger(Ord);
15912 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
15913 // intrinsic must return {i32, i32} and we have to recombine them into a
15914 // single i64 here.
15915 if (ValTy->getPrimitiveSizeInBits() == 64) {
15916 Intrinsic::ID Int =
15917 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
15918 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
15920 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15921 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
15923 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15924 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15925 if (!Subtarget->isLittle())
15926 std::swap (Lo, Hi);
15927 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15928 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15929 return Builder.CreateOr(
15930 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
15933 Type *Tys[] = { Addr->getType() };
15934 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
15935 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
15937 return Builder.CreateTruncOrBitCast(
15938 Builder.CreateCall(Ldrex, Addr),
15939 cast<PointerType>(Addr->getType())->getElementType());
15942 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15943 IRBuilder<> &Builder) const {
15944 if (!Subtarget->hasV7Ops())
15945 return;
15946 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15947 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
15950 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
15951 Value *Addr,
15952 AtomicOrdering Ord) const {
15953 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15954 bool IsRelease = isReleaseOrStronger(Ord);
15956 // Since the intrinsics must have legal type, the i64 intrinsics take two
15957 // parameters: "i32, i32". We must marshal Val into the appropriate form
15958 // before the call.
15959 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
15960 Intrinsic::ID Int =
15961 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
15962 Function *Strex = Intrinsic::getDeclaration(M, Int);
15963 Type *Int32Ty = Type::getInt32Ty(M->getContext());
15965 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
15966 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
15967 if (!Subtarget->isLittle())
15968 std::swap(Lo, Hi);
15969 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15970 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
15973 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
15974 Type *Tys[] = { Addr->getType() };
15975 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
15977 return Builder.CreateCall(
15978 Strex, {Builder.CreateZExtOrBitCast(
15979 Val, Strex->getFunctionType()->getParamType(0)),
15980 Addr});
15984 bool ARMTargetLowering::alignLoopsWithOptSize() const {
15985 return Subtarget->isMClass();
15988 /// A helper function for determining the number of interleaved accesses we
15989 /// will generate when lowering accesses of the given type.
15990 unsigned
15991 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
15992 const DataLayout &DL) const {
15993 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
15996 bool ARMTargetLowering::isLegalInterleavedAccessType(
15997 VectorType *VecTy, const DataLayout &DL) const {
15999 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16000 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16002 // Ensure the vector doesn't have f16 elements. Even though we could do an
16003 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16004 // f32.
16005 if (VecTy->getElementType()->isHalfTy())
16006 return false;
16008 // Ensure the number of vector elements is greater than 1.
16009 if (VecTy->getNumElements() < 2)
16010 return false;
16012 // Ensure the element type is legal.
16013 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16014 return false;
16016 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16017 // 128 will be split into multiple interleaved accesses.
16018 return VecSize == 64 || VecSize % 128 == 0;
16021 /// Lower an interleaved load into a vldN intrinsic.
16023 /// E.g. Lower an interleaved load (Factor = 2):
16024 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16025 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16026 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16028 /// Into:
16029 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16030 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16031 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16032 bool ARMTargetLowering::lowerInterleavedLoad(
16033 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16034 ArrayRef<unsigned> Indices, unsigned Factor) const {
16035 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16036 "Invalid interleave factor");
16037 assert(!Shuffles.empty() && "Empty shufflevector input");
16038 assert(Shuffles.size() == Indices.size() &&
16039 "Unmatched number of shufflevectors and indices");
16041 VectorType *VecTy = Shuffles[0]->getType();
16042 Type *EltTy = VecTy->getVectorElementType();
16044 const DataLayout &DL = LI->getModule()->getDataLayout();
16046 // Skip if we do not have NEON and skip illegal vector types. We can
16047 // "legalize" wide vector types into multiple interleaved accesses as long as
16048 // the vector types are divisible by 128.
16049 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16050 return false;
16052 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16054 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16055 // load integer vectors first and then convert to pointer vectors.
16056 if (EltTy->isPointerTy())
16057 VecTy =
16058 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16060 IRBuilder<> Builder(LI);
16062 // The base address of the load.
16063 Value *BaseAddr = LI->getPointerOperand();
16065 if (NumLoads > 1) {
16066 // If we're going to generate more than one load, reset the sub-vector type
16067 // to something legal.
16068 VecTy = VectorType::get(VecTy->getVectorElementType(),
16069 VecTy->getVectorNumElements() / NumLoads);
16071 // We will compute the pointer operand of each load from the original base
16072 // address using GEPs. Cast the base address to a pointer to the scalar
16073 // element type.
16074 BaseAddr = Builder.CreateBitCast(
16075 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16076 LI->getPointerAddressSpace()));
16079 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16081 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16082 Type *Tys[] = {VecTy, Int8Ptr};
16083 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16084 Intrinsic::arm_neon_vld3,
16085 Intrinsic::arm_neon_vld4};
16086 Function *VldnFunc =
16087 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16089 // Holds sub-vectors extracted from the load intrinsic return values. The
16090 // sub-vectors are associated with the shufflevector instructions they will
16091 // replace.
16092 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16094 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16095 // If we're generating more than one load, compute the base address of
16096 // subsequent loads as an offset from the previous.
16097 if (LoadCount > 0)
16098 BaseAddr =
16099 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16100 VecTy->getVectorNumElements() * Factor);
16102 SmallVector<Value *, 2> Ops;
16103 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16104 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16106 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16108 // Replace uses of each shufflevector with the corresponding vector loaded
16109 // by ldN.
16110 for (unsigned i = 0; i < Shuffles.size(); i++) {
16111 ShuffleVectorInst *SV = Shuffles[i];
16112 unsigned Index = Indices[i];
16114 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16116 // Convert the integer vector to pointer vector if the element is pointer.
16117 if (EltTy->isPointerTy())
16118 SubVec = Builder.CreateIntToPtr(
16119 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16120 VecTy->getVectorNumElements()));
16122 SubVecs[SV].push_back(SubVec);
16126 // Replace uses of the shufflevector instructions with the sub-vectors
16127 // returned by the load intrinsic. If a shufflevector instruction is
16128 // associated with more than one sub-vector, those sub-vectors will be
16129 // concatenated into a single wide vector.
16130 for (ShuffleVectorInst *SVI : Shuffles) {
16131 auto &SubVec = SubVecs[SVI];
16132 auto *WideVec =
16133 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16134 SVI->replaceAllUsesWith(WideVec);
16137 return true;
16140 /// Lower an interleaved store into a vstN intrinsic.
16142 /// E.g. Lower an interleaved store (Factor = 3):
16143 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16144 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16145 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16147 /// Into:
16148 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16149 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16150 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16151 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16153 /// Note that the new shufflevectors will be removed and we'll only generate one
16154 /// vst3 instruction in CodeGen.
16156 /// Example for a more general valid mask (Factor 3). Lower:
16157 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16158 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16159 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16161 /// Into:
16162 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16163 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16164 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16165 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16166 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16167 ShuffleVectorInst *SVI,
16168 unsigned Factor) const {
16169 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16170 "Invalid interleave factor");
16172 VectorType *VecTy = SVI->getType();
16173 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16174 "Invalid interleaved store");
16176 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16177 Type *EltTy = VecTy->getVectorElementType();
16178 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16180 const DataLayout &DL = SI->getModule()->getDataLayout();
16182 // Skip if we do not have NEON and skip illegal vector types. We can
16183 // "legalize" wide vector types into multiple interleaved accesses as long as
16184 // the vector types are divisible by 128.
16185 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16186 return false;
16188 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16190 Value *Op0 = SVI->getOperand(0);
16191 Value *Op1 = SVI->getOperand(1);
16192 IRBuilder<> Builder(SI);
16194 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16195 // vectors to integer vectors.
16196 if (EltTy->isPointerTy()) {
16197 Type *IntTy = DL.getIntPtrType(EltTy);
16199 // Convert to the corresponding integer vector.
16200 Type *IntVecTy =
16201 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16202 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16203 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16205 SubVecTy = VectorType::get(IntTy, LaneLen);
16208 // The base address of the store.
16209 Value *BaseAddr = SI->getPointerOperand();
16211 if (NumStores > 1) {
16212 // If we're going to generate more than one store, reset the lane length
16213 // and sub-vector type to something legal.
16214 LaneLen /= NumStores;
16215 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16217 // We will compute the pointer operand of each store from the original base
16218 // address using GEPs. Cast the base address to a pointer to the scalar
16219 // element type.
16220 BaseAddr = Builder.CreateBitCast(
16221 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16222 SI->getPointerAddressSpace()));
16225 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16227 auto Mask = SVI->getShuffleMask();
16229 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16230 Type *Tys[] = {Int8Ptr, SubVecTy};
16231 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16232 Intrinsic::arm_neon_vst3,
16233 Intrinsic::arm_neon_vst4};
16235 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16236 // If we generating more than one store, we compute the base address of
16237 // subsequent stores as an offset from the previous.
16238 if (StoreCount > 0)
16239 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16240 BaseAddr, LaneLen * Factor);
16242 SmallVector<Value *, 6> Ops;
16243 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16245 Function *VstNFunc =
16246 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16248 // Split the shufflevector operands into sub vectors for the new vstN call.
16249 for (unsigned i = 0; i < Factor; i++) {
16250 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16251 if (Mask[IdxI] >= 0) {
16252 Ops.push_back(Builder.CreateShuffleVector(
16253 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16254 } else {
16255 unsigned StartMask = 0;
16256 for (unsigned j = 1; j < LaneLen; j++) {
16257 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16258 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16259 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16260 break;
16263 // Note: If all elements in a chunk are undefs, StartMask=0!
16264 // Note: Filling undef gaps with random elements is ok, since
16265 // those elements were being written anyway (with undefs).
16266 // In the case of all undefs we're defaulting to using elems from 0
16267 // Note: StartMask cannot be negative, it's checked in
16268 // isReInterleaveMask
16269 Ops.push_back(Builder.CreateShuffleVector(
16270 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16274 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16275 Builder.CreateCall(VstNFunc, Ops);
16277 return true;
16280 enum HABaseType {
16281 HA_UNKNOWN = 0,
16282 HA_FLOAT,
16283 HA_DOUBLE,
16284 HA_VECT64,
16285 HA_VECT128
16288 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16289 uint64_t &Members) {
16290 if (auto *ST = dyn_cast<StructType>(Ty)) {
16291 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16292 uint64_t SubMembers = 0;
16293 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16294 return false;
16295 Members += SubMembers;
16297 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16298 uint64_t SubMembers = 0;
16299 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16300 return false;
16301 Members += SubMembers * AT->getNumElements();
16302 } else if (Ty->isFloatTy()) {
16303 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16304 return false;
16305 Members = 1;
16306 Base = HA_FLOAT;
16307 } else if (Ty->isDoubleTy()) {
16308 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16309 return false;
16310 Members = 1;
16311 Base = HA_DOUBLE;
16312 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16313 Members = 1;
16314 switch (Base) {
16315 case HA_FLOAT:
16316 case HA_DOUBLE:
16317 return false;
16318 case HA_VECT64:
16319 return VT->getBitWidth() == 64;
16320 case HA_VECT128:
16321 return VT->getBitWidth() == 128;
16322 case HA_UNKNOWN:
16323 switch (VT->getBitWidth()) {
16324 case 64:
16325 Base = HA_VECT64;
16326 return true;
16327 case 128:
16328 Base = HA_VECT128;
16329 return true;
16330 default:
16331 return false;
16336 return (Members > 0 && Members <= 4);
16339 /// Return the correct alignment for the current calling convention.
16340 unsigned
16341 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16342 DataLayout DL) const {
16343 if (!ArgTy->isVectorTy())
16344 return DL.getABITypeAlignment(ArgTy);
16346 // Avoid over-aligning vector parameters. It would require realigning the
16347 // stack and waste space for no real benefit.
16348 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16351 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16352 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16353 /// passing according to AAPCS rules.
16354 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16355 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16356 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16357 CallingConv::ARM_AAPCS_VFP)
16358 return false;
16360 HABaseType Base = HA_UNKNOWN;
16361 uint64_t Members = 0;
16362 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16363 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16365 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16366 return IsHA || IsIntArray;
16369 unsigned ARMTargetLowering::getExceptionPointerRegister(
16370 const Constant *PersonalityFn) const {
16371 // Platforms which do not use SjLj EH may return values in these registers
16372 // via the personality function.
16373 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16376 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16377 const Constant *PersonalityFn) const {
16378 // Platforms which do not use SjLj EH may return values in these registers
16379 // via the personality function.
16380 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16383 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16384 // Update IsSplitCSR in ARMFunctionInfo.
16385 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16386 AFI->setIsSplitCSR(true);
16389 void ARMTargetLowering::insertCopiesSplitCSR(
16390 MachineBasicBlock *Entry,
16391 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16392 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16393 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16394 if (!IStart)
16395 return;
16397 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16398 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16399 MachineBasicBlock::iterator MBBI = Entry->begin();
16400 for (const MCPhysReg *I = IStart; *I; ++I) {
16401 const TargetRegisterClass *RC = nullptr;
16402 if (ARM::GPRRegClass.contains(*I))
16403 RC = &ARM::GPRRegClass;
16404 else if (ARM::DPRRegClass.contains(*I))
16405 RC = &ARM::DPRRegClass;
16406 else
16407 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16409 unsigned NewVR = MRI->createVirtualRegister(RC);
16410 // Create copy from CSR to a virtual register.
16411 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16412 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16413 // nounwind. If we want to generalize this later, we may need to emit
16414 // CFI pseudo-instructions.
16415 assert(Entry->getParent()->getFunction().hasFnAttribute(
16416 Attribute::NoUnwind) &&
16417 "Function should be nounwind in insertCopiesSplitCSR!");
16418 Entry->addLiveIn(*I);
16419 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16420 .addReg(*I);
16422 // Insert the copy-back instructions right before the terminator.
16423 for (auto *Exit : Exits)
16424 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16425 TII->get(TargetOpcode::COPY), *I)
16426 .addReg(NewVR);
16430 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16431 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16432 TargetLoweringBase::finalizeLowering(MF);