[LLVM][Alignment] Make functions using log of alignment explicit
[llvm-core.git] / lib / Target / ARM / ARMISelLowering.cpp
blobbbaa9431dec79b7fcf0fb6180e1bb2541b1e1552
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
12 //===----------------------------------------------------------------------===//
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
118 #define DEBUG_TYPE "arm-isel"
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(true));
131 static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(128));
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147 ARM::R0, ARM::R1, ARM::R2, ARM::R3
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151 MVT PromotedBitwiseVT) {
152 if (VT != PromotedLdStVT) {
153 setOperationAction(ISD::LOAD, VT, Promote);
154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
156 setOperationAction(ISD::STORE, VT, Promote);
157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
160 MVT ElemTy = VT.getVectorElementType();
161 if (ElemTy != MVT::f64)
162 setOperationAction(ISD::SETCC, VT, Custom);
163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165 if (ElemTy == MVT::i32) {
166 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170 } else {
171 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180 setOperationAction(ISD::SELECT, VT, Expand);
181 setOperationAction(ISD::SELECT_CC, VT, Expand);
182 setOperationAction(ISD::VSELECT, VT, Expand);
183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184 if (VT.isInteger()) {
185 setOperationAction(ISD::SHL, VT, Custom);
186 setOperationAction(ISD::SRA, VT, Custom);
187 setOperationAction(ISD::SRL, VT, Custom);
190 // Promote all bit-wise operations.
191 if (VT.isInteger() && VT != PromotedBitwiseVT) {
192 setOperationAction(ISD::AND, VT, Promote);
193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194 setOperationAction(ISD::OR, VT, Promote);
195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196 setOperationAction(ISD::XOR, VT, Promote);
197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
200 // Neon does not support vector divide/remainder operations.
201 setOperationAction(ISD::SDIV, VT, Expand);
202 setOperationAction(ISD::UDIV, VT, Expand);
203 setOperationAction(ISD::FDIV, VT, Expand);
204 setOperationAction(ISD::SREM, VT, Expand);
205 setOperationAction(ISD::UREM, VT, Expand);
206 setOperationAction(ISD::FREM, VT, Expand);
208 if (!VT.isFloatingPoint() &&
209 VT != MVT::v2i64 && VT != MVT::v1i64)
210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211 setOperationAction(Opcode, VT, Legal);
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215 addRegisterClass(VT, &ARM::DPRRegClass);
216 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220 addRegisterClass(VT, &ARM::DPairRegClass);
221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
224 void ARMTargetLowering::setAllExpand(MVT VT) {
225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
226 setOperationAction(Opc, VT, Expand);
228 // We support these really simple operations even on types where all
229 // the actual arithmetic has to be broken down into simpler
230 // operations or turned into library calls.
231 setOperationAction(ISD::BITCAST, VT, Legal);
232 setOperationAction(ISD::LOAD, VT, Legal);
233 setOperationAction(ISD::STORE, VT, Legal);
234 setOperationAction(ISD::UNDEF, VT, Legal);
237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
238 LegalizeAction Action) {
239 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
247 for (auto VT : IntTypes) {
248 addRegisterClass(VT, &ARM::MQPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SHL, VT, Custom);
254 setOperationAction(ISD::SRA, VT, Custom);
255 setOperationAction(ISD::SRL, VT, Custom);
256 setOperationAction(ISD::SMIN, VT, Legal);
257 setOperationAction(ISD::SMAX, VT, Legal);
258 setOperationAction(ISD::UMIN, VT, Legal);
259 setOperationAction(ISD::UMAX, VT, Legal);
260 setOperationAction(ISD::ABS, VT, Legal);
261 setOperationAction(ISD::SETCC, VT, Custom);
263 // No native support for these.
264 setOperationAction(ISD::UDIV, VT, Expand);
265 setOperationAction(ISD::SDIV, VT, Expand);
266 setOperationAction(ISD::UREM, VT, Expand);
267 setOperationAction(ISD::SREM, VT, Expand);
268 setOperationAction(ISD::CTPOP, VT, Expand);
270 // Vector reductions
271 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
273 if (!HasMVEFP) {
274 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
275 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
276 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
277 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
280 // Pre and Post inc are supported on loads and stores
281 for (unsigned im = (unsigned)ISD::PRE_INC;
282 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
283 setIndexedLoadAction(im, VT, Legal);
284 setIndexedStoreAction(im, VT, Legal);
288 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
289 for (auto VT : FloatTypes) {
290 addRegisterClass(VT, &ARM::MQPRRegClass);
291 if (!HasMVEFP)
292 setAllExpand(VT);
294 // These are legal or custom whether we have MVE.fp or not
295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
296 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
297 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
300 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
301 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
302 setOperationAction(ISD::SETCC, VT, Custom);
304 // Pre and Post inc are supported on loads and stores
305 for (unsigned im = (unsigned)ISD::PRE_INC;
306 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
307 setIndexedLoadAction(im, VT, Legal);
308 setIndexedStoreAction(im, VT, Legal);
311 if (HasMVEFP) {
312 setOperationAction(ISD::FMINNUM, VT, Legal);
313 setOperationAction(ISD::FMAXNUM, VT, Legal);
314 setOperationAction(ISD::FROUND, VT, Legal);
316 // No native support for these.
317 setOperationAction(ISD::FDIV, VT, Expand);
318 setOperationAction(ISD::FREM, VT, Expand);
319 setOperationAction(ISD::FSQRT, VT, Expand);
320 setOperationAction(ISD::FSIN, VT, Expand);
321 setOperationAction(ISD::FCOS, VT, Expand);
322 setOperationAction(ISD::FPOW, VT, Expand);
323 setOperationAction(ISD::FLOG, VT, Expand);
324 setOperationAction(ISD::FLOG2, VT, Expand);
325 setOperationAction(ISD::FLOG10, VT, Expand);
326 setOperationAction(ISD::FEXP, VT, Expand);
327 setOperationAction(ISD::FEXP2, VT, Expand);
328 setOperationAction(ISD::FNEARBYINT, VT, Expand);
332 // We 'support' these types up to bitcast/load/store level, regardless of
333 // MVE integer-only / float support. Only doing FP data processing on the FP
334 // vector types is inhibited at integer-only level.
335 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
336 for (auto VT : LongTypes) {
337 addRegisterClass(VT, &ARM::MQPRRegClass);
338 setAllExpand(VT);
339 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
343 // We can do bitwise operations on v2i64 vectors
344 setOperationAction(ISD::AND, MVT::v2i64, Legal);
345 setOperationAction(ISD::OR, MVT::v2i64, Legal);
346 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
348 // It is legal to extload from v4i8 to v4i16 or v4i32.
349 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
350 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
351 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
353 // Some truncating stores are legal too.
354 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
355 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
356 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
358 // Pre and Post inc on these are legal, given the correct extends
359 for (unsigned im = (unsigned)ISD::PRE_INC;
360 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
361 setIndexedLoadAction(im, MVT::v8i8, Legal);
362 setIndexedStoreAction(im, MVT::v8i8, Legal);
363 setIndexedLoadAction(im, MVT::v4i8, Legal);
364 setIndexedStoreAction(im, MVT::v4i8, Legal);
365 setIndexedLoadAction(im, MVT::v4i16, Legal);
366 setIndexedStoreAction(im, MVT::v4i16, Legal);
369 // Predicate types
370 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
371 for (auto VT : pTypes) {
372 addRegisterClass(VT, &ARM::VCCRRegClass);
373 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
374 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
375 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
376 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
377 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
378 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
379 setOperationAction(ISD::SETCC, VT, Custom);
380 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
384 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
385 const ARMSubtarget &STI)
386 : TargetLowering(TM), Subtarget(&STI) {
387 RegInfo = Subtarget->getRegisterInfo();
388 Itins = Subtarget->getInstrItineraryData();
390 setBooleanContents(ZeroOrOneBooleanContent);
391 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
393 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
394 !Subtarget->isTargetWatchOS()) {
395 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
396 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
397 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
398 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
399 : CallingConv::ARM_AAPCS);
402 if (Subtarget->isTargetMachO()) {
403 // Uses VFP for Thumb libfuncs if available.
404 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
405 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
406 static const struct {
407 const RTLIB::Libcall Op;
408 const char * const Name;
409 const ISD::CondCode Cond;
410 } LibraryCalls[] = {
411 // Single-precision floating-point arithmetic.
412 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
413 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
414 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
415 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
417 // Double-precision floating-point arithmetic.
418 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
419 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
420 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
421 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
423 // Single-precision comparisons.
424 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
425 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
426 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
427 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
428 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
429 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
430 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
431 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
433 // Double-precision comparisons.
434 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
435 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
436 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
437 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
438 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
439 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
440 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
441 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
443 // Floating-point to integer conversions.
444 // i64 conversions are done via library routines even when generating VFP
445 // instructions, so use the same ones.
446 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
447 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
448 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
449 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
451 // Conversions between floating types.
452 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
453 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
455 // Integer to floating-point conversions.
456 // i64 conversions are done via library routines even when generating VFP
457 // instructions, so use the same ones.
458 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
459 // e.g., __floatunsidf vs. __floatunssidfvfp.
460 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
461 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
462 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
463 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
466 for (const auto &LC : LibraryCalls) {
467 setLibcallName(LC.Op, LC.Name);
468 if (LC.Cond != ISD::SETCC_INVALID)
469 setCmpLibcallCC(LC.Op, LC.Cond);
474 // These libcalls are not available in 32-bit.
475 setLibcallName(RTLIB::SHL_I128, nullptr);
476 setLibcallName(RTLIB::SRL_I128, nullptr);
477 setLibcallName(RTLIB::SRA_I128, nullptr);
479 // RTLIB
480 if (Subtarget->isAAPCS_ABI() &&
481 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
482 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
483 static const struct {
484 const RTLIB::Libcall Op;
485 const char * const Name;
486 const CallingConv::ID CC;
487 const ISD::CondCode Cond;
488 } LibraryCalls[] = {
489 // Double-precision floating-point arithmetic helper functions
490 // RTABI chapter 4.1.2, Table 2
491 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
496 // Double-precision floating-point comparison helper functions
497 // RTABI chapter 4.1.2, Table 3
498 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
499 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
500 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
501 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
502 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
503 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
504 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
505 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
507 // Single-precision floating-point arithmetic helper functions
508 // RTABI chapter 4.1.2, Table 4
509 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 // Single-precision floating-point comparison helper functions
515 // RTABI chapter 4.1.2, Table 5
516 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
518 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
520 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
525 // Floating-point to integer conversions.
526 // RTABI chapter 4.1.2, Table 6
527 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
533 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
534 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
536 // Conversions between floating types.
537 // RTABI chapter 4.1.2, Table 7
538 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
539 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
540 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 // Integer to floating-point conversions.
543 // RTABI chapter 4.1.2, Table 8
544 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553 // Long long helper functions
554 // RTABI chapter 4.2, Table 9
555 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 // Integer division functions
561 // RTABI chapter 4.3.1
562 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
572 for (const auto &LC : LibraryCalls) {
573 setLibcallName(LC.Op, LC.Name);
574 setLibcallCallingConv(LC.Op, LC.CC);
575 if (LC.Cond != ISD::SETCC_INVALID)
576 setCmpLibcallCC(LC.Op, LC.Cond);
579 // EABI dependent RTLIB
580 if (TM.Options.EABIVersion == EABI::EABI4 ||
581 TM.Options.EABIVersion == EABI::EABI5) {
582 static const struct {
583 const RTLIB::Libcall Op;
584 const char *const Name;
585 const CallingConv::ID CC;
586 const ISD::CondCode Cond;
587 } MemOpsLibraryCalls[] = {
588 // Memory operations
589 // RTABI chapter 4.3.4
590 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595 for (const auto &LC : MemOpsLibraryCalls) {
596 setLibcallName(LC.Op, LC.Name);
597 setLibcallCallingConv(LC.Op, LC.CC);
598 if (LC.Cond != ISD::SETCC_INVALID)
599 setCmpLibcallCC(LC.Op, LC.Cond);
604 if (Subtarget->isTargetWindows()) {
605 static const struct {
606 const RTLIB::Libcall Op;
607 const char * const Name;
608 const CallingConv::ID CC;
609 } LibraryCalls[] = {
610 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
611 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
612 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
613 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
614 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
615 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
616 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
617 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
620 for (const auto &LC : LibraryCalls) {
621 setLibcallName(LC.Op, LC.Name);
622 setLibcallCallingConv(LC.Op, LC.CC);
626 // Use divmod compiler-rt calls for iOS 5.0 and later.
627 if (Subtarget->isTargetMachO() &&
628 !(Subtarget->isTargetIOS() &&
629 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
630 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
631 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
634 // The half <-> float conversion functions are always soft-float on
635 // non-watchos platforms, but are needed for some targets which use a
636 // hard-float calling convention by default.
637 if (!Subtarget->isTargetWatchABI()) {
638 if (Subtarget->isAAPCS_ABI()) {
639 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
640 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
641 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
642 } else {
643 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
644 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
645 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
649 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
650 // a __gnu_ prefix (which is the default).
651 if (Subtarget->isTargetAEABI()) {
652 static const struct {
653 const RTLIB::Libcall Op;
654 const char * const Name;
655 const CallingConv::ID CC;
656 } LibraryCalls[] = {
657 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
658 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
659 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
662 for (const auto &LC : LibraryCalls) {
663 setLibcallName(LC.Op, LC.Name);
664 setLibcallCallingConv(LC.Op, LC.CC);
668 if (Subtarget->isThumb1Only())
669 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
670 else
671 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
673 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
674 Subtarget->hasFPRegs()) {
675 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
676 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
677 if (!Subtarget->hasVFP2Base())
678 setAllExpand(MVT::f32);
679 if (!Subtarget->hasFP64())
680 setAllExpand(MVT::f64);
683 if (Subtarget->hasFullFP16()) {
684 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
685 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
686 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
687 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
689 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
690 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
693 for (MVT VT : MVT::vector_valuetypes()) {
694 for (MVT InnerVT : MVT::vector_valuetypes()) {
695 setTruncStoreAction(VT, InnerVT, Expand);
696 addAllExtLoads(VT, InnerVT, Expand);
699 setOperationAction(ISD::MULHS, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHU, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::BSWAP, VT, Expand);
707 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
708 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
710 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
711 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
713 if (Subtarget->hasMVEIntegerOps())
714 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
716 // Combine low-overhead loop intrinsics so that we can lower i1 types.
717 if (Subtarget->hasLOB()) {
718 setTargetDAGCombine(ISD::BRCOND);
719 setTargetDAGCombine(ISD::BR_CC);
722 if (Subtarget->hasNEON()) {
723 addDRTypeForNEON(MVT::v2f32);
724 addDRTypeForNEON(MVT::v8i8);
725 addDRTypeForNEON(MVT::v4i16);
726 addDRTypeForNEON(MVT::v2i32);
727 addDRTypeForNEON(MVT::v1i64);
729 addQRTypeForNEON(MVT::v4f32);
730 addQRTypeForNEON(MVT::v2f64);
731 addQRTypeForNEON(MVT::v16i8);
732 addQRTypeForNEON(MVT::v8i16);
733 addQRTypeForNEON(MVT::v4i32);
734 addQRTypeForNEON(MVT::v2i64);
736 if (Subtarget->hasFullFP16()) {
737 addQRTypeForNEON(MVT::v8f16);
738 addDRTypeForNEON(MVT::v4f16);
742 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
743 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
744 // none of Neon, MVE or VFP supports any arithmetic operations on it.
745 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
746 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
747 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
748 // FIXME: Code duplication: FDIV and FREM are expanded always, see
749 // ARMTargetLowering::addTypeForNEON method for details.
750 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
751 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
752 // FIXME: Create unittest.
753 // In another words, find a way when "copysign" appears in DAG with vector
754 // operands.
755 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
756 // FIXME: Code duplication: SETCC has custom operation action, see
757 // ARMTargetLowering::addTypeForNEON method for details.
758 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
759 // FIXME: Create unittest for FNEG and for FABS.
760 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
761 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
762 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
763 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
764 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
765 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
766 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
767 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
768 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
769 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
770 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
771 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
772 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
774 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
777 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
780 if (Subtarget->hasNEON()) {
781 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
782 // supported for v4f32.
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
784 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
785 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
786 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
787 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
788 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
789 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
790 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
791 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
792 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
793 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
794 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
795 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
796 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
798 // Mark v2f32 intrinsics.
799 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
800 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
801 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
802 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
803 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
804 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
805 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
806 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
807 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
808 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
809 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
810 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
811 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
812 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
814 // Neon does not support some operations on v1i64 and v2i64 types.
815 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
816 // Custom handling for some quad-vector types to detect VMULL.
817 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
818 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 // Custom handling for some vector types to avoid expensive expansions
821 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
822 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
823 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
824 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
825 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
826 // a destination type that is wider than the source, and nor does
827 // it have a FP_TO_[SU]INT instruction with a narrower destination than
828 // source.
829 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
831 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
832 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
833 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
834 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
836 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
838 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
839 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
841 // NEON does not have single instruction CTPOP for vectors with element
842 // types wider than 8-bits. However, custom lowering can leverage the
843 // v8i8/v16i8 vcnt instruction.
844 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
851 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
852 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
854 // NEON does not have single instruction CTTZ for vectors.
855 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
857 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
858 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
860 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
861 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
862 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
863 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
865 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
866 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
875 // NEON only has FMA instructions as of VFP4.
876 if (!Subtarget->hasVFP4Base()) {
877 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
878 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
881 setTargetDAGCombine(ISD::INTRINSIC_VOID);
882 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
883 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
884 setTargetDAGCombine(ISD::SHL);
885 setTargetDAGCombine(ISD::SRL);
886 setTargetDAGCombine(ISD::SRA);
887 setTargetDAGCombine(ISD::SIGN_EXTEND);
888 setTargetDAGCombine(ISD::ZERO_EXTEND);
889 setTargetDAGCombine(ISD::ANY_EXTEND);
890 setTargetDAGCombine(ISD::STORE);
891 setTargetDAGCombine(ISD::FP_TO_SINT);
892 setTargetDAGCombine(ISD::FP_TO_UINT);
893 setTargetDAGCombine(ISD::FDIV);
894 setTargetDAGCombine(ISD::LOAD);
896 // It is legal to extload from v4i8 to v4i16 or v4i32.
897 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
898 MVT::v2i32}) {
899 for (MVT VT : MVT::integer_vector_valuetypes()) {
900 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
901 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
902 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
907 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
908 setTargetDAGCombine(ISD::BUILD_VECTOR);
909 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
910 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
913 if (!Subtarget->hasFP64()) {
914 // When targeting a floating-point unit with only single-precision
915 // operations, f64 is legal for the few double-precision instructions which
916 // are present However, no double-precision operations other than moves,
917 // loads and stores are provided by the hardware.
918 setOperationAction(ISD::FADD, MVT::f64, Expand);
919 setOperationAction(ISD::FSUB, MVT::f64, Expand);
920 setOperationAction(ISD::FMUL, MVT::f64, Expand);
921 setOperationAction(ISD::FMA, MVT::f64, Expand);
922 setOperationAction(ISD::FDIV, MVT::f64, Expand);
923 setOperationAction(ISD::FREM, MVT::f64, Expand);
924 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
925 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
926 setOperationAction(ISD::FNEG, MVT::f64, Expand);
927 setOperationAction(ISD::FABS, MVT::f64, Expand);
928 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
929 setOperationAction(ISD::FSIN, MVT::f64, Expand);
930 setOperationAction(ISD::FCOS, MVT::f64, Expand);
931 setOperationAction(ISD::FPOW, MVT::f64, Expand);
932 setOperationAction(ISD::FLOG, MVT::f64, Expand);
933 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
934 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
935 setOperationAction(ISD::FEXP, MVT::f64, Expand);
936 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
937 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
938 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
939 setOperationAction(ISD::FRINT, MVT::f64, Expand);
940 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
941 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
942 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
943 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
944 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
945 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
946 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
947 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
948 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
951 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
952 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
953 if (Subtarget->hasFullFP16())
954 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
957 if (!Subtarget->hasFP16())
958 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
960 if (!Subtarget->hasFP64())
961 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
963 computeRegisterProperties(Subtarget->getRegisterInfo());
965 // ARM does not have floating-point extending loads.
966 for (MVT VT : MVT::fp_valuetypes()) {
967 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
968 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
971 // ... or truncating stores
972 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
973 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
974 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
976 // ARM does not have i1 sign extending load.
977 for (MVT VT : MVT::integer_valuetypes())
978 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
980 // ARM supports all 4 flavors of integer indexed load / store.
981 if (!Subtarget->isThumb1Only()) {
982 for (unsigned im = (unsigned)ISD::PRE_INC;
983 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
984 setIndexedLoadAction(im, MVT::i1, Legal);
985 setIndexedLoadAction(im, MVT::i8, Legal);
986 setIndexedLoadAction(im, MVT::i16, Legal);
987 setIndexedLoadAction(im, MVT::i32, Legal);
988 setIndexedStoreAction(im, MVT::i1, Legal);
989 setIndexedStoreAction(im, MVT::i8, Legal);
990 setIndexedStoreAction(im, MVT::i16, Legal);
991 setIndexedStoreAction(im, MVT::i32, Legal);
993 } else {
994 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
995 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
996 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
999 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1000 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1001 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1002 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1004 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1005 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1007 // i64 operation support.
1008 setOperationAction(ISD::MUL, MVT::i64, Expand);
1009 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1010 if (Subtarget->isThumb1Only()) {
1011 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1012 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1014 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1015 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1016 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1018 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1019 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1020 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1021 setOperationAction(ISD::SRL, MVT::i64, Custom);
1022 setOperationAction(ISD::SRA, MVT::i64, Custom);
1023 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1024 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1026 // MVE lowers 64 bit shifts to lsll and lsrl
1027 // assuming that ISD::SRL and SRA of i64 are already marked custom
1028 if (Subtarget->hasMVEIntegerOps())
1029 setOperationAction(ISD::SHL, MVT::i64, Custom);
1031 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1032 if (Subtarget->isThumb1Only()) {
1033 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1034 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1035 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1038 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1039 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1041 // ARM does not have ROTL.
1042 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1043 for (MVT VT : MVT::vector_valuetypes()) {
1044 setOperationAction(ISD::ROTL, VT, Expand);
1045 setOperationAction(ISD::ROTR, VT, Expand);
1047 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1048 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1049 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1050 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1051 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1054 // @llvm.readcyclecounter requires the Performance Monitors extension.
1055 // Default to the 0 expansion on unsupported platforms.
1056 // FIXME: Technically there are older ARM CPUs that have
1057 // implementation-specific ways of obtaining this information.
1058 if (Subtarget->hasPerfMon())
1059 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1061 // Only ARMv6 has BSWAP.
1062 if (!Subtarget->hasV6Ops())
1063 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1065 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1066 : Subtarget->hasDivideInARMMode();
1067 if (!hasDivide) {
1068 // These are expanded into libcalls if the cpu doesn't have HW divider.
1069 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1070 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1073 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1074 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1075 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1077 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1078 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1081 setOperationAction(ISD::SREM, MVT::i32, Expand);
1082 setOperationAction(ISD::UREM, MVT::i32, Expand);
1084 // Register based DivRem for AEABI (RTABI 4.2)
1085 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1086 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1087 Subtarget->isTargetWindows()) {
1088 setOperationAction(ISD::SREM, MVT::i64, Custom);
1089 setOperationAction(ISD::UREM, MVT::i64, Custom);
1090 HasStandaloneRem = false;
1092 if (Subtarget->isTargetWindows()) {
1093 const struct {
1094 const RTLIB::Libcall Op;
1095 const char * const Name;
1096 const CallingConv::ID CC;
1097 } LibraryCalls[] = {
1098 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1099 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1100 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1101 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1103 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1104 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1105 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1106 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1109 for (const auto &LC : LibraryCalls) {
1110 setLibcallName(LC.Op, LC.Name);
1111 setLibcallCallingConv(LC.Op, LC.CC);
1113 } else {
1114 const struct {
1115 const RTLIB::Libcall Op;
1116 const char * const Name;
1117 const CallingConv::ID CC;
1118 } LibraryCalls[] = {
1119 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1120 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1121 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1122 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1124 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1125 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1126 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1127 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1130 for (const auto &LC : LibraryCalls) {
1131 setLibcallName(LC.Op, LC.Name);
1132 setLibcallCallingConv(LC.Op, LC.CC);
1136 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1137 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1138 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1139 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1140 } else {
1141 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1142 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1145 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1146 for (auto &VT : {MVT::f32, MVT::f64})
1147 setOperationAction(ISD::FPOWI, VT, Custom);
1149 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1150 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1151 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1152 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1154 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1155 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1157 // Use the default implementation.
1158 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1159 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1160 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1161 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1162 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1163 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1165 if (Subtarget->isTargetWindows())
1166 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1167 else
1168 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1170 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1171 // the default expansion.
1172 InsertFencesForAtomic = false;
1173 if (Subtarget->hasAnyDataBarrier() &&
1174 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1175 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1176 // to ldrex/strex loops already.
1177 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1178 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1179 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1181 // On v8, we have particularly efficient implementations of atomic fences
1182 // if they can be combined with nearby atomic loads and stores.
1183 if (!Subtarget->hasAcquireRelease() ||
1184 getTargetMachine().getOptLevel() == 0) {
1185 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1186 InsertFencesForAtomic = true;
1188 } else {
1189 // If there's anything we can use as a barrier, go through custom lowering
1190 // for ATOMIC_FENCE.
1191 // If target has DMB in thumb, Fences can be inserted.
1192 if (Subtarget->hasDataBarrier())
1193 InsertFencesForAtomic = true;
1195 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1196 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1198 // Set them all for expansion, which will force libcalls.
1199 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1200 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1201 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1202 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1203 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1204 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1205 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1206 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1207 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1208 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1209 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1210 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1211 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1212 // Unordered/Monotonic case.
1213 if (!InsertFencesForAtomic) {
1214 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1215 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1219 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1221 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1222 if (!Subtarget->hasV6Ops()) {
1223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1228 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1229 !Subtarget->isThumb1Only()) {
1230 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1231 // iff target supports vfp2.
1232 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1233 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1236 // We want to custom lower some of our intrinsics.
1237 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1238 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1239 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1240 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1241 if (Subtarget->useSjLjEH())
1242 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1244 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1245 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1246 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1247 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1248 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1249 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1250 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1251 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1252 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1253 if (Subtarget->hasFullFP16()) {
1254 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1255 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1256 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1259 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1261 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1262 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1263 if (Subtarget->hasFullFP16())
1264 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1265 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1266 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1267 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1269 // We don't support sin/cos/fmod/copysign/pow
1270 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1271 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1272 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1273 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1275 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1276 setOperationAction(ISD::FREM, MVT::f64, Expand);
1277 setOperationAction(ISD::FREM, MVT::f32, Expand);
1278 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1279 !Subtarget->isThumb1Only()) {
1280 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1281 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1283 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1284 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1286 if (!Subtarget->hasVFP4Base()) {
1287 setOperationAction(ISD::FMA, MVT::f64, Expand);
1288 setOperationAction(ISD::FMA, MVT::f32, Expand);
1291 // Various VFP goodness
1292 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1293 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1294 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1295 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1296 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1299 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1300 if (!Subtarget->hasFP16()) {
1301 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1302 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1306 // Use __sincos_stret if available.
1307 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1308 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1309 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1310 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1313 // FP-ARMv8 implements a lot of rounding-like FP operations.
1314 if (Subtarget->hasFPARMv8Base()) {
1315 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1316 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1317 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1319 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1320 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1321 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1322 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1323 if (Subtarget->hasNEON()) {
1324 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1325 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1326 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1327 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1330 if (Subtarget->hasFP64()) {
1331 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1332 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1333 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1334 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1335 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1336 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1337 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1338 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1342 // FP16 often need to be promoted to call lib functions
1343 if (Subtarget->hasFullFP16()) {
1344 setOperationAction(ISD::FREM, MVT::f16, Promote);
1345 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1346 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1349 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1350 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1351 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1352 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1353 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1354 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1355 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1357 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1360 if (Subtarget->hasNEON()) {
1361 // vmin and vmax aren't available in a scalar form, so we use
1362 // a NEON instruction with an undef lane instead.
1363 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1364 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1365 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1366 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1367 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1368 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1369 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1370 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1372 if (Subtarget->hasFullFP16()) {
1373 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1374 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1375 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1376 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1378 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1379 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1380 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1381 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1385 // We have target-specific dag combine patterns for the following nodes:
1386 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1387 setTargetDAGCombine(ISD::ADD);
1388 setTargetDAGCombine(ISD::SUB);
1389 setTargetDAGCombine(ISD::MUL);
1390 setTargetDAGCombine(ISD::AND);
1391 setTargetDAGCombine(ISD::OR);
1392 setTargetDAGCombine(ISD::XOR);
1394 if (Subtarget->hasV6Ops())
1395 setTargetDAGCombine(ISD::SRL);
1396 if (Subtarget->isThumb1Only())
1397 setTargetDAGCombine(ISD::SHL);
1399 setStackPointerRegisterToSaveRestore(ARM::SP);
1401 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1402 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1403 setSchedulingPreference(Sched::RegPressure);
1404 else
1405 setSchedulingPreference(Sched::Hybrid);
1407 //// temporary - rewrite interface to use type
1408 MaxStoresPerMemset = 8;
1409 MaxStoresPerMemsetOptSize = 4;
1410 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1411 MaxStoresPerMemcpyOptSize = 2;
1412 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1413 MaxStoresPerMemmoveOptSize = 2;
1415 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1416 // are at least 4 bytes aligned.
1417 setMinStackArgumentAlignment(4);
1419 // Prefer likely predicted branches to selects on out-of-order cores.
1420 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1422 setPrefLoopLogAlignment(Subtarget->getPrefLoopLogAlignment());
1424 setMinFunctionLogAlignment(Subtarget->isThumb() ? 1 : 2);
1426 if (Subtarget->isThumb() || Subtarget->isThumb2())
1427 setTargetDAGCombine(ISD::ABS);
1430 bool ARMTargetLowering::useSoftFloat() const {
1431 return Subtarget->useSoftFloat();
1434 // FIXME: It might make sense to define the representative register class as the
1435 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1436 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1437 // SPR's representative would be DPR_VFP2. This should work well if register
1438 // pressure tracking were modified such that a register use would increment the
1439 // pressure of the register class's representative and all of it's super
1440 // classes' representatives transitively. We have not implemented this because
1441 // of the difficulty prior to coalescing of modeling operand register classes
1442 // due to the common occurrence of cross class copies and subregister insertions
1443 // and extractions.
1444 std::pair<const TargetRegisterClass *, uint8_t>
1445 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1446 MVT VT) const {
1447 const TargetRegisterClass *RRC = nullptr;
1448 uint8_t Cost = 1;
1449 switch (VT.SimpleTy) {
1450 default:
1451 return TargetLowering::findRepresentativeClass(TRI, VT);
1452 // Use DPR as representative register class for all floating point
1453 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1454 // the cost is 1 for both f32 and f64.
1455 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1456 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1457 RRC = &ARM::DPRRegClass;
1458 // When NEON is used for SP, only half of the register file is available
1459 // because operations that define both SP and DP results will be constrained
1460 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1461 // coalescing by double-counting the SP regs. See the FIXME above.
1462 if (Subtarget->useNEONForSinglePrecisionFP())
1463 Cost = 2;
1464 break;
1465 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1466 case MVT::v4f32: case MVT::v2f64:
1467 RRC = &ARM::DPRRegClass;
1468 Cost = 2;
1469 break;
1470 case MVT::v4i64:
1471 RRC = &ARM::DPRRegClass;
1472 Cost = 4;
1473 break;
1474 case MVT::v8i64:
1475 RRC = &ARM::DPRRegClass;
1476 Cost = 8;
1477 break;
1479 return std::make_pair(RRC, Cost);
1482 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1483 switch ((ARMISD::NodeType)Opcode) {
1484 case ARMISD::FIRST_NUMBER: break;
1485 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1486 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1487 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1488 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1489 case ARMISD::CALL: return "ARMISD::CALL";
1490 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1491 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1492 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1493 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1494 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1495 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1496 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1497 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1498 case ARMISD::CMP: return "ARMISD::CMP";
1499 case ARMISD::CMN: return "ARMISD::CMN";
1500 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1501 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1502 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1503 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1504 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1506 case ARMISD::CMOV: return "ARMISD::CMOV";
1507 case ARMISD::SUBS: return "ARMISD::SUBS";
1509 case ARMISD::SSAT: return "ARMISD::SSAT";
1510 case ARMISD::USAT: return "ARMISD::USAT";
1512 case ARMISD::ASRL: return "ARMISD::ASRL";
1513 case ARMISD::LSRL: return "ARMISD::LSRL";
1514 case ARMISD::LSLL: return "ARMISD::LSLL";
1516 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1517 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1518 case ARMISD::RRX: return "ARMISD::RRX";
1520 case ARMISD::ADDC: return "ARMISD::ADDC";
1521 case ARMISD::ADDE: return "ARMISD::ADDE";
1522 case ARMISD::SUBC: return "ARMISD::SUBC";
1523 case ARMISD::SUBE: return "ARMISD::SUBE";
1524 case ARMISD::LSLS: return "ARMISD::LSLS";
1526 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1527 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1528 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1529 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1530 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1532 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1533 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1534 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1536 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1538 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1540 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1542 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1544 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1546 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1547 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1549 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1550 case ARMISD::VCMP: return "ARMISD::VCMP";
1551 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1552 case ARMISD::VTST: return "ARMISD::VTST";
1554 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1555 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1556 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1557 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1558 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1559 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1560 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1561 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1562 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1563 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1564 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1565 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1566 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1567 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1568 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1569 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1570 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1571 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1572 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1573 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1574 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1575 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1576 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1577 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1578 case ARMISD::VDUP: return "ARMISD::VDUP";
1579 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1580 case ARMISD::VEXT: return "ARMISD::VEXT";
1581 case ARMISD::VREV64: return "ARMISD::VREV64";
1582 case ARMISD::VREV32: return "ARMISD::VREV32";
1583 case ARMISD::VREV16: return "ARMISD::VREV16";
1584 case ARMISD::VZIP: return "ARMISD::VZIP";
1585 case ARMISD::VUZP: return "ARMISD::VUZP";
1586 case ARMISD::VTRN: return "ARMISD::VTRN";
1587 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1588 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1589 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1590 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1591 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1592 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1593 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1594 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1595 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1596 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1597 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1598 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1599 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1600 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1601 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1602 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1603 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1604 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1605 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1606 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1607 case ARMISD::BFI: return "ARMISD::BFI";
1608 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1609 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1610 case ARMISD::VBSL: return "ARMISD::VBSL";
1611 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1612 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1613 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1614 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1615 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1616 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1617 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1618 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1619 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1620 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1621 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1622 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1623 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1624 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1625 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1626 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1627 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1628 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1629 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1630 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1631 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1632 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1633 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1634 case ARMISD::WLS: return "ARMISD::WLS";
1635 case ARMISD::LE: return "ARMISD::LE";
1636 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1637 case ARMISD::CSINV: return "ARMISD::CSINV";
1638 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1639 case ARMISD::CSINC: return "ARMISD::CSINC";
1641 return nullptr;
1644 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1645 EVT VT) const {
1646 if (!VT.isVector())
1647 return getPointerTy(DL);
1649 // MVE has a predicate register.
1650 if (Subtarget->hasMVEIntegerOps() &&
1651 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1652 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1653 return VT.changeVectorElementTypeToInteger();
1656 /// getRegClassFor - Return the register class that should be used for the
1657 /// specified value type.
1658 const TargetRegisterClass *
1659 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1660 (void)isDivergent;
1661 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1662 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1663 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1664 // MVE Q registers.
1665 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1666 if (VT == MVT::v4i64)
1667 return &ARM::QQPRRegClass;
1668 if (VT == MVT::v8i64)
1669 return &ARM::QQQQPRRegClass;
1671 return TargetLowering::getRegClassFor(VT);
1674 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1675 // source/dest is aligned and the copy size is large enough. We therefore want
1676 // to align such objects passed to memory intrinsics.
1677 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1678 unsigned &PrefAlign) const {
1679 if (!isa<MemIntrinsic>(CI))
1680 return false;
1681 MinSize = 8;
1682 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1683 // cycle faster than 4-byte aligned LDM.
1684 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1685 return true;
1688 // Create a fast isel object.
1689 FastISel *
1690 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1691 const TargetLibraryInfo *libInfo) const {
1692 return ARM::createFastISel(funcInfo, libInfo);
1695 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1696 unsigned NumVals = N->getNumValues();
1697 if (!NumVals)
1698 return Sched::RegPressure;
1700 for (unsigned i = 0; i != NumVals; ++i) {
1701 EVT VT = N->getValueType(i);
1702 if (VT == MVT::Glue || VT == MVT::Other)
1703 continue;
1704 if (VT.isFloatingPoint() || VT.isVector())
1705 return Sched::ILP;
1708 if (!N->isMachineOpcode())
1709 return Sched::RegPressure;
1711 // Load are scheduled for latency even if there instruction itinerary
1712 // is not available.
1713 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1714 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1716 if (MCID.getNumDefs() == 0)
1717 return Sched::RegPressure;
1718 if (!Itins->isEmpty() &&
1719 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1720 return Sched::ILP;
1722 return Sched::RegPressure;
1725 //===----------------------------------------------------------------------===//
1726 // Lowering Code
1727 //===----------------------------------------------------------------------===//
1729 static bool isSRL16(const SDValue &Op) {
1730 if (Op.getOpcode() != ISD::SRL)
1731 return false;
1732 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1733 return Const->getZExtValue() == 16;
1734 return false;
1737 static bool isSRA16(const SDValue &Op) {
1738 if (Op.getOpcode() != ISD::SRA)
1739 return false;
1740 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1741 return Const->getZExtValue() == 16;
1742 return false;
1745 static bool isSHL16(const SDValue &Op) {
1746 if (Op.getOpcode() != ISD::SHL)
1747 return false;
1748 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1749 return Const->getZExtValue() == 16;
1750 return false;
1753 // Check for a signed 16-bit value. We special case SRA because it makes it
1754 // more simple when also looking for SRAs that aren't sign extending a
1755 // smaller value. Without the check, we'd need to take extra care with
1756 // checking order for some operations.
1757 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1758 if (isSRA16(Op))
1759 return isSHL16(Op.getOperand(0));
1760 return DAG.ComputeNumSignBits(Op) == 17;
1763 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1764 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1765 switch (CC) {
1766 default: llvm_unreachable("Unknown condition code!");
1767 case ISD::SETNE: return ARMCC::NE;
1768 case ISD::SETEQ: return ARMCC::EQ;
1769 case ISD::SETGT: return ARMCC::GT;
1770 case ISD::SETGE: return ARMCC::GE;
1771 case ISD::SETLT: return ARMCC::LT;
1772 case ISD::SETLE: return ARMCC::LE;
1773 case ISD::SETUGT: return ARMCC::HI;
1774 case ISD::SETUGE: return ARMCC::HS;
1775 case ISD::SETULT: return ARMCC::LO;
1776 case ISD::SETULE: return ARMCC::LS;
1780 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1781 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1782 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1783 CondCode2 = ARMCC::AL;
1784 InvalidOnQNaN = true;
1785 switch (CC) {
1786 default: llvm_unreachable("Unknown FP condition!");
1787 case ISD::SETEQ:
1788 case ISD::SETOEQ:
1789 CondCode = ARMCC::EQ;
1790 InvalidOnQNaN = false;
1791 break;
1792 case ISD::SETGT:
1793 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1794 case ISD::SETGE:
1795 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1796 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1797 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1798 case ISD::SETONE:
1799 CondCode = ARMCC::MI;
1800 CondCode2 = ARMCC::GT;
1801 InvalidOnQNaN = false;
1802 break;
1803 case ISD::SETO: CondCode = ARMCC::VC; break;
1804 case ISD::SETUO: CondCode = ARMCC::VS; break;
1805 case ISD::SETUEQ:
1806 CondCode = ARMCC::EQ;
1807 CondCode2 = ARMCC::VS;
1808 InvalidOnQNaN = false;
1809 break;
1810 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1811 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1812 case ISD::SETLT:
1813 case ISD::SETULT: CondCode = ARMCC::LT; break;
1814 case ISD::SETLE:
1815 case ISD::SETULE: CondCode = ARMCC::LE; break;
1816 case ISD::SETNE:
1817 case ISD::SETUNE:
1818 CondCode = ARMCC::NE;
1819 InvalidOnQNaN = false;
1820 break;
1824 //===----------------------------------------------------------------------===//
1825 // Calling Convention Implementation
1826 //===----------------------------------------------------------------------===//
1828 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1829 /// account presence of floating point hardware and calling convention
1830 /// limitations, such as support for variadic functions.
1831 CallingConv::ID
1832 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1833 bool isVarArg) const {
1834 switch (CC) {
1835 default:
1836 report_fatal_error("Unsupported calling convention");
1837 case CallingConv::ARM_AAPCS:
1838 case CallingConv::ARM_APCS:
1839 case CallingConv::GHC:
1840 return CC;
1841 case CallingConv::PreserveMost:
1842 return CallingConv::PreserveMost;
1843 case CallingConv::ARM_AAPCS_VFP:
1844 case CallingConv::Swift:
1845 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1846 case CallingConv::C:
1847 if (!Subtarget->isAAPCS_ABI())
1848 return CallingConv::ARM_APCS;
1849 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1850 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1851 !isVarArg)
1852 return CallingConv::ARM_AAPCS_VFP;
1853 else
1854 return CallingConv::ARM_AAPCS;
1855 case CallingConv::Fast:
1856 case CallingConv::CXX_FAST_TLS:
1857 if (!Subtarget->isAAPCS_ABI()) {
1858 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1859 return CallingConv::Fast;
1860 return CallingConv::ARM_APCS;
1861 } else if (Subtarget->hasVFP2Base() &&
1862 !Subtarget->isThumb1Only() && !isVarArg)
1863 return CallingConv::ARM_AAPCS_VFP;
1864 else
1865 return CallingConv::ARM_AAPCS;
1869 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1870 bool isVarArg) const {
1871 return CCAssignFnForNode(CC, false, isVarArg);
1874 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1875 bool isVarArg) const {
1876 return CCAssignFnForNode(CC, true, isVarArg);
1879 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1880 /// CallingConvention.
1881 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1882 bool Return,
1883 bool isVarArg) const {
1884 switch (getEffectiveCallingConv(CC, isVarArg)) {
1885 default:
1886 report_fatal_error("Unsupported calling convention");
1887 case CallingConv::ARM_APCS:
1888 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1889 case CallingConv::ARM_AAPCS:
1890 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1891 case CallingConv::ARM_AAPCS_VFP:
1892 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1893 case CallingConv::Fast:
1894 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1895 case CallingConv::GHC:
1896 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1897 case CallingConv::PreserveMost:
1898 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1902 /// LowerCallResult - Lower the result values of a call into the
1903 /// appropriate copies out of appropriate physical registers.
1904 SDValue ARMTargetLowering::LowerCallResult(
1905 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1906 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1907 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1908 SDValue ThisVal) const {
1909 // Assign locations to each value returned by this call.
1910 SmallVector<CCValAssign, 16> RVLocs;
1911 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1912 *DAG.getContext());
1913 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1915 // Copy all of the result registers out of their specified physreg.
1916 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1917 CCValAssign VA = RVLocs[i];
1919 // Pass 'this' value directly from the argument to return value, to avoid
1920 // reg unit interference
1921 if (i == 0 && isThisReturn) {
1922 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1923 "unexpected return calling convention register assignment");
1924 InVals.push_back(ThisVal);
1925 continue;
1928 SDValue Val;
1929 if (VA.needsCustom()) {
1930 // Handle f64 or half of a v2f64.
1931 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1932 InFlag);
1933 Chain = Lo.getValue(1);
1934 InFlag = Lo.getValue(2);
1935 VA = RVLocs[++i]; // skip ahead to next loc
1936 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1937 InFlag);
1938 Chain = Hi.getValue(1);
1939 InFlag = Hi.getValue(2);
1940 if (!Subtarget->isLittle())
1941 std::swap (Lo, Hi);
1942 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1944 if (VA.getLocVT() == MVT::v2f64) {
1945 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1946 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1947 DAG.getConstant(0, dl, MVT::i32));
1949 VA = RVLocs[++i]; // skip ahead to next loc
1950 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1951 Chain = Lo.getValue(1);
1952 InFlag = Lo.getValue(2);
1953 VA = RVLocs[++i]; // skip ahead to next loc
1954 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1955 Chain = Hi.getValue(1);
1956 InFlag = Hi.getValue(2);
1957 if (!Subtarget->isLittle())
1958 std::swap (Lo, Hi);
1959 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1960 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1961 DAG.getConstant(1, dl, MVT::i32));
1963 } else {
1964 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1965 InFlag);
1966 Chain = Val.getValue(1);
1967 InFlag = Val.getValue(2);
1970 switch (VA.getLocInfo()) {
1971 default: llvm_unreachable("Unknown loc info!");
1972 case CCValAssign::Full: break;
1973 case CCValAssign::BCvt:
1974 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1975 break;
1978 InVals.push_back(Val);
1981 return Chain;
1984 /// LowerMemOpCallTo - Store the argument to the stack.
1985 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1986 SDValue Arg, const SDLoc &dl,
1987 SelectionDAG &DAG,
1988 const CCValAssign &VA,
1989 ISD::ArgFlagsTy Flags) const {
1990 unsigned LocMemOffset = VA.getLocMemOffset();
1991 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1992 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1993 StackPtr, PtrOff);
1994 return DAG.getStore(
1995 Chain, dl, Arg, PtrOff,
1996 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1999 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2000 SDValue Chain, SDValue &Arg,
2001 RegsToPassVector &RegsToPass,
2002 CCValAssign &VA, CCValAssign &NextVA,
2003 SDValue &StackPtr,
2004 SmallVectorImpl<SDValue> &MemOpChains,
2005 ISD::ArgFlagsTy Flags) const {
2006 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2007 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2008 unsigned id = Subtarget->isLittle() ? 0 : 1;
2009 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2011 if (NextVA.isRegLoc())
2012 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2013 else {
2014 assert(NextVA.isMemLoc());
2015 if (!StackPtr.getNode())
2016 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2017 getPointerTy(DAG.getDataLayout()));
2019 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2020 dl, DAG, NextVA,
2021 Flags));
2025 /// LowerCall - Lowering a call into a callseq_start <-
2026 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2027 /// nodes.
2028 SDValue
2029 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2030 SmallVectorImpl<SDValue> &InVals) const {
2031 SelectionDAG &DAG = CLI.DAG;
2032 SDLoc &dl = CLI.DL;
2033 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2034 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2035 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2036 SDValue Chain = CLI.Chain;
2037 SDValue Callee = CLI.Callee;
2038 bool &isTailCall = CLI.IsTailCall;
2039 CallingConv::ID CallConv = CLI.CallConv;
2040 bool doesNotRet = CLI.DoesNotReturn;
2041 bool isVarArg = CLI.IsVarArg;
2043 MachineFunction &MF = DAG.getMachineFunction();
2044 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2045 bool isThisReturn = false;
2046 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2047 bool PreferIndirect = false;
2049 // Disable tail calls if they're not supported.
2050 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2051 isTailCall = false;
2053 if (isa<GlobalAddressSDNode>(Callee)) {
2054 // If we're optimizing for minimum size and the function is called three or
2055 // more times in this block, we can improve codesize by calling indirectly
2056 // as BLXr has a 16-bit encoding.
2057 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2058 if (CLI.CS) {
2059 auto *BB = CLI.CS.getParent();
2060 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2061 count_if(GV->users(), [&BB](const User *U) {
2062 return isa<Instruction>(U) &&
2063 cast<Instruction>(U)->getParent() == BB;
2064 }) > 2;
2067 if (isTailCall) {
2068 // Check if it's really possible to do a tail call.
2069 isTailCall = IsEligibleForTailCallOptimization(
2070 Callee, CallConv, isVarArg, isStructRet,
2071 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2072 PreferIndirect);
2073 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2074 report_fatal_error("failed to perform tail call elimination on a call "
2075 "site marked musttail");
2076 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2077 // detected sibcalls.
2078 if (isTailCall)
2079 ++NumTailCalls;
2082 // Analyze operands of the call, assigning locations to each operand.
2083 SmallVector<CCValAssign, 16> ArgLocs;
2084 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2085 *DAG.getContext());
2086 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2088 // Get a count of how many bytes are to be pushed on the stack.
2089 unsigned NumBytes = CCInfo.getNextStackOffset();
2091 if (isTailCall) {
2092 // For tail calls, memory operands are available in our caller's stack.
2093 NumBytes = 0;
2094 } else {
2095 // Adjust the stack pointer for the new arguments...
2096 // These operations are automatically eliminated by the prolog/epilog pass
2097 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2100 SDValue StackPtr =
2101 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2103 RegsToPassVector RegsToPass;
2104 SmallVector<SDValue, 8> MemOpChains;
2106 // Walk the register/memloc assignments, inserting copies/loads. In the case
2107 // of tail call optimization, arguments are handled later.
2108 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2109 i != e;
2110 ++i, ++realArgIdx) {
2111 CCValAssign &VA = ArgLocs[i];
2112 SDValue Arg = OutVals[realArgIdx];
2113 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2114 bool isByVal = Flags.isByVal();
2116 // Promote the value if needed.
2117 switch (VA.getLocInfo()) {
2118 default: llvm_unreachable("Unknown loc info!");
2119 case CCValAssign::Full: break;
2120 case CCValAssign::SExt:
2121 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2122 break;
2123 case CCValAssign::ZExt:
2124 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2125 break;
2126 case CCValAssign::AExt:
2127 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2128 break;
2129 case CCValAssign::BCvt:
2130 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2131 break;
2134 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2135 if (VA.needsCustom()) {
2136 if (VA.getLocVT() == MVT::v2f64) {
2137 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2138 DAG.getConstant(0, dl, MVT::i32));
2139 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2140 DAG.getConstant(1, dl, MVT::i32));
2142 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2143 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2145 VA = ArgLocs[++i]; // skip ahead to next loc
2146 if (VA.isRegLoc()) {
2147 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2148 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2149 } else {
2150 assert(VA.isMemLoc());
2152 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2153 dl, DAG, VA, Flags));
2155 } else {
2156 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2157 StackPtr, MemOpChains, Flags);
2159 } else if (VA.isRegLoc()) {
2160 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2161 Outs[0].VT == MVT::i32) {
2162 assert(VA.getLocVT() == MVT::i32 &&
2163 "unexpected calling convention register assignment");
2164 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2165 "unexpected use of 'returned'");
2166 isThisReturn = true;
2168 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2169 } else if (isByVal) {
2170 assert(VA.isMemLoc());
2171 unsigned offset = 0;
2173 // True if this byval aggregate will be split between registers
2174 // and memory.
2175 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2176 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2178 if (CurByValIdx < ByValArgsCount) {
2180 unsigned RegBegin, RegEnd;
2181 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2183 EVT PtrVT =
2184 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2185 unsigned int i, j;
2186 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2187 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2188 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2189 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2190 MachinePointerInfo(),
2191 DAG.InferPtrAlignment(AddArg));
2192 MemOpChains.push_back(Load.getValue(1));
2193 RegsToPass.push_back(std::make_pair(j, Load));
2196 // If parameter size outsides register area, "offset" value
2197 // helps us to calculate stack slot for remained part properly.
2198 offset = RegEnd - RegBegin;
2200 CCInfo.nextInRegsParam();
2203 if (Flags.getByValSize() > 4*offset) {
2204 auto PtrVT = getPointerTy(DAG.getDataLayout());
2205 unsigned LocMemOffset = VA.getLocMemOffset();
2206 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2207 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2208 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2209 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2210 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2211 MVT::i32);
2212 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2213 MVT::i32);
2215 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2216 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2217 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2218 Ops));
2220 } else if (!isTailCall) {
2221 assert(VA.isMemLoc());
2223 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2224 dl, DAG, VA, Flags));
2228 if (!MemOpChains.empty())
2229 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2231 // Build a sequence of copy-to-reg nodes chained together with token chain
2232 // and flag operands which copy the outgoing args into the appropriate regs.
2233 SDValue InFlag;
2234 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2235 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2236 RegsToPass[i].second, InFlag);
2237 InFlag = Chain.getValue(1);
2240 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2241 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2242 // node so that legalize doesn't hack it.
2243 bool isDirect = false;
2245 const TargetMachine &TM = getTargetMachine();
2246 const Module *Mod = MF.getFunction().getParent();
2247 const GlobalValue *GV = nullptr;
2248 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2249 GV = G->getGlobal();
2250 bool isStub =
2251 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2253 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2254 bool isLocalARMFunc = false;
2255 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2256 auto PtrVt = getPointerTy(DAG.getDataLayout());
2258 if (Subtarget->genLongCalls()) {
2259 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2260 "long-calls codegen is not position independent!");
2261 // Handle a global address or an external symbol. If it's not one of
2262 // those, the target's already in a register, so we don't need to do
2263 // anything extra.
2264 if (isa<GlobalAddressSDNode>(Callee)) {
2265 // Create a constant pool entry for the callee address
2266 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2267 ARMConstantPoolValue *CPV =
2268 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2270 // Get the address of the callee into a register
2271 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2272 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2273 Callee = DAG.getLoad(
2274 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2275 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2276 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2277 const char *Sym = S->getSymbol();
2279 // Create a constant pool entry for the callee address
2280 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2281 ARMConstantPoolValue *CPV =
2282 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2283 ARMPCLabelIndex, 0);
2284 // Get the address of the callee into a register
2285 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2286 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2287 Callee = DAG.getLoad(
2288 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2289 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2291 } else if (isa<GlobalAddressSDNode>(Callee)) {
2292 if (!PreferIndirect) {
2293 isDirect = true;
2294 bool isDef = GV->isStrongDefinitionForLinker();
2296 // ARM call to a local ARM function is predicable.
2297 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2298 // tBX takes a register source operand.
2299 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2300 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2301 Callee = DAG.getNode(
2302 ARMISD::WrapperPIC, dl, PtrVt,
2303 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2304 Callee = DAG.getLoad(
2305 PtrVt, dl, DAG.getEntryNode(), Callee,
2306 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2307 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2308 MachineMemOperand::MOInvariant);
2309 } else if (Subtarget->isTargetCOFF()) {
2310 assert(Subtarget->isTargetWindows() &&
2311 "Windows is the only supported COFF target");
2312 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2313 ? ARMII::MO_DLLIMPORT
2314 : ARMII::MO_NO_FLAG;
2315 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2316 TargetFlags);
2317 if (GV->hasDLLImportStorageClass())
2318 Callee =
2319 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2320 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2321 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2322 } else {
2323 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2326 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2327 isDirect = true;
2328 // tBX takes a register source operand.
2329 const char *Sym = S->getSymbol();
2330 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2331 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2332 ARMConstantPoolValue *CPV =
2333 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2334 ARMPCLabelIndex, 4);
2335 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2336 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2337 Callee = DAG.getLoad(
2338 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2339 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2340 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2341 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2342 } else {
2343 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2347 // FIXME: handle tail calls differently.
2348 unsigned CallOpc;
2349 if (Subtarget->isThumb()) {
2350 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2351 CallOpc = ARMISD::CALL_NOLINK;
2352 else
2353 CallOpc = ARMISD::CALL;
2354 } else {
2355 if (!isDirect && !Subtarget->hasV5TOps())
2356 CallOpc = ARMISD::CALL_NOLINK;
2357 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2358 // Emit regular call when code size is the priority
2359 !Subtarget->hasMinSize())
2360 // "mov lr, pc; b _foo" to avoid confusing the RSP
2361 CallOpc = ARMISD::CALL_NOLINK;
2362 else
2363 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2366 std::vector<SDValue> Ops;
2367 Ops.push_back(Chain);
2368 Ops.push_back(Callee);
2370 // Add argument registers to the end of the list so that they are known live
2371 // into the call.
2372 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2373 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2374 RegsToPass[i].second.getValueType()));
2376 // Add a register mask operand representing the call-preserved registers.
2377 if (!isTailCall) {
2378 const uint32_t *Mask;
2379 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2380 if (isThisReturn) {
2381 // For 'this' returns, use the R0-preserving mask if applicable
2382 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2383 if (!Mask) {
2384 // Set isThisReturn to false if the calling convention is not one that
2385 // allows 'returned' to be modeled in this way, so LowerCallResult does
2386 // not try to pass 'this' straight through
2387 isThisReturn = false;
2388 Mask = ARI->getCallPreservedMask(MF, CallConv);
2390 } else
2391 Mask = ARI->getCallPreservedMask(MF, CallConv);
2393 assert(Mask && "Missing call preserved mask for calling convention");
2394 Ops.push_back(DAG.getRegisterMask(Mask));
2397 if (InFlag.getNode())
2398 Ops.push_back(InFlag);
2400 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2401 if (isTailCall) {
2402 MF.getFrameInfo().setHasTailCall();
2403 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2406 // Returns a chain and a flag for retval copy to use.
2407 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2408 InFlag = Chain.getValue(1);
2410 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2411 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2412 if (!Ins.empty())
2413 InFlag = Chain.getValue(1);
2415 // Handle result values, copying them out of physregs into vregs that we
2416 // return.
2417 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2418 InVals, isThisReturn,
2419 isThisReturn ? OutVals[0] : SDValue());
2422 /// HandleByVal - Every parameter *after* a byval parameter is passed
2423 /// on the stack. Remember the next parameter register to allocate,
2424 /// and then confiscate the rest of the parameter registers to insure
2425 /// this.
2426 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2427 unsigned Align) const {
2428 // Byval (as with any stack) slots are always at least 4 byte aligned.
2429 Align = std::max(Align, 4U);
2431 unsigned Reg = State->AllocateReg(GPRArgRegs);
2432 if (!Reg)
2433 return;
2435 unsigned AlignInRegs = Align / 4;
2436 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2437 for (unsigned i = 0; i < Waste; ++i)
2438 Reg = State->AllocateReg(GPRArgRegs);
2440 if (!Reg)
2441 return;
2443 unsigned Excess = 4 * (ARM::R4 - Reg);
2445 // Special case when NSAA != SP and parameter size greater than size of
2446 // all remained GPR regs. In that case we can't split parameter, we must
2447 // send it to stack. We also must set NCRN to R4, so waste all
2448 // remained registers.
2449 const unsigned NSAAOffset = State->getNextStackOffset();
2450 if (NSAAOffset != 0 && Size > Excess) {
2451 while (State->AllocateReg(GPRArgRegs))
2453 return;
2456 // First register for byval parameter is the first register that wasn't
2457 // allocated before this method call, so it would be "reg".
2458 // If parameter is small enough to be saved in range [reg, r4), then
2459 // the end (first after last) register would be reg + param-size-in-regs,
2460 // else parameter would be splitted between registers and stack,
2461 // end register would be r4 in this case.
2462 unsigned ByValRegBegin = Reg;
2463 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2464 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2465 // Note, first register is allocated in the beginning of function already,
2466 // allocate remained amount of registers we need.
2467 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2468 State->AllocateReg(GPRArgRegs);
2469 // A byval parameter that is split between registers and memory needs its
2470 // size truncated here.
2471 // In the case where the entire structure fits in registers, we set the
2472 // size in memory to zero.
2473 Size = std::max<int>(Size - Excess, 0);
2476 /// MatchingStackOffset - Return true if the given stack call argument is
2477 /// already available in the same position (relatively) of the caller's
2478 /// incoming argument stack.
2479 static
2480 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2481 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2482 const TargetInstrInfo *TII) {
2483 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2484 int FI = std::numeric_limits<int>::max();
2485 if (Arg.getOpcode() == ISD::CopyFromReg) {
2486 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2487 if (!Register::isVirtualRegister(VR))
2488 return false;
2489 MachineInstr *Def = MRI->getVRegDef(VR);
2490 if (!Def)
2491 return false;
2492 if (!Flags.isByVal()) {
2493 if (!TII->isLoadFromStackSlot(*Def, FI))
2494 return false;
2495 } else {
2496 return false;
2498 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2499 if (Flags.isByVal())
2500 // ByVal argument is passed in as a pointer but it's now being
2501 // dereferenced. e.g.
2502 // define @foo(%struct.X* %A) {
2503 // tail call @bar(%struct.X* byval %A)
2504 // }
2505 return false;
2506 SDValue Ptr = Ld->getBasePtr();
2507 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2508 if (!FINode)
2509 return false;
2510 FI = FINode->getIndex();
2511 } else
2512 return false;
2514 assert(FI != std::numeric_limits<int>::max());
2515 if (!MFI.isFixedObjectIndex(FI))
2516 return false;
2517 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2520 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2521 /// for tail call optimization. Targets which want to do tail call
2522 /// optimization should implement this function.
2523 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2524 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2525 bool isCalleeStructRet, bool isCallerStructRet,
2526 const SmallVectorImpl<ISD::OutputArg> &Outs,
2527 const SmallVectorImpl<SDValue> &OutVals,
2528 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2529 const bool isIndirect) const {
2530 MachineFunction &MF = DAG.getMachineFunction();
2531 const Function &CallerF = MF.getFunction();
2532 CallingConv::ID CallerCC = CallerF.getCallingConv();
2534 assert(Subtarget->supportsTailCall());
2536 // Indirect tail calls cannot be optimized for Thumb1 if the args
2537 // to the call take up r0-r3. The reason is that there are no legal registers
2538 // left to hold the pointer to the function to be called.
2539 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2540 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2541 return false;
2543 // Look for obvious safe cases to perform tail call optimization that do not
2544 // require ABI changes. This is what gcc calls sibcall.
2546 // Exception-handling functions need a special set of instructions to indicate
2547 // a return to the hardware. Tail-calling another function would probably
2548 // break this.
2549 if (CallerF.hasFnAttribute("interrupt"))
2550 return false;
2552 // Also avoid sibcall optimization if either caller or callee uses struct
2553 // return semantics.
2554 if (isCalleeStructRet || isCallerStructRet)
2555 return false;
2557 // Externally-defined functions with weak linkage should not be
2558 // tail-called on ARM when the OS does not support dynamic
2559 // pre-emption of symbols, as the AAELF spec requires normal calls
2560 // to undefined weak functions to be replaced with a NOP or jump to the
2561 // next instruction. The behaviour of branch instructions in this
2562 // situation (as used for tail calls) is implementation-defined, so we
2563 // cannot rely on the linker replacing the tail call with a return.
2564 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2565 const GlobalValue *GV = G->getGlobal();
2566 const Triple &TT = getTargetMachine().getTargetTriple();
2567 if (GV->hasExternalWeakLinkage() &&
2568 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2569 return false;
2572 // Check that the call results are passed in the same way.
2573 LLVMContext &C = *DAG.getContext();
2574 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2575 CCAssignFnForReturn(CalleeCC, isVarArg),
2576 CCAssignFnForReturn(CallerCC, isVarArg)))
2577 return false;
2578 // The callee has to preserve all registers the caller needs to preserve.
2579 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2580 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2581 if (CalleeCC != CallerCC) {
2582 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2583 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2584 return false;
2587 // If Caller's vararg or byval argument has been split between registers and
2588 // stack, do not perform tail call, since part of the argument is in caller's
2589 // local frame.
2590 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2591 if (AFI_Caller->getArgRegsSaveSize())
2592 return false;
2594 // If the callee takes no arguments then go on to check the results of the
2595 // call.
2596 if (!Outs.empty()) {
2597 // Check if stack adjustment is needed. For now, do not do this if any
2598 // argument is passed on the stack.
2599 SmallVector<CCValAssign, 16> ArgLocs;
2600 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2601 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2602 if (CCInfo.getNextStackOffset()) {
2603 // Check if the arguments are already laid out in the right way as
2604 // the caller's fixed stack objects.
2605 MachineFrameInfo &MFI = MF.getFrameInfo();
2606 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2607 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2608 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2609 i != e;
2610 ++i, ++realArgIdx) {
2611 CCValAssign &VA = ArgLocs[i];
2612 EVT RegVT = VA.getLocVT();
2613 SDValue Arg = OutVals[realArgIdx];
2614 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2615 if (VA.getLocInfo() == CCValAssign::Indirect)
2616 return false;
2617 if (VA.needsCustom()) {
2618 // f64 and vector types are split into multiple registers or
2619 // register/stack-slot combinations. The types will not match
2620 // the registers; give up on memory f64 refs until we figure
2621 // out what to do about this.
2622 if (!VA.isRegLoc())
2623 return false;
2624 if (!ArgLocs[++i].isRegLoc())
2625 return false;
2626 if (RegVT == MVT::v2f64) {
2627 if (!ArgLocs[++i].isRegLoc())
2628 return false;
2629 if (!ArgLocs[++i].isRegLoc())
2630 return false;
2632 } else if (!VA.isRegLoc()) {
2633 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2634 MFI, MRI, TII))
2635 return false;
2640 const MachineRegisterInfo &MRI = MF.getRegInfo();
2641 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2642 return false;
2645 return true;
2648 bool
2649 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2650 MachineFunction &MF, bool isVarArg,
2651 const SmallVectorImpl<ISD::OutputArg> &Outs,
2652 LLVMContext &Context) const {
2653 SmallVector<CCValAssign, 16> RVLocs;
2654 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2655 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2658 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2659 const SDLoc &DL, SelectionDAG &DAG) {
2660 const MachineFunction &MF = DAG.getMachineFunction();
2661 const Function &F = MF.getFunction();
2663 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2665 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2666 // version of the "preferred return address". These offsets affect the return
2667 // instruction if this is a return from PL1 without hypervisor extensions.
2668 // IRQ/FIQ: +4 "subs pc, lr, #4"
2669 // SWI: 0 "subs pc, lr, #0"
2670 // ABORT: +4 "subs pc, lr, #4"
2671 // UNDEF: +4/+2 "subs pc, lr, #0"
2672 // UNDEF varies depending on where the exception came from ARM or Thumb
2673 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2675 int64_t LROffset;
2676 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2677 IntKind == "ABORT")
2678 LROffset = 4;
2679 else if (IntKind == "SWI" || IntKind == "UNDEF")
2680 LROffset = 0;
2681 else
2682 report_fatal_error("Unsupported interrupt attribute. If present, value "
2683 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2685 RetOps.insert(RetOps.begin() + 1,
2686 DAG.getConstant(LROffset, DL, MVT::i32, false));
2688 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2691 SDValue
2692 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2693 bool isVarArg,
2694 const SmallVectorImpl<ISD::OutputArg> &Outs,
2695 const SmallVectorImpl<SDValue> &OutVals,
2696 const SDLoc &dl, SelectionDAG &DAG) const {
2697 // CCValAssign - represent the assignment of the return value to a location.
2698 SmallVector<CCValAssign, 16> RVLocs;
2700 // CCState - Info about the registers and stack slots.
2701 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2702 *DAG.getContext());
2704 // Analyze outgoing return values.
2705 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2707 SDValue Flag;
2708 SmallVector<SDValue, 4> RetOps;
2709 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2710 bool isLittleEndian = Subtarget->isLittle();
2712 MachineFunction &MF = DAG.getMachineFunction();
2713 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2714 AFI->setReturnRegsCount(RVLocs.size());
2716 // Copy the result values into the output registers.
2717 for (unsigned i = 0, realRVLocIdx = 0;
2718 i != RVLocs.size();
2719 ++i, ++realRVLocIdx) {
2720 CCValAssign &VA = RVLocs[i];
2721 assert(VA.isRegLoc() && "Can only return in registers!");
2723 SDValue Arg = OutVals[realRVLocIdx];
2724 bool ReturnF16 = false;
2726 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2727 // Half-precision return values can be returned like this:
2729 // t11 f16 = fadd ...
2730 // t12: i16 = bitcast t11
2731 // t13: i32 = zero_extend t12
2732 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2734 // to avoid code generation for bitcasts, we simply set Arg to the node
2735 // that produces the f16 value, t11 in this case.
2737 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2738 SDValue ZE = Arg.getOperand(0);
2739 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2740 SDValue BC = ZE.getOperand(0);
2741 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2742 Arg = BC.getOperand(0);
2743 ReturnF16 = true;
2749 switch (VA.getLocInfo()) {
2750 default: llvm_unreachable("Unknown loc info!");
2751 case CCValAssign::Full: break;
2752 case CCValAssign::BCvt:
2753 if (!ReturnF16)
2754 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2755 break;
2758 if (VA.needsCustom()) {
2759 if (VA.getLocVT() == MVT::v2f64) {
2760 // Extract the first half and return it in two registers.
2761 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2762 DAG.getConstant(0, dl, MVT::i32));
2763 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2764 DAG.getVTList(MVT::i32, MVT::i32), Half);
2766 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2767 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2768 Flag);
2769 Flag = Chain.getValue(1);
2770 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2771 VA = RVLocs[++i]; // skip ahead to next loc
2772 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2773 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2774 Flag);
2775 Flag = Chain.getValue(1);
2776 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2777 VA = RVLocs[++i]; // skip ahead to next loc
2779 // Extract the 2nd half and fall through to handle it as an f64 value.
2780 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2781 DAG.getConstant(1, dl, MVT::i32));
2783 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2784 // available.
2785 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2786 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2787 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2788 fmrrd.getValue(isLittleEndian ? 0 : 1),
2789 Flag);
2790 Flag = Chain.getValue(1);
2791 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2792 VA = RVLocs[++i]; // skip ahead to next loc
2793 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2794 fmrrd.getValue(isLittleEndian ? 1 : 0),
2795 Flag);
2796 } else
2797 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2799 // Guarantee that all emitted copies are
2800 // stuck together, avoiding something bad.
2801 Flag = Chain.getValue(1);
2802 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2803 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2805 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2806 const MCPhysReg *I =
2807 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2808 if (I) {
2809 for (; *I; ++I) {
2810 if (ARM::GPRRegClass.contains(*I))
2811 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2812 else if (ARM::DPRRegClass.contains(*I))
2813 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2814 else
2815 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2819 // Update chain and glue.
2820 RetOps[0] = Chain;
2821 if (Flag.getNode())
2822 RetOps.push_back(Flag);
2824 // CPUs which aren't M-class use a special sequence to return from
2825 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2826 // though we use "subs pc, lr, #N").
2828 // M-class CPUs actually use a normal return sequence with a special
2829 // (hardware-provided) value in LR, so the normal code path works.
2830 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2831 !Subtarget->isMClass()) {
2832 if (Subtarget->isThumb1Only())
2833 report_fatal_error("interrupt attribute is not supported in Thumb1");
2834 return LowerInterruptReturn(RetOps, dl, DAG);
2837 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2840 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2841 if (N->getNumValues() != 1)
2842 return false;
2843 if (!N->hasNUsesOfValue(1, 0))
2844 return false;
2846 SDValue TCChain = Chain;
2847 SDNode *Copy = *N->use_begin();
2848 if (Copy->getOpcode() == ISD::CopyToReg) {
2849 // If the copy has a glue operand, we conservatively assume it isn't safe to
2850 // perform a tail call.
2851 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2852 return false;
2853 TCChain = Copy->getOperand(0);
2854 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2855 SDNode *VMov = Copy;
2856 // f64 returned in a pair of GPRs.
2857 SmallPtrSet<SDNode*, 2> Copies;
2858 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2859 UI != UE; ++UI) {
2860 if (UI->getOpcode() != ISD::CopyToReg)
2861 return false;
2862 Copies.insert(*UI);
2864 if (Copies.size() > 2)
2865 return false;
2867 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2868 UI != UE; ++UI) {
2869 SDValue UseChain = UI->getOperand(0);
2870 if (Copies.count(UseChain.getNode()))
2871 // Second CopyToReg
2872 Copy = *UI;
2873 else {
2874 // We are at the top of this chain.
2875 // If the copy has a glue operand, we conservatively assume it
2876 // isn't safe to perform a tail call.
2877 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2878 return false;
2879 // First CopyToReg
2880 TCChain = UseChain;
2883 } else if (Copy->getOpcode() == ISD::BITCAST) {
2884 // f32 returned in a single GPR.
2885 if (!Copy->hasOneUse())
2886 return false;
2887 Copy = *Copy->use_begin();
2888 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2889 return false;
2890 // If the copy has a glue operand, we conservatively assume it isn't safe to
2891 // perform a tail call.
2892 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2893 return false;
2894 TCChain = Copy->getOperand(0);
2895 } else {
2896 return false;
2899 bool HasRet = false;
2900 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2901 UI != UE; ++UI) {
2902 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2903 UI->getOpcode() != ARMISD::INTRET_FLAG)
2904 return false;
2905 HasRet = true;
2908 if (!HasRet)
2909 return false;
2911 Chain = TCChain;
2912 return true;
2915 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2916 if (!Subtarget->supportsTailCall())
2917 return false;
2919 auto Attr =
2920 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2921 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2922 return false;
2924 return true;
2927 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2928 // and pass the lower and high parts through.
2929 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2930 SDLoc DL(Op);
2931 SDValue WriteValue = Op->getOperand(2);
2933 // This function is only supposed to be called for i64 type argument.
2934 assert(WriteValue.getValueType() == MVT::i64
2935 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2937 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2938 DAG.getConstant(0, DL, MVT::i32));
2939 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2940 DAG.getConstant(1, DL, MVT::i32));
2941 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2942 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2945 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2946 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2947 // one of the above mentioned nodes. It has to be wrapped because otherwise
2948 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2949 // be used to form addressing mode. These wrapped nodes will be selected
2950 // into MOVi.
2951 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2952 SelectionDAG &DAG) const {
2953 EVT PtrVT = Op.getValueType();
2954 // FIXME there is no actual debug info here
2955 SDLoc dl(Op);
2956 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2957 SDValue Res;
2959 // When generating execute-only code Constant Pools must be promoted to the
2960 // global data section. It's a bit ugly that we can't share them across basic
2961 // blocks, but this way we guarantee that execute-only behaves correct with
2962 // position-independent addressing modes.
2963 if (Subtarget->genExecuteOnly()) {
2964 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2965 auto T = const_cast<Type*>(CP->getType());
2966 auto C = const_cast<Constant*>(CP->getConstVal());
2967 auto M = const_cast<Module*>(DAG.getMachineFunction().
2968 getFunction().getParent());
2969 auto GV = new GlobalVariable(
2970 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2971 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2972 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2973 Twine(AFI->createPICLabelUId())
2975 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2976 dl, PtrVT);
2977 return LowerGlobalAddress(GA, DAG);
2980 if (CP->isMachineConstantPoolEntry())
2981 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2982 CP->getAlignment());
2983 else
2984 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2985 CP->getAlignment());
2986 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2989 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2990 return MachineJumpTableInfo::EK_Inline;
2993 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2994 SelectionDAG &DAG) const {
2995 MachineFunction &MF = DAG.getMachineFunction();
2996 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2997 unsigned ARMPCLabelIndex = 0;
2998 SDLoc DL(Op);
2999 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3000 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3001 SDValue CPAddr;
3002 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3003 if (!IsPositionIndependent) {
3004 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3005 } else {
3006 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3007 ARMPCLabelIndex = AFI->createPICLabelUId();
3008 ARMConstantPoolValue *CPV =
3009 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3010 ARMCP::CPBlockAddress, PCAdj);
3011 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3013 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3014 SDValue Result = DAG.getLoad(
3015 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3016 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3017 if (!IsPositionIndependent)
3018 return Result;
3019 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3020 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3023 /// Convert a TLS address reference into the correct sequence of loads
3024 /// and calls to compute the variable's address for Darwin, and return an
3025 /// SDValue containing the final node.
3027 /// Darwin only has one TLS scheme which must be capable of dealing with the
3028 /// fully general situation, in the worst case. This means:
3029 /// + "extern __thread" declaration.
3030 /// + Defined in a possibly unknown dynamic library.
3032 /// The general system is that each __thread variable has a [3 x i32] descriptor
3033 /// which contains information used by the runtime to calculate the address. The
3034 /// only part of this the compiler needs to know about is the first word, which
3035 /// contains a function pointer that must be called with the address of the
3036 /// entire descriptor in "r0".
3038 /// Since this descriptor may be in a different unit, in general access must
3039 /// proceed along the usual ARM rules. A common sequence to produce is:
3041 /// movw rT1, :lower16:_var$non_lazy_ptr
3042 /// movt rT1, :upper16:_var$non_lazy_ptr
3043 /// ldr r0, [rT1]
3044 /// ldr rT2, [r0]
3045 /// blx rT2
3046 /// [...address now in r0...]
3047 SDValue
3048 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3049 SelectionDAG &DAG) const {
3050 assert(Subtarget->isTargetDarwin() &&
3051 "This function expects a Darwin target");
3052 SDLoc DL(Op);
3054 // First step is to get the address of the actua global symbol. This is where
3055 // the TLS descriptor lives.
3056 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3058 // The first entry in the descriptor is a function pointer that we must call
3059 // to obtain the address of the variable.
3060 SDValue Chain = DAG.getEntryNode();
3061 SDValue FuncTLVGet = DAG.getLoad(
3062 MVT::i32, DL, Chain, DescAddr,
3063 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3064 /* Alignment = */ 4,
3065 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3066 MachineMemOperand::MOInvariant);
3067 Chain = FuncTLVGet.getValue(1);
3069 MachineFunction &F = DAG.getMachineFunction();
3070 MachineFrameInfo &MFI = F.getFrameInfo();
3071 MFI.setAdjustsStack(true);
3073 // TLS calls preserve all registers except those that absolutely must be
3074 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3075 // silly).
3076 auto TRI =
3077 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3078 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3079 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3081 // Finally, we can make the call. This is just a degenerate version of a
3082 // normal AArch64 call node: r0 takes the address of the descriptor, and
3083 // returns the address of the variable in this thread.
3084 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3085 Chain =
3086 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3087 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3088 DAG.getRegisterMask(Mask), Chain.getValue(1));
3089 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3092 SDValue
3093 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3094 SelectionDAG &DAG) const {
3095 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3097 SDValue Chain = DAG.getEntryNode();
3098 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3099 SDLoc DL(Op);
3101 // Load the current TEB (thread environment block)
3102 SDValue Ops[] = {Chain,
3103 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3104 DAG.getConstant(15, DL, MVT::i32),
3105 DAG.getConstant(0, DL, MVT::i32),
3106 DAG.getConstant(13, DL, MVT::i32),
3107 DAG.getConstant(0, DL, MVT::i32),
3108 DAG.getConstant(2, DL, MVT::i32)};
3109 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3110 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3112 SDValue TEB = CurrentTEB.getValue(0);
3113 Chain = CurrentTEB.getValue(1);
3115 // Load the ThreadLocalStoragePointer from the TEB
3116 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3117 SDValue TLSArray =
3118 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3119 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3121 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3122 // offset into the TLSArray.
3124 // Load the TLS index from the C runtime
3125 SDValue TLSIndex =
3126 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3127 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3128 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3130 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3131 DAG.getConstant(2, DL, MVT::i32));
3132 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3133 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3134 MachinePointerInfo());
3136 // Get the offset of the start of the .tls section (section base)
3137 const auto *GA = cast<GlobalAddressSDNode>(Op);
3138 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3139 SDValue Offset = DAG.getLoad(
3140 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3141 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3142 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3144 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3147 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3148 SDValue
3149 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3150 SelectionDAG &DAG) const {
3151 SDLoc dl(GA);
3152 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3153 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3154 MachineFunction &MF = DAG.getMachineFunction();
3155 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3156 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3157 ARMConstantPoolValue *CPV =
3158 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3159 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3160 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3161 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3162 Argument = DAG.getLoad(
3163 PtrVT, dl, DAG.getEntryNode(), Argument,
3164 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3165 SDValue Chain = Argument.getValue(1);
3167 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3168 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3170 // call __tls_get_addr.
3171 ArgListTy Args;
3172 ArgListEntry Entry;
3173 Entry.Node = Argument;
3174 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3175 Args.push_back(Entry);
3177 // FIXME: is there useful debug info available here?
3178 TargetLowering::CallLoweringInfo CLI(DAG);
3179 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3180 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3181 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3183 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3184 return CallResult.first;
3187 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3188 // "local exec" model.
3189 SDValue
3190 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3191 SelectionDAG &DAG,
3192 TLSModel::Model model) const {
3193 const GlobalValue *GV = GA->getGlobal();
3194 SDLoc dl(GA);
3195 SDValue Offset;
3196 SDValue Chain = DAG.getEntryNode();
3197 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3198 // Get the Thread Pointer
3199 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3201 if (model == TLSModel::InitialExec) {
3202 MachineFunction &MF = DAG.getMachineFunction();
3203 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3204 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3205 // Initial exec model.
3206 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3207 ARMConstantPoolValue *CPV =
3208 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3209 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3210 true);
3211 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3212 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3213 Offset = DAG.getLoad(
3214 PtrVT, dl, Chain, Offset,
3215 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3216 Chain = Offset.getValue(1);
3218 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3219 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3221 Offset = DAG.getLoad(
3222 PtrVT, dl, Chain, Offset,
3223 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3224 } else {
3225 // local exec model
3226 assert(model == TLSModel::LocalExec);
3227 ARMConstantPoolValue *CPV =
3228 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3229 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3230 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3231 Offset = DAG.getLoad(
3232 PtrVT, dl, Chain, Offset,
3233 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3236 // The address of the thread local variable is the add of the thread
3237 // pointer with the offset of the variable.
3238 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3241 SDValue
3242 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3243 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3244 if (DAG.getTarget().useEmulatedTLS())
3245 return LowerToTLSEmulatedModel(GA, DAG);
3247 if (Subtarget->isTargetDarwin())
3248 return LowerGlobalTLSAddressDarwin(Op, DAG);
3250 if (Subtarget->isTargetWindows())
3251 return LowerGlobalTLSAddressWindows(Op, DAG);
3253 // TODO: implement the "local dynamic" model
3254 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3255 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3257 switch (model) {
3258 case TLSModel::GeneralDynamic:
3259 case TLSModel::LocalDynamic:
3260 return LowerToTLSGeneralDynamicModel(GA, DAG);
3261 case TLSModel::InitialExec:
3262 case TLSModel::LocalExec:
3263 return LowerToTLSExecModels(GA, DAG, model);
3265 llvm_unreachable("bogus TLS model");
3268 /// Return true if all users of V are within function F, looking through
3269 /// ConstantExprs.
3270 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3271 SmallVector<const User*,4> Worklist;
3272 for (auto *U : V->users())
3273 Worklist.push_back(U);
3274 while (!Worklist.empty()) {
3275 auto *U = Worklist.pop_back_val();
3276 if (isa<ConstantExpr>(U)) {
3277 for (auto *UU : U->users())
3278 Worklist.push_back(UU);
3279 continue;
3282 auto *I = dyn_cast<Instruction>(U);
3283 if (!I || I->getParent()->getParent() != F)
3284 return false;
3286 return true;
3289 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3290 const GlobalValue *GV, SelectionDAG &DAG,
3291 EVT PtrVT, const SDLoc &dl) {
3292 // If we're creating a pool entry for a constant global with unnamed address,
3293 // and the global is small enough, we can emit it inline into the constant pool
3294 // to save ourselves an indirection.
3296 // This is a win if the constant is only used in one function (so it doesn't
3297 // need to be duplicated) or duplicating the constant wouldn't increase code
3298 // size (implying the constant is no larger than 4 bytes).
3299 const Function &F = DAG.getMachineFunction().getFunction();
3301 // We rely on this decision to inline being idemopotent and unrelated to the
3302 // use-site. We know that if we inline a variable at one use site, we'll
3303 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3304 // doesn't know about this optimization, so bail out if it's enabled else
3305 // we could decide to inline here (and thus never emit the GV) but require
3306 // the GV from fast-isel generated code.
3307 if (!EnableConstpoolPromotion ||
3308 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3309 return SDValue();
3311 auto *GVar = dyn_cast<GlobalVariable>(GV);
3312 if (!GVar || !GVar->hasInitializer() ||
3313 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3314 !GVar->hasLocalLinkage())
3315 return SDValue();
3317 // If we inline a value that contains relocations, we move the relocations
3318 // from .data to .text. This is not allowed in position-independent code.
3319 auto *Init = GVar->getInitializer();
3320 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3321 Init->needsRelocation())
3322 return SDValue();
3324 // The constant islands pass can only really deal with alignment requests
3325 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3326 // any type wanting greater alignment requirements than 4 bytes. We also
3327 // can only promote constants that are multiples of 4 bytes in size or
3328 // are paddable to a multiple of 4. Currently we only try and pad constants
3329 // that are strings for simplicity.
3330 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3331 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3332 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3333 unsigned RequiredPadding = 4 - (Size % 4);
3334 bool PaddingPossible =
3335 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3336 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3337 Size == 0)
3338 return SDValue();
3340 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3341 MachineFunction &MF = DAG.getMachineFunction();
3342 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3344 // We can't bloat the constant pool too much, else the ConstantIslands pass
3345 // may fail to converge. If we haven't promoted this global yet (it may have
3346 // multiple uses), and promoting it would increase the constant pool size (Sz
3347 // > 4), ensure we have space to do so up to MaxTotal.
3348 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3349 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3350 ConstpoolPromotionMaxTotal)
3351 return SDValue();
3353 // This is only valid if all users are in a single function; we can't clone
3354 // the constant in general. The LLVM IR unnamed_addr allows merging
3355 // constants, but not cloning them.
3357 // We could potentially allow cloning if we could prove all uses of the
3358 // constant in the current function don't care about the address, like
3359 // printf format strings. But that isn't implemented for now.
3360 if (!allUsersAreInFunction(GVar, &F))
3361 return SDValue();
3363 // We're going to inline this global. Pad it out if needed.
3364 if (RequiredPadding != 4) {
3365 StringRef S = CDAInit->getAsString();
3367 SmallVector<uint8_t,16> V(S.size());
3368 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3369 while (RequiredPadding--)
3370 V.push_back(0);
3371 Init = ConstantDataArray::get(*DAG.getContext(), V);
3374 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3375 SDValue CPAddr =
3376 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3377 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3378 AFI->markGlobalAsPromotedToConstantPool(GVar);
3379 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3380 PaddedSize - 4);
3382 ++NumConstpoolPromoted;
3383 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3386 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3387 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3388 if (!(GV = GA->getBaseObject()))
3389 return false;
3390 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3391 return V->isConstant();
3392 return isa<Function>(GV);
3395 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3396 SelectionDAG &DAG) const {
3397 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3398 default: llvm_unreachable("unknown object format");
3399 case Triple::COFF:
3400 return LowerGlobalAddressWindows(Op, DAG);
3401 case Triple::ELF:
3402 return LowerGlobalAddressELF(Op, DAG);
3403 case Triple::MachO:
3404 return LowerGlobalAddressDarwin(Op, DAG);
3408 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3409 SelectionDAG &DAG) const {
3410 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3411 SDLoc dl(Op);
3412 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3413 const TargetMachine &TM = getTargetMachine();
3414 bool IsRO = isReadOnly(GV);
3416 // promoteToConstantPool only if not generating XO text section
3417 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3418 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3419 return V;
3421 if (isPositionIndependent()) {
3422 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3423 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3424 UseGOT_PREL ? ARMII::MO_GOT : 0);
3425 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3426 if (UseGOT_PREL)
3427 Result =
3428 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3429 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3430 return Result;
3431 } else if (Subtarget->isROPI() && IsRO) {
3432 // PC-relative.
3433 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3434 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3435 return Result;
3436 } else if (Subtarget->isRWPI() && !IsRO) {
3437 // SB-relative.
3438 SDValue RelAddr;
3439 if (Subtarget->useMovt()) {
3440 ++NumMovwMovt;
3441 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3442 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3443 } else { // use literal pool for address constant
3444 ARMConstantPoolValue *CPV =
3445 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3446 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3447 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3448 RelAddr = DAG.getLoad(
3449 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3450 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3452 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3453 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3454 return Result;
3457 // If we have T2 ops, we can materialize the address directly via movt/movw
3458 // pair. This is always cheaper.
3459 if (Subtarget->useMovt()) {
3460 ++NumMovwMovt;
3461 // FIXME: Once remat is capable of dealing with instructions with register
3462 // operands, expand this into two nodes.
3463 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3464 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3465 } else {
3466 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3467 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3468 return DAG.getLoad(
3469 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3470 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3474 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3475 SelectionDAG &DAG) const {
3476 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3477 "ROPI/RWPI not currently supported for Darwin");
3478 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3479 SDLoc dl(Op);
3480 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3482 if (Subtarget->useMovt())
3483 ++NumMovwMovt;
3485 // FIXME: Once remat is capable of dealing with instructions with register
3486 // operands, expand this into multiple nodes
3487 unsigned Wrapper =
3488 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3490 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3491 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3493 if (Subtarget->isGVIndirectSymbol(GV))
3494 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3495 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3496 return Result;
3499 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3500 SelectionDAG &DAG) const {
3501 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3502 assert(Subtarget->useMovt() &&
3503 "Windows on ARM expects to use movw/movt");
3504 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3505 "ROPI/RWPI not currently supported for Windows");
3507 const TargetMachine &TM = getTargetMachine();
3508 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3509 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3510 if (GV->hasDLLImportStorageClass())
3511 TargetFlags = ARMII::MO_DLLIMPORT;
3512 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3513 TargetFlags = ARMII::MO_COFFSTUB;
3514 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3515 SDValue Result;
3516 SDLoc DL(Op);
3518 ++NumMovwMovt;
3520 // FIXME: Once remat is capable of dealing with instructions with register
3521 // operands, expand this into two nodes.
3522 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3523 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3524 TargetFlags));
3525 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3526 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3527 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3528 return Result;
3531 SDValue
3532 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3533 SDLoc dl(Op);
3534 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3535 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3536 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3537 Op.getOperand(1), Val);
3540 SDValue
3541 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3542 SDLoc dl(Op);
3543 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3544 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3547 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3548 SelectionDAG &DAG) const {
3549 SDLoc dl(Op);
3550 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3551 Op.getOperand(0));
3554 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3555 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3556 unsigned IntNo =
3557 cast<ConstantSDNode>(
3558 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3559 ->getZExtValue();
3560 switch (IntNo) {
3561 default:
3562 return SDValue(); // Don't custom lower most intrinsics.
3563 case Intrinsic::arm_gnu_eabi_mcount: {
3564 MachineFunction &MF = DAG.getMachineFunction();
3565 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3566 SDLoc dl(Op);
3567 SDValue Chain = Op.getOperand(0);
3568 // call "\01__gnu_mcount_nc"
3569 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3570 const uint32_t *Mask =
3571 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3572 assert(Mask && "Missing call preserved mask for calling convention");
3573 // Mark LR an implicit live-in.
3574 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3575 SDValue ReturnAddress =
3576 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3577 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3578 SDValue Callee =
3579 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3580 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3581 if (Subtarget->isThumb())
3582 return SDValue(
3583 DAG.getMachineNode(
3584 ARM::tBL_PUSHLR, dl, ResultTys,
3585 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3586 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3588 return SDValue(
3589 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3590 {ReturnAddress, Callee, RegisterMask, Chain}),
3596 SDValue
3597 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3598 const ARMSubtarget *Subtarget) const {
3599 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3600 SDLoc dl(Op);
3601 switch (IntNo) {
3602 default: return SDValue(); // Don't custom lower most intrinsics.
3603 case Intrinsic::thread_pointer: {
3604 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3605 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3607 case Intrinsic::eh_sjlj_lsda: {
3608 MachineFunction &MF = DAG.getMachineFunction();
3609 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3610 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3611 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3612 SDValue CPAddr;
3613 bool IsPositionIndependent = isPositionIndependent();
3614 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3615 ARMConstantPoolValue *CPV =
3616 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3617 ARMCP::CPLSDA, PCAdj);
3618 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3619 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3620 SDValue Result = DAG.getLoad(
3621 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3622 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3624 if (IsPositionIndependent) {
3625 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3626 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3628 return Result;
3630 case Intrinsic::arm_neon_vabs:
3631 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3632 Op.getOperand(1));
3633 case Intrinsic::arm_neon_vmulls:
3634 case Intrinsic::arm_neon_vmullu: {
3635 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3636 ? ARMISD::VMULLs : ARMISD::VMULLu;
3637 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3638 Op.getOperand(1), Op.getOperand(2));
3640 case Intrinsic::arm_neon_vminnm:
3641 case Intrinsic::arm_neon_vmaxnm: {
3642 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3643 ? ISD::FMINNUM : ISD::FMAXNUM;
3644 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3645 Op.getOperand(1), Op.getOperand(2));
3647 case Intrinsic::arm_neon_vminu:
3648 case Intrinsic::arm_neon_vmaxu: {
3649 if (Op.getValueType().isFloatingPoint())
3650 return SDValue();
3651 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3652 ? ISD::UMIN : ISD::UMAX;
3653 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3654 Op.getOperand(1), Op.getOperand(2));
3656 case Intrinsic::arm_neon_vmins:
3657 case Intrinsic::arm_neon_vmaxs: {
3658 // v{min,max}s is overloaded between signed integers and floats.
3659 if (!Op.getValueType().isFloatingPoint()) {
3660 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3661 ? ISD::SMIN : ISD::SMAX;
3662 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3663 Op.getOperand(1), Op.getOperand(2));
3665 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3666 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3667 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3668 Op.getOperand(1), Op.getOperand(2));
3670 case Intrinsic::arm_neon_vtbl1:
3671 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3672 Op.getOperand(1), Op.getOperand(2));
3673 case Intrinsic::arm_neon_vtbl2:
3674 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3675 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3679 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3680 const ARMSubtarget *Subtarget) {
3681 SDLoc dl(Op);
3682 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3683 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3684 if (SSID == SyncScope::SingleThread)
3685 return Op;
3687 if (!Subtarget->hasDataBarrier()) {
3688 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3689 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3690 // here.
3691 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3692 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3693 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3694 DAG.getConstant(0, dl, MVT::i32));
3697 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3698 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3699 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3700 if (Subtarget->isMClass()) {
3701 // Only a full system barrier exists in the M-class architectures.
3702 Domain = ARM_MB::SY;
3703 } else if (Subtarget->preferISHSTBarriers() &&
3704 Ord == AtomicOrdering::Release) {
3705 // Swift happens to implement ISHST barriers in a way that's compatible with
3706 // Release semantics but weaker than ISH so we'd be fools not to use
3707 // it. Beware: other processors probably don't!
3708 Domain = ARM_MB::ISHST;
3711 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3712 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3713 DAG.getConstant(Domain, dl, MVT::i32));
3716 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3717 const ARMSubtarget *Subtarget) {
3718 // ARM pre v5TE and Thumb1 does not have preload instructions.
3719 if (!(Subtarget->isThumb2() ||
3720 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3721 // Just preserve the chain.
3722 return Op.getOperand(0);
3724 SDLoc dl(Op);
3725 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3726 if (!isRead &&
3727 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3728 // ARMv7 with MP extension has PLDW.
3729 return Op.getOperand(0);
3731 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3732 if (Subtarget->isThumb()) {
3733 // Invert the bits.
3734 isRead = ~isRead & 1;
3735 isData = ~isData & 1;
3738 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3739 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3740 DAG.getConstant(isData, dl, MVT::i32));
3743 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3744 MachineFunction &MF = DAG.getMachineFunction();
3745 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3747 // vastart just stores the address of the VarArgsFrameIndex slot into the
3748 // memory location argument.
3749 SDLoc dl(Op);
3750 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3751 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3752 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3753 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3754 MachinePointerInfo(SV));
3757 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3758 CCValAssign &NextVA,
3759 SDValue &Root,
3760 SelectionDAG &DAG,
3761 const SDLoc &dl) const {
3762 MachineFunction &MF = DAG.getMachineFunction();
3763 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3765 const TargetRegisterClass *RC;
3766 if (AFI->isThumb1OnlyFunction())
3767 RC = &ARM::tGPRRegClass;
3768 else
3769 RC = &ARM::GPRRegClass;
3771 // Transform the arguments stored in physical registers into virtual ones.
3772 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3773 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3775 SDValue ArgValue2;
3776 if (NextVA.isMemLoc()) {
3777 MachineFrameInfo &MFI = MF.getFrameInfo();
3778 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3780 // Create load node to retrieve arguments from the stack.
3781 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3782 ArgValue2 = DAG.getLoad(
3783 MVT::i32, dl, Root, FIN,
3784 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3785 } else {
3786 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3787 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3789 if (!Subtarget->isLittle())
3790 std::swap (ArgValue, ArgValue2);
3791 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3794 // The remaining GPRs hold either the beginning of variable-argument
3795 // data, or the beginning of an aggregate passed by value (usually
3796 // byval). Either way, we allocate stack slots adjacent to the data
3797 // provided by our caller, and store the unallocated registers there.
3798 // If this is a variadic function, the va_list pointer will begin with
3799 // these values; otherwise, this reassembles a (byval) structure that
3800 // was split between registers and memory.
3801 // Return: The frame index registers were stored into.
3802 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3803 const SDLoc &dl, SDValue &Chain,
3804 const Value *OrigArg,
3805 unsigned InRegsParamRecordIdx,
3806 int ArgOffset, unsigned ArgSize) const {
3807 // Currently, two use-cases possible:
3808 // Case #1. Non-var-args function, and we meet first byval parameter.
3809 // Setup first unallocated register as first byval register;
3810 // eat all remained registers
3811 // (these two actions are performed by HandleByVal method).
3812 // Then, here, we initialize stack frame with
3813 // "store-reg" instructions.
3814 // Case #2. Var-args function, that doesn't contain byval parameters.
3815 // The same: eat all remained unallocated registers,
3816 // initialize stack frame.
3818 MachineFunction &MF = DAG.getMachineFunction();
3819 MachineFrameInfo &MFI = MF.getFrameInfo();
3820 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3821 unsigned RBegin, REnd;
3822 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3823 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3824 } else {
3825 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3826 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3827 REnd = ARM::R4;
3830 if (REnd != RBegin)
3831 ArgOffset = -4 * (ARM::R4 - RBegin);
3833 auto PtrVT = getPointerTy(DAG.getDataLayout());
3834 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3835 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3837 SmallVector<SDValue, 4> MemOps;
3838 const TargetRegisterClass *RC =
3839 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3841 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3842 unsigned VReg = MF.addLiveIn(Reg, RC);
3843 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3844 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3845 MachinePointerInfo(OrigArg, 4 * i));
3846 MemOps.push_back(Store);
3847 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3850 if (!MemOps.empty())
3851 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3852 return FrameIndex;
3855 // Setup stack frame, the va_list pointer will start from.
3856 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3857 const SDLoc &dl, SDValue &Chain,
3858 unsigned ArgOffset,
3859 unsigned TotalArgRegsSaveSize,
3860 bool ForceMutable) const {
3861 MachineFunction &MF = DAG.getMachineFunction();
3862 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3864 // Try to store any remaining integer argument regs
3865 // to their spots on the stack so that they may be loaded by dereferencing
3866 // the result of va_next.
3867 // If there is no regs to be stored, just point address after last
3868 // argument passed via stack.
3869 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3870 CCInfo.getInRegsParamsCount(),
3871 CCInfo.getNextStackOffset(),
3872 std::max(4U, TotalArgRegsSaveSize));
3873 AFI->setVarArgsFrameIndex(FrameIndex);
3876 SDValue ARMTargetLowering::LowerFormalArguments(
3877 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3878 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3879 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3880 MachineFunction &MF = DAG.getMachineFunction();
3881 MachineFrameInfo &MFI = MF.getFrameInfo();
3883 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3885 // Assign locations to all of the incoming arguments.
3886 SmallVector<CCValAssign, 16> ArgLocs;
3887 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3888 *DAG.getContext());
3889 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3891 SmallVector<SDValue, 16> ArgValues;
3892 SDValue ArgValue;
3893 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3894 unsigned CurArgIdx = 0;
3896 // Initially ArgRegsSaveSize is zero.
3897 // Then we increase this value each time we meet byval parameter.
3898 // We also increase this value in case of varargs function.
3899 AFI->setArgRegsSaveSize(0);
3901 // Calculate the amount of stack space that we need to allocate to store
3902 // byval and variadic arguments that are passed in registers.
3903 // We need to know this before we allocate the first byval or variadic
3904 // argument, as they will be allocated a stack slot below the CFA (Canonical
3905 // Frame Address, the stack pointer at entry to the function).
3906 unsigned ArgRegBegin = ARM::R4;
3907 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3908 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3909 break;
3911 CCValAssign &VA = ArgLocs[i];
3912 unsigned Index = VA.getValNo();
3913 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3914 if (!Flags.isByVal())
3915 continue;
3917 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3918 unsigned RBegin, REnd;
3919 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3920 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3922 CCInfo.nextInRegsParam();
3924 CCInfo.rewindByValRegsInfo();
3926 int lastInsIndex = -1;
3927 if (isVarArg && MFI.hasVAStart()) {
3928 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3929 if (RegIdx != array_lengthof(GPRArgRegs))
3930 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3933 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3934 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3935 auto PtrVT = getPointerTy(DAG.getDataLayout());
3937 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3938 CCValAssign &VA = ArgLocs[i];
3939 if (Ins[VA.getValNo()].isOrigArg()) {
3940 std::advance(CurOrigArg,
3941 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3942 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3944 // Arguments stored in registers.
3945 if (VA.isRegLoc()) {
3946 EVT RegVT = VA.getLocVT();
3948 if (VA.needsCustom()) {
3949 // f64 and vector types are split up into multiple registers or
3950 // combinations of registers and stack slots.
3951 if (VA.getLocVT() == MVT::v2f64) {
3952 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3953 Chain, DAG, dl);
3954 VA = ArgLocs[++i]; // skip ahead to next loc
3955 SDValue ArgValue2;
3956 if (VA.isMemLoc()) {
3957 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3958 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3959 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3960 MachinePointerInfo::getFixedStack(
3961 DAG.getMachineFunction(), FI));
3962 } else {
3963 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3964 Chain, DAG, dl);
3966 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3967 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3968 ArgValue, ArgValue1,
3969 DAG.getIntPtrConstant(0, dl));
3970 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3971 ArgValue, ArgValue2,
3972 DAG.getIntPtrConstant(1, dl));
3973 } else
3974 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3975 } else {
3976 const TargetRegisterClass *RC;
3979 if (RegVT == MVT::f16)
3980 RC = &ARM::HPRRegClass;
3981 else if (RegVT == MVT::f32)
3982 RC = &ARM::SPRRegClass;
3983 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3984 RC = &ARM::DPRRegClass;
3985 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3986 RC = &ARM::QPRRegClass;
3987 else if (RegVT == MVT::i32)
3988 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3989 : &ARM::GPRRegClass;
3990 else
3991 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3993 // Transform the arguments in physical registers into virtual ones.
3994 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3995 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3997 // If this value is passed in r0 and has the returned attribute (e.g.
3998 // C++ 'structors), record this fact for later use.
3999 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4000 AFI->setPreservesR0();
4004 // If this is an 8 or 16-bit value, it is really passed promoted
4005 // to 32 bits. Insert an assert[sz]ext to capture this, then
4006 // truncate to the right size.
4007 switch (VA.getLocInfo()) {
4008 default: llvm_unreachable("Unknown loc info!");
4009 case CCValAssign::Full: break;
4010 case CCValAssign::BCvt:
4011 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4012 break;
4013 case CCValAssign::SExt:
4014 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4015 DAG.getValueType(VA.getValVT()));
4016 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4017 break;
4018 case CCValAssign::ZExt:
4019 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4020 DAG.getValueType(VA.getValVT()));
4021 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4022 break;
4025 InVals.push_back(ArgValue);
4026 } else { // VA.isRegLoc()
4027 // sanity check
4028 assert(VA.isMemLoc());
4029 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4031 int index = VA.getValNo();
4033 // Some Ins[] entries become multiple ArgLoc[] entries.
4034 // Process them only once.
4035 if (index != lastInsIndex)
4037 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4038 // FIXME: For now, all byval parameter objects are marked mutable.
4039 // This can be changed with more analysis.
4040 // In case of tail call optimization mark all arguments mutable.
4041 // Since they could be overwritten by lowering of arguments in case of
4042 // a tail call.
4043 if (Flags.isByVal()) {
4044 assert(Ins[index].isOrigArg() &&
4045 "Byval arguments cannot be implicit");
4046 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4048 int FrameIndex = StoreByValRegs(
4049 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4050 VA.getLocMemOffset(), Flags.getByValSize());
4051 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4052 CCInfo.nextInRegsParam();
4053 } else {
4054 unsigned FIOffset = VA.getLocMemOffset();
4055 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4056 FIOffset, true);
4058 // Create load nodes to retrieve arguments from the stack.
4059 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4060 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4061 MachinePointerInfo::getFixedStack(
4062 DAG.getMachineFunction(), FI)));
4064 lastInsIndex = index;
4069 // varargs
4070 if (isVarArg && MFI.hasVAStart())
4071 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4072 CCInfo.getNextStackOffset(),
4073 TotalArgRegsSaveSize);
4075 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4077 return Chain;
4080 /// isFloatingPointZero - Return true if this is +0.0.
4081 static bool isFloatingPointZero(SDValue Op) {
4082 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4083 return CFP->getValueAPF().isPosZero();
4084 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4085 // Maybe this has already been legalized into the constant pool?
4086 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4087 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4088 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4089 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4090 return CFP->getValueAPF().isPosZero();
4092 } else if (Op->getOpcode() == ISD::BITCAST &&
4093 Op->getValueType(0) == MVT::f64) {
4094 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4095 // created by LowerConstantFP().
4096 SDValue BitcastOp = Op->getOperand(0);
4097 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4098 isNullConstant(BitcastOp->getOperand(0)))
4099 return true;
4101 return false;
4104 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4105 /// the given operands.
4106 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4107 SDValue &ARMcc, SelectionDAG &DAG,
4108 const SDLoc &dl) const {
4109 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4110 unsigned C = RHSC->getZExtValue();
4111 if (!isLegalICmpImmediate((int32_t)C)) {
4112 // Constant does not fit, try adjusting it by one.
4113 switch (CC) {
4114 default: break;
4115 case ISD::SETLT:
4116 case ISD::SETGE:
4117 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4118 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4119 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4121 break;
4122 case ISD::SETULT:
4123 case ISD::SETUGE:
4124 if (C != 0 && isLegalICmpImmediate(C-1)) {
4125 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4126 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4128 break;
4129 case ISD::SETLE:
4130 case ISD::SETGT:
4131 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4132 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4133 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4135 break;
4136 case ISD::SETULE:
4137 case ISD::SETUGT:
4138 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4139 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4140 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4142 break;
4145 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4146 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4147 // In ARM and Thumb-2, the compare instructions can shift their second
4148 // operand.
4149 CC = ISD::getSetCCSwappedOperands(CC);
4150 std::swap(LHS, RHS);
4153 // Thumb1 has very limited immediate modes, so turning an "and" into a
4154 // shift can save multiple instructions.
4156 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4157 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4158 // own. If it's the operand to an unsigned comparison with an immediate,
4159 // we can eliminate one of the shifts: we transform
4160 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4162 // We avoid transforming cases which aren't profitable due to encoding
4163 // details:
4165 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4166 // would not; in that case, we're essentially trading one immediate load for
4167 // another.
4168 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4169 // 3. C2 is zero; we have other code for this special case.
4171 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4172 // instruction, since the AND is always one instruction anyway, but we could
4173 // use narrow instructions in some cases.
4174 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4175 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4176 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4177 !isSignedIntSetCC(CC)) {
4178 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4179 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4180 uint64_t RHSV = RHSC->getZExtValue();
4181 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4182 unsigned ShiftBits = countLeadingZeros(Mask);
4183 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4184 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4185 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4186 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4191 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4192 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4193 // way a cmp would.
4194 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4195 // some tweaks to the heuristics for the previous and->shift transform.
4196 // FIXME: Optimize cases where the LHS isn't a shift.
4197 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4198 isa<ConstantSDNode>(RHS) &&
4199 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4200 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4201 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4202 unsigned ShiftAmt =
4203 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4204 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4205 DAG.getVTList(MVT::i32, MVT::i32),
4206 LHS.getOperand(0),
4207 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4208 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4209 Shift.getValue(1), SDValue());
4210 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4211 return Chain.getValue(1);
4214 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4216 // If the RHS is a constant zero then the V (overflow) flag will never be
4217 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4218 // simpler for other passes (like the peephole optimiser) to deal with.
4219 if (isNullConstant(RHS)) {
4220 switch (CondCode) {
4221 default: break;
4222 case ARMCC::GE:
4223 CondCode = ARMCC::PL;
4224 break;
4225 case ARMCC::LT:
4226 CondCode = ARMCC::MI;
4227 break;
4231 ARMISD::NodeType CompareType;
4232 switch (CondCode) {
4233 default:
4234 CompareType = ARMISD::CMP;
4235 break;
4236 case ARMCC::EQ:
4237 case ARMCC::NE:
4238 // Uses only Z Flag
4239 CompareType = ARMISD::CMPZ;
4240 break;
4242 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4243 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4246 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4247 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4248 SelectionDAG &DAG, const SDLoc &dl,
4249 bool InvalidOnQNaN) const {
4250 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4251 SDValue Cmp;
4252 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4253 if (!isFloatingPointZero(RHS))
4254 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4255 else
4256 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4257 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4260 /// duplicateCmp - Glue values can have only one use, so this function
4261 /// duplicates a comparison node.
4262 SDValue
4263 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4264 unsigned Opc = Cmp.getOpcode();
4265 SDLoc DL(Cmp);
4266 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4267 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4269 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4270 Cmp = Cmp.getOperand(0);
4271 Opc = Cmp.getOpcode();
4272 if (Opc == ARMISD::CMPFP)
4273 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4274 Cmp.getOperand(1), Cmp.getOperand(2));
4275 else {
4276 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4277 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4278 Cmp.getOperand(1));
4280 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4283 // This function returns three things: the arithmetic computation itself
4284 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4285 // comparison and the condition code define the case in which the arithmetic
4286 // computation *does not* overflow.
4287 std::pair<SDValue, SDValue>
4288 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4289 SDValue &ARMcc) const {
4290 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4292 SDValue Value, OverflowCmp;
4293 SDValue LHS = Op.getOperand(0);
4294 SDValue RHS = Op.getOperand(1);
4295 SDLoc dl(Op);
4297 // FIXME: We are currently always generating CMPs because we don't support
4298 // generating CMN through the backend. This is not as good as the natural
4299 // CMP case because it causes a register dependency and cannot be folded
4300 // later.
4302 switch (Op.getOpcode()) {
4303 default:
4304 llvm_unreachable("Unknown overflow instruction!");
4305 case ISD::SADDO:
4306 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4307 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4308 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4309 break;
4310 case ISD::UADDO:
4311 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4312 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4313 // We do not use it in the USUBO case as Value may not be used.
4314 Value = DAG.getNode(ARMISD::ADDC, dl,
4315 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4316 .getValue(0);
4317 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4318 break;
4319 case ISD::SSUBO:
4320 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4321 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4322 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4323 break;
4324 case ISD::USUBO:
4325 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4326 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4327 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4328 break;
4329 case ISD::UMULO:
4330 // We generate a UMUL_LOHI and then check if the high word is 0.
4331 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4332 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4333 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4334 LHS, RHS);
4335 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4336 DAG.getConstant(0, dl, MVT::i32));
4337 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4338 break;
4339 case ISD::SMULO:
4340 // We generate a SMUL_LOHI and then check if all the bits of the high word
4341 // are the same as the sign bit of the low word.
4342 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4343 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4344 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4345 LHS, RHS);
4346 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4347 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4348 Value.getValue(0),
4349 DAG.getConstant(31, dl, MVT::i32)));
4350 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4351 break;
4352 } // switch (...)
4354 return std::make_pair(Value, OverflowCmp);
4357 SDValue
4358 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4359 // Let legalize expand this if it isn't a legal type yet.
4360 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4361 return SDValue();
4363 SDValue Value, OverflowCmp;
4364 SDValue ARMcc;
4365 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4366 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4367 SDLoc dl(Op);
4368 // We use 0 and 1 as false and true values.
4369 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4370 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4371 EVT VT = Op.getValueType();
4373 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4374 ARMcc, CCR, OverflowCmp);
4376 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4377 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4380 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4381 SelectionDAG &DAG) {
4382 SDLoc DL(BoolCarry);
4383 EVT CarryVT = BoolCarry.getValueType();
4385 // This converts the boolean value carry into the carry flag by doing
4386 // ARMISD::SUBC Carry, 1
4387 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4388 DAG.getVTList(CarryVT, MVT::i32),
4389 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4390 return Carry.getValue(1);
4393 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4394 SelectionDAG &DAG) {
4395 SDLoc DL(Flags);
4397 // Now convert the carry flag into a boolean carry. We do this
4398 // using ARMISD:ADDE 0, 0, Carry
4399 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4400 DAG.getConstant(0, DL, MVT::i32),
4401 DAG.getConstant(0, DL, MVT::i32), Flags);
4404 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4405 SelectionDAG &DAG) const {
4406 // Let legalize expand this if it isn't a legal type yet.
4407 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4408 return SDValue();
4410 SDValue LHS = Op.getOperand(0);
4411 SDValue RHS = Op.getOperand(1);
4412 SDLoc dl(Op);
4414 EVT VT = Op.getValueType();
4415 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4416 SDValue Value;
4417 SDValue Overflow;
4418 switch (Op.getOpcode()) {
4419 default:
4420 llvm_unreachable("Unknown overflow instruction!");
4421 case ISD::UADDO:
4422 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4423 // Convert the carry flag into a boolean value.
4424 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4425 break;
4426 case ISD::USUBO: {
4427 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4428 // Convert the carry flag into a boolean value.
4429 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4430 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4431 // value. So compute 1 - C.
4432 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4433 DAG.getConstant(1, dl, MVT::i32), Overflow);
4434 break;
4438 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4441 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4442 SDValue Cond = Op.getOperand(0);
4443 SDValue SelectTrue = Op.getOperand(1);
4444 SDValue SelectFalse = Op.getOperand(2);
4445 SDLoc dl(Op);
4446 unsigned Opc = Cond.getOpcode();
4448 if (Cond.getResNo() == 1 &&
4449 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4450 Opc == ISD::USUBO)) {
4451 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4452 return SDValue();
4454 SDValue Value, OverflowCmp;
4455 SDValue ARMcc;
4456 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4457 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4458 EVT VT = Op.getValueType();
4460 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4461 OverflowCmp, DAG);
4464 // Convert:
4466 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4467 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4469 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4470 const ConstantSDNode *CMOVTrue =
4471 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4472 const ConstantSDNode *CMOVFalse =
4473 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4475 if (CMOVTrue && CMOVFalse) {
4476 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4477 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4479 SDValue True;
4480 SDValue False;
4481 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4482 True = SelectTrue;
4483 False = SelectFalse;
4484 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4485 True = SelectFalse;
4486 False = SelectTrue;
4489 if (True.getNode() && False.getNode()) {
4490 EVT VT = Op.getValueType();
4491 SDValue ARMcc = Cond.getOperand(2);
4492 SDValue CCR = Cond.getOperand(3);
4493 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4494 assert(True.getValueType() == VT);
4495 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4500 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4501 // undefined bits before doing a full-word comparison with zero.
4502 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4503 DAG.getConstant(1, dl, Cond.getValueType()));
4505 return DAG.getSelectCC(dl, Cond,
4506 DAG.getConstant(0, dl, Cond.getValueType()),
4507 SelectTrue, SelectFalse, ISD::SETNE);
4510 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4511 bool &swpCmpOps, bool &swpVselOps) {
4512 // Start by selecting the GE condition code for opcodes that return true for
4513 // 'equality'
4514 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4515 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4516 CondCode = ARMCC::GE;
4518 // and GT for opcodes that return false for 'equality'.
4519 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4520 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4521 CondCode = ARMCC::GT;
4523 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4524 // to swap the compare operands.
4525 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4526 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4527 swpCmpOps = true;
4529 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4530 // If we have an unordered opcode, we need to swap the operands to the VSEL
4531 // instruction (effectively negating the condition).
4533 // This also has the effect of swapping which one of 'less' or 'greater'
4534 // returns true, so we also swap the compare operands. It also switches
4535 // whether we return true for 'equality', so we compensate by picking the
4536 // opposite condition code to our original choice.
4537 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4538 CC == ISD::SETUGT) {
4539 swpCmpOps = !swpCmpOps;
4540 swpVselOps = !swpVselOps;
4541 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4544 // 'ordered' is 'anything but unordered', so use the VS condition code and
4545 // swap the VSEL operands.
4546 if (CC == ISD::SETO) {
4547 CondCode = ARMCC::VS;
4548 swpVselOps = true;
4551 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4552 // code and swap the VSEL operands. Also do this if we don't care about the
4553 // unordered case.
4554 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4555 CondCode = ARMCC::EQ;
4556 swpVselOps = true;
4560 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4561 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4562 SDValue Cmp, SelectionDAG &DAG) const {
4563 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4564 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4565 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4566 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4567 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4569 SDValue TrueLow = TrueVal.getValue(0);
4570 SDValue TrueHigh = TrueVal.getValue(1);
4571 SDValue FalseLow = FalseVal.getValue(0);
4572 SDValue FalseHigh = FalseVal.getValue(1);
4574 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4575 ARMcc, CCR, Cmp);
4576 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4577 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4579 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4580 } else {
4581 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4582 Cmp);
4586 static bool isGTorGE(ISD::CondCode CC) {
4587 return CC == ISD::SETGT || CC == ISD::SETGE;
4590 static bool isLTorLE(ISD::CondCode CC) {
4591 return CC == ISD::SETLT || CC == ISD::SETLE;
4594 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4595 // All of these conditions (and their <= and >= counterparts) will do:
4596 // x < k ? k : x
4597 // x > k ? x : k
4598 // k < x ? x : k
4599 // k > x ? k : x
4600 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4601 const SDValue TrueVal, const SDValue FalseVal,
4602 const ISD::CondCode CC, const SDValue K) {
4603 return (isGTorGE(CC) &&
4604 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4605 (isLTorLE(CC) &&
4606 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4609 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4610 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4611 const SDValue TrueVal, const SDValue FalseVal,
4612 const ISD::CondCode CC, const SDValue K) {
4613 return (isGTorGE(CC) &&
4614 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4615 (isLTorLE(CC) &&
4616 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4619 // Check if two chained conditionals could be converted into SSAT or USAT.
4621 // SSAT can replace a set of two conditional selectors that bound a number to an
4622 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4624 // x < -k ? -k : (x > k ? k : x)
4625 // x < -k ? -k : (x < k ? x : k)
4626 // x > -k ? (x > k ? k : x) : -k
4627 // x < k ? (x < -k ? -k : x) : k
4628 // etc.
4630 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4631 // a power of 2.
4633 // It returns true if the conversion can be done, false otherwise.
4634 // Additionally, the variable is returned in parameter V, the constant in K and
4635 // usat is set to true if the conditional represents an unsigned saturation
4636 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4637 uint64_t &K, bool &usat) {
4638 SDValue LHS1 = Op.getOperand(0);
4639 SDValue RHS1 = Op.getOperand(1);
4640 SDValue TrueVal1 = Op.getOperand(2);
4641 SDValue FalseVal1 = Op.getOperand(3);
4642 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4644 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4645 if (Op2.getOpcode() != ISD::SELECT_CC)
4646 return false;
4648 SDValue LHS2 = Op2.getOperand(0);
4649 SDValue RHS2 = Op2.getOperand(1);
4650 SDValue TrueVal2 = Op2.getOperand(2);
4651 SDValue FalseVal2 = Op2.getOperand(3);
4652 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4654 // Find out which are the constants and which are the variables
4655 // in each conditional
4656 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4657 ? &RHS1
4658 : nullptr;
4659 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4660 ? &RHS2
4661 : nullptr;
4662 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4663 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4664 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4665 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4667 // We must detect cases where the original operations worked with 16- or
4668 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4669 // must work with sign-extended values but the select operations return
4670 // the original non-extended value.
4671 SDValue V2TmpReg = V2Tmp;
4672 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4673 V2TmpReg = V2Tmp->getOperand(0);
4675 // Check that the registers and the constants have the correct values
4676 // in both conditionals
4677 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4678 V2TmpReg != V2)
4679 return false;
4681 // Figure out which conditional is saturating the lower/upper bound.
4682 const SDValue *LowerCheckOp =
4683 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4684 ? &Op
4685 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4686 ? &Op2
4687 : nullptr;
4688 const SDValue *UpperCheckOp =
4689 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4690 ? &Op
4691 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4692 ? &Op2
4693 : nullptr;
4695 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4696 return false;
4698 // Check that the constant in the lower-bound check is
4699 // the opposite of the constant in the upper-bound check
4700 // in 1's complement.
4701 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4702 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4703 int64_t PosVal = std::max(Val1, Val2);
4704 int64_t NegVal = std::min(Val1, Val2);
4706 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4707 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4708 isPowerOf2_64(PosVal + 1)) {
4710 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4711 if (Val1 == ~Val2)
4712 usat = false;
4713 else if (NegVal == 0)
4714 usat = true;
4715 else
4716 return false;
4718 V = V2;
4719 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4721 return true;
4724 return false;
4727 // Check if a condition of the type x < k ? k : x can be converted into a
4728 // bit operation instead of conditional moves.
4729 // Currently this is allowed given:
4730 // - The conditions and values match up
4731 // - k is 0 or -1 (all ones)
4732 // This function will not check the last condition, thats up to the caller
4733 // It returns true if the transformation can be made, and in such case
4734 // returns x in V, and k in SatK.
4735 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4736 SDValue &SatK)
4738 SDValue LHS = Op.getOperand(0);
4739 SDValue RHS = Op.getOperand(1);
4740 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4741 SDValue TrueVal = Op.getOperand(2);
4742 SDValue FalseVal = Op.getOperand(3);
4744 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4745 ? &RHS
4746 : nullptr;
4748 // No constant operation in comparison, early out
4749 if (!K)
4750 return false;
4752 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4753 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4754 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4756 // If the constant on left and right side, or variable on left and right,
4757 // does not match, early out
4758 if (*K != KTmp || V != VTmp)
4759 return false;
4761 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4762 SatK = *K;
4763 return true;
4766 return false;
4769 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4770 if (VT == MVT::f32)
4771 return !Subtarget->hasVFP2Base();
4772 if (VT == MVT::f64)
4773 return !Subtarget->hasFP64();
4774 if (VT == MVT::f16)
4775 return !Subtarget->hasFullFP16();
4776 return false;
4779 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4780 EVT VT = Op.getValueType();
4781 SDLoc dl(Op);
4783 // Try to convert two saturating conditional selects into a single SSAT
4784 SDValue SatValue;
4785 uint64_t SatConstant;
4786 bool SatUSat;
4787 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4788 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4789 if (SatUSat)
4790 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4791 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4792 else
4793 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4794 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4797 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4798 // into more efficient bit operations, which is possible when k is 0 or -1
4799 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4800 // single instructions. On Thumb the shift and the bit operation will be two
4801 // instructions.
4802 // Only allow this transformation on full-width (32-bit) operations
4803 SDValue LowerSatConstant;
4804 if (VT == MVT::i32 &&
4805 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4806 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4807 DAG.getConstant(31, dl, VT));
4808 if (isNullConstant(LowerSatConstant)) {
4809 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4810 DAG.getAllOnesConstant(dl, VT));
4811 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4812 } else if (isAllOnesConstant(LowerSatConstant))
4813 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4816 SDValue LHS = Op.getOperand(0);
4817 SDValue RHS = Op.getOperand(1);
4818 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4819 SDValue TrueVal = Op.getOperand(2);
4820 SDValue FalseVal = Op.getOperand(3);
4821 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4822 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4824 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4825 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4826 unsigned TVal = CTVal->getZExtValue();
4827 unsigned FVal = CFVal->getZExtValue();
4828 unsigned Opcode = 0;
4830 if (TVal == ~FVal) {
4831 Opcode = ARMISD::CSINV;
4832 } else if (TVal == ~FVal + 1) {
4833 Opcode = ARMISD::CSNEG;
4834 } else if (TVal + 1 == FVal) {
4835 Opcode = ARMISD::CSINC;
4836 } else if (TVal == FVal + 1) {
4837 Opcode = ARMISD::CSINC;
4838 std::swap(TrueVal, FalseVal);
4839 std::swap(TVal, FVal);
4840 CC = ISD::getSetCCInverse(CC, true);
4843 if (Opcode) {
4844 // If one of the constants is cheaper than another, materialise the
4845 // cheaper one and let the csel generate the other.
4846 if (Opcode != ARMISD::CSINC &&
4847 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4848 std::swap(TrueVal, FalseVal);
4849 std::swap(TVal, FVal);
4850 CC = ISD::getSetCCInverse(CC, true);
4853 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4854 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4855 // -(-a) == a, but (a+1)+1 != a).
4856 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4857 std::swap(TrueVal, FalseVal);
4858 std::swap(TVal, FVal);
4859 CC = ISD::getSetCCInverse(CC, true);
4861 if (TVal == 0)
4862 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4864 // Drops F's value because we can get it by inverting/negating TVal.
4865 FalseVal = TrueVal;
4867 SDValue ARMcc;
4868 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4869 EVT VT = TrueVal.getValueType();
4870 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4874 if (isUnsupportedFloatingType(LHS.getValueType())) {
4875 DAG.getTargetLoweringInfo().softenSetCCOperands(
4876 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4878 // If softenSetCCOperands only returned one value, we should compare it to
4879 // zero.
4880 if (!RHS.getNode()) {
4881 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4882 CC = ISD::SETNE;
4886 if (LHS.getValueType() == MVT::i32) {
4887 // Try to generate VSEL on ARMv8.
4888 // The VSEL instruction can't use all the usual ARM condition
4889 // codes: it only has two bits to select the condition code, so it's
4890 // constrained to use only GE, GT, VS and EQ.
4892 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4893 // swap the operands of the previous compare instruction (effectively
4894 // inverting the compare condition, swapping 'less' and 'greater') and
4895 // sometimes need to swap the operands to the VSEL (which inverts the
4896 // condition in the sense of firing whenever the previous condition didn't)
4897 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4898 TrueVal.getValueType() == MVT::f32 ||
4899 TrueVal.getValueType() == MVT::f64)) {
4900 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4901 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4902 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4903 CC = ISD::getSetCCInverse(CC, true);
4904 std::swap(TrueVal, FalseVal);
4908 SDValue ARMcc;
4909 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4910 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4911 // Choose GE over PL, which vsel does now support
4912 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4913 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4914 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4917 ARMCC::CondCodes CondCode, CondCode2;
4918 bool InvalidOnQNaN;
4919 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4921 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4922 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4923 // must use VSEL (limited condition codes), due to not having conditional f16
4924 // moves.
4925 if (Subtarget->hasFPARMv8Base() &&
4926 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4927 (TrueVal.getValueType() == MVT::f16 ||
4928 TrueVal.getValueType() == MVT::f32 ||
4929 TrueVal.getValueType() == MVT::f64)) {
4930 bool swpCmpOps = false;
4931 bool swpVselOps = false;
4932 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4934 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4935 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4936 if (swpCmpOps)
4937 std::swap(LHS, RHS);
4938 if (swpVselOps)
4939 std::swap(TrueVal, FalseVal);
4943 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4944 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4945 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4946 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4947 if (CondCode2 != ARMCC::AL) {
4948 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4949 // FIXME: Needs another CMP because flag can have but one use.
4950 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4951 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4953 return Result;
4956 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4957 /// to morph to an integer compare sequence.
4958 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4959 const ARMSubtarget *Subtarget) {
4960 SDNode *N = Op.getNode();
4961 if (!N->hasOneUse())
4962 // Otherwise it requires moving the value from fp to integer registers.
4963 return false;
4964 if (!N->getNumValues())
4965 return false;
4966 EVT VT = Op.getValueType();
4967 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4968 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4969 // vmrs are very slow, e.g. cortex-a8.
4970 return false;
4972 if (isFloatingPointZero(Op)) {
4973 SeenZero = true;
4974 return true;
4976 return ISD::isNormalLoad(N);
4979 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4980 if (isFloatingPointZero(Op))
4981 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4983 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4984 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4985 Ld->getPointerInfo(), Ld->getAlignment(),
4986 Ld->getMemOperand()->getFlags());
4988 llvm_unreachable("Unknown VFP cmp argument!");
4991 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4992 SDValue &RetVal1, SDValue &RetVal2) {
4993 SDLoc dl(Op);
4995 if (isFloatingPointZero(Op)) {
4996 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4997 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4998 return;
5001 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5002 SDValue Ptr = Ld->getBasePtr();
5003 RetVal1 =
5004 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5005 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5007 EVT PtrType = Ptr.getValueType();
5008 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5009 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5010 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5011 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5012 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5013 Ld->getMemOperand()->getFlags());
5014 return;
5017 llvm_unreachable("Unknown VFP cmp argument!");
5020 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5021 /// f32 and even f64 comparisons to integer ones.
5022 SDValue
5023 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5024 SDValue Chain = Op.getOperand(0);
5025 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5026 SDValue LHS = Op.getOperand(2);
5027 SDValue RHS = Op.getOperand(3);
5028 SDValue Dest = Op.getOperand(4);
5029 SDLoc dl(Op);
5031 bool LHSSeenZero = false;
5032 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5033 bool RHSSeenZero = false;
5034 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5035 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5036 // If unsafe fp math optimization is enabled and there are no other uses of
5037 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5038 // to an integer comparison.
5039 if (CC == ISD::SETOEQ)
5040 CC = ISD::SETEQ;
5041 else if (CC == ISD::SETUNE)
5042 CC = ISD::SETNE;
5044 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5045 SDValue ARMcc;
5046 if (LHS.getValueType() == MVT::f32) {
5047 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5048 bitcastf32Toi32(LHS, DAG), Mask);
5049 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5050 bitcastf32Toi32(RHS, DAG), Mask);
5051 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5052 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5053 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5054 Chain, Dest, ARMcc, CCR, Cmp);
5057 SDValue LHS1, LHS2;
5058 SDValue RHS1, RHS2;
5059 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5060 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5061 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5062 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5063 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5064 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5065 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5066 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5067 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5070 return SDValue();
5073 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5074 SDValue Chain = Op.getOperand(0);
5075 SDValue Cond = Op.getOperand(1);
5076 SDValue Dest = Op.getOperand(2);
5077 SDLoc dl(Op);
5079 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5080 // instruction.
5081 unsigned Opc = Cond.getOpcode();
5082 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5083 !Subtarget->isThumb1Only();
5084 if (Cond.getResNo() == 1 &&
5085 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5086 Opc == ISD::USUBO || OptimizeMul)) {
5087 // Only lower legal XALUO ops.
5088 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5089 return SDValue();
5091 // The actual operation with overflow check.
5092 SDValue Value, OverflowCmp;
5093 SDValue ARMcc;
5094 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5096 // Reverse the condition code.
5097 ARMCC::CondCodes CondCode =
5098 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5099 CondCode = ARMCC::getOppositeCondition(CondCode);
5100 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5101 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5103 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5104 OverflowCmp);
5107 return SDValue();
5110 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5111 SDValue Chain = Op.getOperand(0);
5112 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5113 SDValue LHS = Op.getOperand(2);
5114 SDValue RHS = Op.getOperand(3);
5115 SDValue Dest = Op.getOperand(4);
5116 SDLoc dl(Op);
5118 if (isUnsupportedFloatingType(LHS.getValueType())) {
5119 DAG.getTargetLoweringInfo().softenSetCCOperands(
5120 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5122 // If softenSetCCOperands only returned one value, we should compare it to
5123 // zero.
5124 if (!RHS.getNode()) {
5125 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5126 CC = ISD::SETNE;
5130 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5131 // instruction.
5132 unsigned Opc = LHS.getOpcode();
5133 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5134 !Subtarget->isThumb1Only();
5135 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5136 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5137 Opc == ISD::USUBO || OptimizeMul) &&
5138 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5139 // Only lower legal XALUO ops.
5140 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5141 return SDValue();
5143 // The actual operation with overflow check.
5144 SDValue Value, OverflowCmp;
5145 SDValue ARMcc;
5146 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5148 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5149 // Reverse the condition code.
5150 ARMCC::CondCodes CondCode =
5151 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5152 CondCode = ARMCC::getOppositeCondition(CondCode);
5153 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5155 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5157 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5158 OverflowCmp);
5161 if (LHS.getValueType() == MVT::i32) {
5162 SDValue ARMcc;
5163 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5164 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5165 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5166 Chain, Dest, ARMcc, CCR, Cmp);
5169 if (getTargetMachine().Options.UnsafeFPMath &&
5170 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5171 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5172 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5173 return Result;
5176 ARMCC::CondCodes CondCode, CondCode2;
5177 bool InvalidOnQNaN;
5178 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5180 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5181 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5182 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5183 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5184 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5185 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5186 if (CondCode2 != ARMCC::AL) {
5187 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5188 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5189 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5191 return Res;
5194 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5195 SDValue Chain = Op.getOperand(0);
5196 SDValue Table = Op.getOperand(1);
5197 SDValue Index = Op.getOperand(2);
5198 SDLoc dl(Op);
5200 EVT PTy = getPointerTy(DAG.getDataLayout());
5201 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5202 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5203 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5204 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5205 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5206 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5207 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5208 // which does another jump to the destination. This also makes it easier
5209 // to translate it to TBB / TBH later (Thumb2 only).
5210 // FIXME: This might not work if the function is extremely large.
5211 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5212 Addr, Op.getOperand(2), JTI);
5214 if (isPositionIndependent() || Subtarget->isROPI()) {
5215 Addr =
5216 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5217 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5218 Chain = Addr.getValue(1);
5219 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5220 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5221 } else {
5222 Addr =
5223 DAG.getLoad(PTy, dl, Chain, Addr,
5224 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5225 Chain = Addr.getValue(1);
5226 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5230 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5231 EVT VT = Op.getValueType();
5232 SDLoc dl(Op);
5234 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5235 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5236 return Op;
5237 return DAG.UnrollVectorOp(Op.getNode());
5240 const bool HasFullFP16 =
5241 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5243 EVT NewTy;
5244 const EVT OpTy = Op.getOperand(0).getValueType();
5245 if (OpTy == MVT::v4f32)
5246 NewTy = MVT::v4i32;
5247 else if (OpTy == MVT::v4f16 && HasFullFP16)
5248 NewTy = MVT::v4i16;
5249 else if (OpTy == MVT::v8f16 && HasFullFP16)
5250 NewTy = MVT::v8i16;
5251 else
5252 llvm_unreachable("Invalid type for custom lowering!");
5254 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5255 return DAG.UnrollVectorOp(Op.getNode());
5257 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5258 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5261 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5262 EVT VT = Op.getValueType();
5263 if (VT.isVector())
5264 return LowerVectorFP_TO_INT(Op, DAG);
5265 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5266 RTLIB::Libcall LC;
5267 if (Op.getOpcode() == ISD::FP_TO_SINT)
5268 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5269 Op.getValueType());
5270 else
5271 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5272 Op.getValueType());
5273 MakeLibCallOptions CallOptions;
5274 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5275 CallOptions, SDLoc(Op)).first;
5278 return Op;
5281 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5282 EVT VT = Op.getValueType();
5283 SDLoc dl(Op);
5285 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5286 if (VT.getVectorElementType() == MVT::f32)
5287 return Op;
5288 return DAG.UnrollVectorOp(Op.getNode());
5291 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5292 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5293 "Invalid type for custom lowering!");
5295 const bool HasFullFP16 =
5296 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5298 EVT DestVecType;
5299 if (VT == MVT::v4f32)
5300 DestVecType = MVT::v4i32;
5301 else if (VT == MVT::v4f16 && HasFullFP16)
5302 DestVecType = MVT::v4i16;
5303 else if (VT == MVT::v8f16 && HasFullFP16)
5304 DestVecType = MVT::v8i16;
5305 else
5306 return DAG.UnrollVectorOp(Op.getNode());
5308 unsigned CastOpc;
5309 unsigned Opc;
5310 switch (Op.getOpcode()) {
5311 default: llvm_unreachable("Invalid opcode!");
5312 case ISD::SINT_TO_FP:
5313 CastOpc = ISD::SIGN_EXTEND;
5314 Opc = ISD::SINT_TO_FP;
5315 break;
5316 case ISD::UINT_TO_FP:
5317 CastOpc = ISD::ZERO_EXTEND;
5318 Opc = ISD::UINT_TO_FP;
5319 break;
5322 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5323 return DAG.getNode(Opc, dl, VT, Op);
5326 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5327 EVT VT = Op.getValueType();
5328 if (VT.isVector())
5329 return LowerVectorINT_TO_FP(Op, DAG);
5330 if (isUnsupportedFloatingType(VT)) {
5331 RTLIB::Libcall LC;
5332 if (Op.getOpcode() == ISD::SINT_TO_FP)
5333 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5334 Op.getValueType());
5335 else
5336 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5337 Op.getValueType());
5338 MakeLibCallOptions CallOptions;
5339 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5340 CallOptions, SDLoc(Op)).first;
5343 return Op;
5346 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5347 // Implement fcopysign with a fabs and a conditional fneg.
5348 SDValue Tmp0 = Op.getOperand(0);
5349 SDValue Tmp1 = Op.getOperand(1);
5350 SDLoc dl(Op);
5351 EVT VT = Op.getValueType();
5352 EVT SrcVT = Tmp1.getValueType();
5353 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5354 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5355 bool UseNEON = !InGPR && Subtarget->hasNEON();
5357 if (UseNEON) {
5358 // Use VBSL to copy the sign bit.
5359 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5360 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5361 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5362 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5363 if (VT == MVT::f64)
5364 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5365 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5366 DAG.getConstant(32, dl, MVT::i32));
5367 else /*if (VT == MVT::f32)*/
5368 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5369 if (SrcVT == MVT::f32) {
5370 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5371 if (VT == MVT::f64)
5372 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5373 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5374 DAG.getConstant(32, dl, MVT::i32));
5375 } else if (VT == MVT::f32)
5376 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5377 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5378 DAG.getConstant(32, dl, MVT::i32));
5379 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5380 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5382 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5383 dl, MVT::i32);
5384 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5385 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5386 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5388 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5389 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5390 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5391 if (VT == MVT::f32) {
5392 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5393 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5394 DAG.getConstant(0, dl, MVT::i32));
5395 } else {
5396 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5399 return Res;
5402 // Bitcast operand 1 to i32.
5403 if (SrcVT == MVT::f64)
5404 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5405 Tmp1).getValue(1);
5406 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5408 // Or in the signbit with integer operations.
5409 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5410 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5411 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5412 if (VT == MVT::f32) {
5413 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5414 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5415 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5416 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5419 // f64: Or the high part with signbit and then combine two parts.
5420 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5421 Tmp0);
5422 SDValue Lo = Tmp0.getValue(0);
5423 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5424 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5425 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5428 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5429 MachineFunction &MF = DAG.getMachineFunction();
5430 MachineFrameInfo &MFI = MF.getFrameInfo();
5431 MFI.setReturnAddressIsTaken(true);
5433 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5434 return SDValue();
5436 EVT VT = Op.getValueType();
5437 SDLoc dl(Op);
5438 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5439 if (Depth) {
5440 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5441 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5442 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5443 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5444 MachinePointerInfo());
5447 // Return LR, which contains the return address. Mark it an implicit live-in.
5448 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5449 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5452 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5453 const ARMBaseRegisterInfo &ARI =
5454 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5455 MachineFunction &MF = DAG.getMachineFunction();
5456 MachineFrameInfo &MFI = MF.getFrameInfo();
5457 MFI.setFrameAddressIsTaken(true);
5459 EVT VT = Op.getValueType();
5460 SDLoc dl(Op); // FIXME probably not meaningful
5461 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5462 Register FrameReg = ARI.getFrameRegister(MF);
5463 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5464 while (Depth--)
5465 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5466 MachinePointerInfo());
5467 return FrameAddr;
5470 // FIXME? Maybe this could be a TableGen attribute on some registers and
5471 // this table could be generated automatically from RegInfo.
5472 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5473 SelectionDAG &DAG) const {
5474 unsigned Reg = StringSwitch<unsigned>(RegName)
5475 .Case("sp", ARM::SP)
5476 .Default(0);
5477 if (Reg)
5478 return Reg;
5479 report_fatal_error(Twine("Invalid register name \""
5480 + StringRef(RegName) + "\"."));
5483 // Result is 64 bit value so split into two 32 bit values and return as a
5484 // pair of values.
5485 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5486 SelectionDAG &DAG) {
5487 SDLoc DL(N);
5489 // This function is only supposed to be called for i64 type destination.
5490 assert(N->getValueType(0) == MVT::i64
5491 && "ExpandREAD_REGISTER called for non-i64 type result.");
5493 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5494 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5495 N->getOperand(0),
5496 N->getOperand(1));
5498 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5499 Read.getValue(1)));
5500 Results.push_back(Read.getOperand(0));
5503 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5504 /// When \p DstVT, the destination type of \p BC, is on the vector
5505 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5506 /// it might be possible to combine them, such that everything stays on the
5507 /// vector register bank.
5508 /// \p return The node that would replace \p BT, if the combine
5509 /// is possible.
5510 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5511 SelectionDAG &DAG) {
5512 SDValue Op = BC->getOperand(0);
5513 EVT DstVT = BC->getValueType(0);
5515 // The only vector instruction that can produce a scalar (remember,
5516 // since the bitcast was about to be turned into VMOVDRR, the source
5517 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5518 // Moreover, we can do this combine only if there is one use.
5519 // Finally, if the destination type is not a vector, there is not
5520 // much point on forcing everything on the vector bank.
5521 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5522 !Op.hasOneUse())
5523 return SDValue();
5525 // If the index is not constant, we will introduce an additional
5526 // multiply that will stick.
5527 // Give up in that case.
5528 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5529 if (!Index)
5530 return SDValue();
5531 unsigned DstNumElt = DstVT.getVectorNumElements();
5533 // Compute the new index.
5534 const APInt &APIntIndex = Index->getAPIntValue();
5535 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5536 NewIndex *= APIntIndex;
5537 // Check if the new constant index fits into i32.
5538 if (NewIndex.getBitWidth() > 32)
5539 return SDValue();
5541 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5542 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5543 SDLoc dl(Op);
5544 SDValue ExtractSrc = Op.getOperand(0);
5545 EVT VecVT = EVT::getVectorVT(
5546 *DAG.getContext(), DstVT.getScalarType(),
5547 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5548 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5549 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5550 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5553 /// ExpandBITCAST - If the target supports VFP, this function is called to
5554 /// expand a bit convert where either the source or destination type is i64 to
5555 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5556 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5557 /// vectors), since the legalizer won't know what to do with that.
5558 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5559 const ARMSubtarget *Subtarget) {
5560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5561 SDLoc dl(N);
5562 SDValue Op = N->getOperand(0);
5564 // This function is only supposed to be called for i64 types, either as the
5565 // source or destination of the bit convert.
5566 EVT SrcVT = Op.getValueType();
5567 EVT DstVT = N->getValueType(0);
5568 const bool HasFullFP16 = Subtarget->hasFullFP16();
5570 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5571 // FullFP16: half values are passed in S-registers, and we don't
5572 // need any of the bitcast and moves:
5574 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5575 // t5: i32 = bitcast t2
5576 // t18: f16 = ARMISD::VMOVhr t5
5577 if (Op.getOpcode() != ISD::CopyFromReg ||
5578 Op.getValueType() != MVT::f32)
5579 return SDValue();
5581 auto Move = N->use_begin();
5582 if (Move->getOpcode() != ARMISD::VMOVhr)
5583 return SDValue();
5585 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5586 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5587 DAG.ReplaceAllUsesWith(*Move, &Copy);
5588 return Copy;
5591 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5592 if (!HasFullFP16)
5593 return SDValue();
5594 // SoftFP: read half-precision arguments:
5596 // t2: i32,ch = ...
5597 // t7: i16 = truncate t2 <~~~~ Op
5598 // t8: f16 = bitcast t7 <~~~~ N
5600 if (Op.getOperand(0).getValueType() == MVT::i32)
5601 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5602 MVT::f16, Op.getOperand(0));
5604 return SDValue();
5607 // Half-precision return values
5608 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5609 if (!HasFullFP16)
5610 return SDValue();
5612 // t11: f16 = fadd t8, t10
5613 // t12: i16 = bitcast t11 <~~~ SDNode N
5614 // t13: i32 = zero_extend t12
5615 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5616 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5618 // transform this into:
5620 // t20: i32 = ARMISD::VMOVrh t11
5621 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5623 auto ZeroExtend = N->use_begin();
5624 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5625 ZeroExtend->getValueType(0) != MVT::i32)
5626 return SDValue();
5628 auto Copy = ZeroExtend->use_begin();
5629 if (Copy->getOpcode() == ISD::CopyToReg &&
5630 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5631 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5632 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5633 return Cvt;
5635 return SDValue();
5638 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5639 return SDValue();
5641 // Turn i64->f64 into VMOVDRR.
5642 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5643 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5644 // if we can combine the bitcast with its source.
5645 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5646 return Val;
5648 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5649 DAG.getConstant(0, dl, MVT::i32));
5650 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5651 DAG.getConstant(1, dl, MVT::i32));
5652 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5653 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5656 // Turn f64->i64 into VMOVRRD.
5657 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5658 SDValue Cvt;
5659 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5660 SrcVT.getVectorNumElements() > 1)
5661 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5662 DAG.getVTList(MVT::i32, MVT::i32),
5663 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5664 else
5665 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5666 DAG.getVTList(MVT::i32, MVT::i32), Op);
5667 // Merge the pieces into a single i64 value.
5668 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5671 return SDValue();
5674 /// getZeroVector - Returns a vector of specified type with all zero elements.
5675 /// Zero vectors are used to represent vector negation and in those cases
5676 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5677 /// not support i64 elements, so sometimes the zero vectors will need to be
5678 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5679 /// zero vector.
5680 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5681 assert(VT.isVector() && "Expected a vector type");
5682 // The canonical modified immediate encoding of a zero vector is....0!
5683 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5684 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5685 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5686 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5689 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5690 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5691 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5692 SelectionDAG &DAG) const {
5693 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5694 EVT VT = Op.getValueType();
5695 unsigned VTBits = VT.getSizeInBits();
5696 SDLoc dl(Op);
5697 SDValue ShOpLo = Op.getOperand(0);
5698 SDValue ShOpHi = Op.getOperand(1);
5699 SDValue ShAmt = Op.getOperand(2);
5700 SDValue ARMcc;
5701 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5702 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5704 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5706 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5707 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5708 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5709 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5710 DAG.getConstant(VTBits, dl, MVT::i32));
5711 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5712 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5713 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5714 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5715 ISD::SETGE, ARMcc, DAG, dl);
5716 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5717 ARMcc, CCR, CmpLo);
5719 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5720 SDValue HiBigShift = Opc == ISD::SRA
5721 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5722 DAG.getConstant(VTBits - 1, dl, VT))
5723 : DAG.getConstant(0, dl, VT);
5724 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5725 ISD::SETGE, ARMcc, DAG, dl);
5726 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5727 ARMcc, CCR, CmpHi);
5729 SDValue Ops[2] = { Lo, Hi };
5730 return DAG.getMergeValues(Ops, dl);
5733 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5734 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5735 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5736 SelectionDAG &DAG) const {
5737 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5738 EVT VT = Op.getValueType();
5739 unsigned VTBits = VT.getSizeInBits();
5740 SDLoc dl(Op);
5741 SDValue ShOpLo = Op.getOperand(0);
5742 SDValue ShOpHi = Op.getOperand(1);
5743 SDValue ShAmt = Op.getOperand(2);
5744 SDValue ARMcc;
5745 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5747 assert(Op.getOpcode() == ISD::SHL_PARTS);
5748 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5749 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5750 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5751 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5752 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5754 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5755 DAG.getConstant(VTBits, dl, MVT::i32));
5756 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5757 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5758 ISD::SETGE, ARMcc, DAG, dl);
5759 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5760 ARMcc, CCR, CmpHi);
5762 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5763 ISD::SETGE, ARMcc, DAG, dl);
5764 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5765 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5766 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5768 SDValue Ops[2] = { Lo, Hi };
5769 return DAG.getMergeValues(Ops, dl);
5772 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5773 SelectionDAG &DAG) const {
5774 // The rounding mode is in bits 23:22 of the FPSCR.
5775 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5776 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5777 // so that the shift + and get folded into a bitfield extract.
5778 SDLoc dl(Op);
5779 SDValue Ops[] = { DAG.getEntryNode(),
5780 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5782 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5783 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5784 DAG.getConstant(1U << 22, dl, MVT::i32));
5785 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5786 DAG.getConstant(22, dl, MVT::i32));
5787 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5788 DAG.getConstant(3, dl, MVT::i32));
5791 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5792 const ARMSubtarget *ST) {
5793 SDLoc dl(N);
5794 EVT VT = N->getValueType(0);
5795 if (VT.isVector()) {
5796 assert(ST->hasNEON());
5798 // Compute the least significant set bit: LSB = X & -X
5799 SDValue X = N->getOperand(0);
5800 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5801 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5803 EVT ElemTy = VT.getVectorElementType();
5805 if (ElemTy == MVT::i8) {
5806 // Compute with: cttz(x) = ctpop(lsb - 1)
5807 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5808 DAG.getTargetConstant(1, dl, ElemTy));
5809 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5810 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5813 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5814 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5815 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5816 unsigned NumBits = ElemTy.getSizeInBits();
5817 SDValue WidthMinus1 =
5818 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5819 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5820 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5821 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5824 // Compute with: cttz(x) = ctpop(lsb - 1)
5826 // Compute LSB - 1.
5827 SDValue Bits;
5828 if (ElemTy == MVT::i64) {
5829 // Load constant 0xffff'ffff'ffff'ffff to register.
5830 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5831 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5832 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5833 } else {
5834 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5835 DAG.getTargetConstant(1, dl, ElemTy));
5836 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5838 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5841 if (!ST->hasV6T2Ops())
5842 return SDValue();
5844 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5845 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5848 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5849 const ARMSubtarget *ST) {
5850 EVT VT = N->getValueType(0);
5851 SDLoc DL(N);
5853 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5854 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5855 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5856 "Unexpected type for custom ctpop lowering");
5858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5859 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5860 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5861 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5863 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5864 unsigned EltSize = 8;
5865 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5866 while (EltSize != VT.getScalarSizeInBits()) {
5867 SmallVector<SDValue, 8> Ops;
5868 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5869 TLI.getPointerTy(DAG.getDataLayout())));
5870 Ops.push_back(Res);
5872 EltSize *= 2;
5873 NumElts /= 2;
5874 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5875 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5878 return Res;
5881 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5882 /// operand of a vector shift operation, where all the elements of the
5883 /// build_vector must have the same constant integer value.
5884 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5885 // Ignore bit_converts.
5886 while (Op.getOpcode() == ISD::BITCAST)
5887 Op = Op.getOperand(0);
5888 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5889 APInt SplatBits, SplatUndef;
5890 unsigned SplatBitSize;
5891 bool HasAnyUndefs;
5892 if (!BVN ||
5893 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5894 ElementBits) ||
5895 SplatBitSize > ElementBits)
5896 return false;
5897 Cnt = SplatBits.getSExtValue();
5898 return true;
5901 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5902 /// operand of a vector shift left operation. That value must be in the range:
5903 /// 0 <= Value < ElementBits for a left shift; or
5904 /// 0 <= Value <= ElementBits for a long left shift.
5905 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5906 assert(VT.isVector() && "vector shift count is not a vector type");
5907 int64_t ElementBits = VT.getScalarSizeInBits();
5908 if (!getVShiftImm(Op, ElementBits, Cnt))
5909 return false;
5910 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5913 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5914 /// operand of a vector shift right operation. For a shift opcode, the value
5915 /// is positive, but for an intrinsic the value count must be negative. The
5916 /// absolute value must be in the range:
5917 /// 1 <= |Value| <= ElementBits for a right shift; or
5918 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5919 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5920 int64_t &Cnt) {
5921 assert(VT.isVector() && "vector shift count is not a vector type");
5922 int64_t ElementBits = VT.getScalarSizeInBits();
5923 if (!getVShiftImm(Op, ElementBits, Cnt))
5924 return false;
5925 if (!isIntrinsic)
5926 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5927 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5928 Cnt = -Cnt;
5929 return true;
5931 return false;
5934 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5935 const ARMSubtarget *ST) {
5936 EVT VT = N->getValueType(0);
5937 SDLoc dl(N);
5938 int64_t Cnt;
5940 if (!VT.isVector())
5941 return SDValue();
5943 // We essentially have two forms here. Shift by an immediate and shift by a
5944 // vector register (there are also shift by a gpr, but that is just handled
5945 // with a tablegen pattern). We cannot easily match shift by an immediate in
5946 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5947 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5948 // signed or unsigned, and a negative shift indicates a shift right).
5949 if (N->getOpcode() == ISD::SHL) {
5950 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5951 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5952 DAG.getConstant(Cnt, dl, MVT::i32));
5953 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5954 N->getOperand(1));
5957 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5958 "unexpected vector shift opcode");
5960 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5961 unsigned VShiftOpc =
5962 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5963 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5964 DAG.getConstant(Cnt, dl, MVT::i32));
5967 // Other right shifts we don't have operations for (we use a shift left by a
5968 // negative number).
5969 EVT ShiftVT = N->getOperand(1).getValueType();
5970 SDValue NegatedCount = DAG.getNode(
5971 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5972 unsigned VShiftOpc =
5973 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5974 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5977 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5978 const ARMSubtarget *ST) {
5979 EVT VT = N->getValueType(0);
5980 SDLoc dl(N);
5982 // We can get here for a node like i32 = ISD::SHL i32, i64
5983 if (VT != MVT::i64)
5984 return SDValue();
5986 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5987 N->getOpcode() == ISD::SHL) &&
5988 "Unknown shift to lower!");
5990 unsigned ShOpc = N->getOpcode();
5991 if (ST->hasMVEIntegerOps()) {
5992 SDValue ShAmt = N->getOperand(1);
5993 unsigned ShPartsOpc = ARMISD::LSLL;
5994 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5996 // If the shift amount is greater than 32 or has a greater bitwidth than 64
5997 // then do the default optimisation
5998 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
5999 (Con && Con->getZExtValue() >= 32))
6000 return SDValue();
6002 // Extract the lower 32 bits of the shift amount if it's not an i32
6003 if (ShAmt->getValueType(0) != MVT::i32)
6004 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6006 if (ShOpc == ISD::SRL) {
6007 if (!Con)
6008 // There is no t2LSRLr instruction so negate and perform an lsll if the
6009 // shift amount is in a register, emulating a right shift.
6010 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6011 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6012 else
6013 // Else generate an lsrl on the immediate shift amount
6014 ShPartsOpc = ARMISD::LSRL;
6015 } else if (ShOpc == ISD::SRA)
6016 ShPartsOpc = ARMISD::ASRL;
6018 // Lower 32 bits of the destination/source
6019 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6020 DAG.getConstant(0, dl, MVT::i32));
6021 // Upper 32 bits of the destination/source
6022 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6023 DAG.getConstant(1, dl, MVT::i32));
6025 // Generate the shift operation as computed above
6026 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6027 ShAmt);
6028 // The upper 32 bits come from the second return value of lsll
6029 Hi = SDValue(Lo.getNode(), 1);
6030 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6033 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6034 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6035 return SDValue();
6037 // If we are in thumb mode, we don't have RRX.
6038 if (ST->isThumb1Only())
6039 return SDValue();
6041 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6042 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6043 DAG.getConstant(0, dl, MVT::i32));
6044 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6045 DAG.getConstant(1, dl, MVT::i32));
6047 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6048 // captures the result into a carry flag.
6049 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6050 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6052 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6053 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6055 // Merge the pieces into a single i64 value.
6056 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6059 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6060 const ARMSubtarget *ST) {
6061 bool Invert = false;
6062 bool Swap = false;
6063 unsigned Opc = ARMCC::AL;
6065 SDValue Op0 = Op.getOperand(0);
6066 SDValue Op1 = Op.getOperand(1);
6067 SDValue CC = Op.getOperand(2);
6068 EVT VT = Op.getValueType();
6069 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6070 SDLoc dl(Op);
6072 EVT CmpVT;
6073 if (ST->hasNEON())
6074 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6075 else {
6076 assert(ST->hasMVEIntegerOps() &&
6077 "No hardware support for integer vector comparison!");
6079 if (Op.getValueType().getVectorElementType() != MVT::i1)
6080 return SDValue();
6082 // Make sure we expand floating point setcc to scalar if we do not have
6083 // mve.fp, so that we can handle them from there.
6084 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6085 return SDValue();
6087 CmpVT = VT;
6090 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6091 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6092 // Special-case integer 64-bit equality comparisons. They aren't legal,
6093 // but they can be lowered with a few vector instructions.
6094 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6095 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6096 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6097 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6098 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6099 DAG.getCondCode(ISD::SETEQ));
6100 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6101 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6102 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6103 if (SetCCOpcode == ISD::SETNE)
6104 Merged = DAG.getNOT(dl, Merged, CmpVT);
6105 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6106 return Merged;
6109 if (CmpVT.getVectorElementType() == MVT::i64)
6110 // 64-bit comparisons are not legal in general.
6111 return SDValue();
6113 if (Op1.getValueType().isFloatingPoint()) {
6114 switch (SetCCOpcode) {
6115 default: llvm_unreachable("Illegal FP comparison");
6116 case ISD::SETUNE:
6117 case ISD::SETNE:
6118 if (ST->hasMVEFloatOps()) {
6119 Opc = ARMCC::NE; break;
6120 } else {
6121 Invert = true; LLVM_FALLTHROUGH;
6123 case ISD::SETOEQ:
6124 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6125 case ISD::SETOLT:
6126 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6127 case ISD::SETOGT:
6128 case ISD::SETGT: Opc = ARMCC::GT; break;
6129 case ISD::SETOLE:
6130 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6131 case ISD::SETOGE:
6132 case ISD::SETGE: Opc = ARMCC::GE; break;
6133 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6134 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6135 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6136 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6137 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6138 case ISD::SETONE: {
6139 // Expand this to (OLT | OGT).
6140 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6141 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6142 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6143 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6144 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6145 if (Invert)
6146 Result = DAG.getNOT(dl, Result, VT);
6147 return Result;
6149 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6150 case ISD::SETO: {
6151 // Expand this to (OLT | OGE).
6152 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6153 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6154 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6155 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6156 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6157 if (Invert)
6158 Result = DAG.getNOT(dl, Result, VT);
6159 return Result;
6162 } else {
6163 // Integer comparisons.
6164 switch (SetCCOpcode) {
6165 default: llvm_unreachable("Illegal integer comparison");
6166 case ISD::SETNE:
6167 if (ST->hasMVEIntegerOps()) {
6168 Opc = ARMCC::NE; break;
6169 } else {
6170 Invert = true; LLVM_FALLTHROUGH;
6172 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6173 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6174 case ISD::SETGT: Opc = ARMCC::GT; break;
6175 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6176 case ISD::SETGE: Opc = ARMCC::GE; break;
6177 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6178 case ISD::SETUGT: Opc = ARMCC::HI; break;
6179 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6180 case ISD::SETUGE: Opc = ARMCC::HS; break;
6183 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6184 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6185 SDValue AndOp;
6186 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6187 AndOp = Op0;
6188 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6189 AndOp = Op1;
6191 // Ignore bitconvert.
6192 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6193 AndOp = AndOp.getOperand(0);
6195 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6196 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6197 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6198 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6199 if (!Invert)
6200 Result = DAG.getNOT(dl, Result, VT);
6201 return Result;
6206 if (Swap)
6207 std::swap(Op0, Op1);
6209 // If one of the operands is a constant vector zero, attempt to fold the
6210 // comparison to a specialized compare-against-zero form.
6211 SDValue SingleOp;
6212 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6213 SingleOp = Op0;
6214 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6215 if (Opc == ARMCC::GE)
6216 Opc = ARMCC::LE;
6217 else if (Opc == ARMCC::GT)
6218 Opc = ARMCC::LT;
6219 SingleOp = Op1;
6222 SDValue Result;
6223 if (SingleOp.getNode()) {
6224 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6225 DAG.getConstant(Opc, dl, MVT::i32));
6226 } else {
6227 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6228 DAG.getConstant(Opc, dl, MVT::i32));
6231 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6233 if (Invert)
6234 Result = DAG.getNOT(dl, Result, VT);
6236 return Result;
6239 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6240 SDValue LHS = Op.getOperand(0);
6241 SDValue RHS = Op.getOperand(1);
6242 SDValue Carry = Op.getOperand(2);
6243 SDValue Cond = Op.getOperand(3);
6244 SDLoc DL(Op);
6246 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6248 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6249 // have to invert the carry first.
6250 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6251 DAG.getConstant(1, DL, MVT::i32), Carry);
6252 // This converts the boolean value carry into the carry flag.
6253 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6255 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6256 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6258 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6259 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6260 SDValue ARMcc = DAG.getConstant(
6261 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6262 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6263 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6264 Cmp.getValue(1), SDValue());
6265 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6266 CCR, Chain.getValue(1));
6269 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6270 /// valid vector constant for a NEON or MVE instruction with a "modified
6271 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6272 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6273 unsigned SplatBitSize, SelectionDAG &DAG,
6274 const SDLoc &dl, EVT &VT, bool is128Bits,
6275 VMOVModImmType type) {
6276 unsigned OpCmode, Imm;
6278 // SplatBitSize is set to the smallest size that splats the vector, so a
6279 // zero vector will always have SplatBitSize == 8. However, NEON modified
6280 // immediate instructions others than VMOV do not support the 8-bit encoding
6281 // of a zero vector, and the default encoding of zero is supposed to be the
6282 // 32-bit version.
6283 if (SplatBits == 0)
6284 SplatBitSize = 32;
6286 switch (SplatBitSize) {
6287 case 8:
6288 if (type != VMOVModImm)
6289 return SDValue();
6290 // Any 1-byte value is OK. Op=0, Cmode=1110.
6291 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6292 OpCmode = 0xe;
6293 Imm = SplatBits;
6294 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6295 break;
6297 case 16:
6298 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6299 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6300 if ((SplatBits & ~0xff) == 0) {
6301 // Value = 0x00nn: Op=x, Cmode=100x.
6302 OpCmode = 0x8;
6303 Imm = SplatBits;
6304 break;
6306 if ((SplatBits & ~0xff00) == 0) {
6307 // Value = 0xnn00: Op=x, Cmode=101x.
6308 OpCmode = 0xa;
6309 Imm = SplatBits >> 8;
6310 break;
6312 return SDValue();
6314 case 32:
6315 // NEON's 32-bit VMOV supports splat values where:
6316 // * only one byte is nonzero, or
6317 // * the least significant byte is 0xff and the second byte is nonzero, or
6318 // * the least significant 2 bytes are 0xff and the third is nonzero.
6319 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6320 if ((SplatBits & ~0xff) == 0) {
6321 // Value = 0x000000nn: Op=x, Cmode=000x.
6322 OpCmode = 0;
6323 Imm = SplatBits;
6324 break;
6326 if ((SplatBits & ~0xff00) == 0) {
6327 // Value = 0x0000nn00: Op=x, Cmode=001x.
6328 OpCmode = 0x2;
6329 Imm = SplatBits >> 8;
6330 break;
6332 if ((SplatBits & ~0xff0000) == 0) {
6333 // Value = 0x00nn0000: Op=x, Cmode=010x.
6334 OpCmode = 0x4;
6335 Imm = SplatBits >> 16;
6336 break;
6338 if ((SplatBits & ~0xff000000) == 0) {
6339 // Value = 0xnn000000: Op=x, Cmode=011x.
6340 OpCmode = 0x6;
6341 Imm = SplatBits >> 24;
6342 break;
6345 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6346 if (type == OtherModImm) return SDValue();
6348 if ((SplatBits & ~0xffff) == 0 &&
6349 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6350 // Value = 0x0000nnff: Op=x, Cmode=1100.
6351 OpCmode = 0xc;
6352 Imm = SplatBits >> 8;
6353 break;
6356 // cmode == 0b1101 is not supported for MVE VMVN
6357 if (type == MVEVMVNModImm)
6358 return SDValue();
6360 if ((SplatBits & ~0xffffff) == 0 &&
6361 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6362 // Value = 0x00nnffff: Op=x, Cmode=1101.
6363 OpCmode = 0xd;
6364 Imm = SplatBits >> 16;
6365 break;
6368 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6369 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6370 // VMOV.I32. A (very) minor optimization would be to replicate the value
6371 // and fall through here to test for a valid 64-bit splat. But, then the
6372 // caller would also need to check and handle the change in size.
6373 return SDValue();
6375 case 64: {
6376 if (type != VMOVModImm)
6377 return SDValue();
6378 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6379 uint64_t BitMask = 0xff;
6380 uint64_t Val = 0;
6381 unsigned ImmMask = 1;
6382 Imm = 0;
6383 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6384 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6385 Val |= BitMask;
6386 Imm |= ImmMask;
6387 } else if ((SplatBits & BitMask) != 0) {
6388 return SDValue();
6390 BitMask <<= 8;
6391 ImmMask <<= 1;
6394 if (DAG.getDataLayout().isBigEndian())
6395 // swap higher and lower 32 bit word
6396 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6398 // Op=1, Cmode=1110.
6399 OpCmode = 0x1e;
6400 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6401 break;
6404 default:
6405 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6408 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6409 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6412 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6413 const ARMSubtarget *ST) const {
6414 EVT VT = Op.getValueType();
6415 bool IsDouble = (VT == MVT::f64);
6416 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6417 const APFloat &FPVal = CFP->getValueAPF();
6419 // Prevent floating-point constants from using literal loads
6420 // when execute-only is enabled.
6421 if (ST->genExecuteOnly()) {
6422 // If we can represent the constant as an immediate, don't lower it
6423 if (isFPImmLegal(FPVal, VT))
6424 return Op;
6425 // Otherwise, construct as integer, and move to float register
6426 APInt INTVal = FPVal.bitcastToAPInt();
6427 SDLoc DL(CFP);
6428 switch (VT.getSimpleVT().SimpleTy) {
6429 default:
6430 llvm_unreachable("Unknown floating point type!");
6431 break;
6432 case MVT::f64: {
6433 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6434 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6435 if (!ST->isLittle())
6436 std::swap(Lo, Hi);
6437 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6439 case MVT::f32:
6440 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6441 DAG.getConstant(INTVal, DL, MVT::i32));
6445 if (!ST->hasVFP3Base())
6446 return SDValue();
6448 // Use the default (constant pool) lowering for double constants when we have
6449 // an SP-only FPU
6450 if (IsDouble && !Subtarget->hasFP64())
6451 return SDValue();
6453 // Try splatting with a VMOV.f32...
6454 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6456 if (ImmVal != -1) {
6457 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6458 // We have code in place to select a valid ConstantFP already, no need to
6459 // do any mangling.
6460 return Op;
6463 // It's a float and we are trying to use NEON operations where
6464 // possible. Lower it to a splat followed by an extract.
6465 SDLoc DL(Op);
6466 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6467 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6468 NewVal);
6469 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6470 DAG.getConstant(0, DL, MVT::i32));
6473 // The rest of our options are NEON only, make sure that's allowed before
6474 // proceeding..
6475 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6476 return SDValue();
6478 EVT VMovVT;
6479 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6481 // It wouldn't really be worth bothering for doubles except for one very
6482 // important value, which does happen to match: 0.0. So make sure we don't do
6483 // anything stupid.
6484 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6485 return SDValue();
6487 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6488 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6489 VMovVT, false, VMOVModImm);
6490 if (NewVal != SDValue()) {
6491 SDLoc DL(Op);
6492 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6493 NewVal);
6494 if (IsDouble)
6495 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6497 // It's a float: cast and extract a vector element.
6498 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6499 VecConstant);
6500 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6501 DAG.getConstant(0, DL, MVT::i32));
6504 // Finally, try a VMVN.i32
6505 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6506 false, VMVNModImm);
6507 if (NewVal != SDValue()) {
6508 SDLoc DL(Op);
6509 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6511 if (IsDouble)
6512 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6514 // It's a float: cast and extract a vector element.
6515 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6516 VecConstant);
6517 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6518 DAG.getConstant(0, DL, MVT::i32));
6521 return SDValue();
6524 // check if an VEXT instruction can handle the shuffle mask when the
6525 // vector sources of the shuffle are the same.
6526 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6527 unsigned NumElts = VT.getVectorNumElements();
6529 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6530 if (M[0] < 0)
6531 return false;
6533 Imm = M[0];
6535 // If this is a VEXT shuffle, the immediate value is the index of the first
6536 // element. The other shuffle indices must be the successive elements after
6537 // the first one.
6538 unsigned ExpectedElt = Imm;
6539 for (unsigned i = 1; i < NumElts; ++i) {
6540 // Increment the expected index. If it wraps around, just follow it
6541 // back to index zero and keep going.
6542 ++ExpectedElt;
6543 if (ExpectedElt == NumElts)
6544 ExpectedElt = 0;
6546 if (M[i] < 0) continue; // ignore UNDEF indices
6547 if (ExpectedElt != static_cast<unsigned>(M[i]))
6548 return false;
6551 return true;
6554 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6555 bool &ReverseVEXT, unsigned &Imm) {
6556 unsigned NumElts = VT.getVectorNumElements();
6557 ReverseVEXT = false;
6559 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6560 if (M[0] < 0)
6561 return false;
6563 Imm = M[0];
6565 // If this is a VEXT shuffle, the immediate value is the index of the first
6566 // element. The other shuffle indices must be the successive elements after
6567 // the first one.
6568 unsigned ExpectedElt = Imm;
6569 for (unsigned i = 1; i < NumElts; ++i) {
6570 // Increment the expected index. If it wraps around, it may still be
6571 // a VEXT but the source vectors must be swapped.
6572 ExpectedElt += 1;
6573 if (ExpectedElt == NumElts * 2) {
6574 ExpectedElt = 0;
6575 ReverseVEXT = true;
6578 if (M[i] < 0) continue; // ignore UNDEF indices
6579 if (ExpectedElt != static_cast<unsigned>(M[i]))
6580 return false;
6583 // Adjust the index value if the source operands will be swapped.
6584 if (ReverseVEXT)
6585 Imm -= NumElts;
6587 return true;
6590 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6591 /// instruction with the specified blocksize. (The order of the elements
6592 /// within each block of the vector is reversed.)
6593 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6594 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6595 "Only possible block sizes for VREV are: 16, 32, 64");
6597 unsigned EltSz = VT.getScalarSizeInBits();
6598 if (EltSz == 64)
6599 return false;
6601 unsigned NumElts = VT.getVectorNumElements();
6602 unsigned BlockElts = M[0] + 1;
6603 // If the first shuffle index is UNDEF, be optimistic.
6604 if (M[0] < 0)
6605 BlockElts = BlockSize / EltSz;
6607 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6608 return false;
6610 for (unsigned i = 0; i < NumElts; ++i) {
6611 if (M[i] < 0) continue; // ignore UNDEF indices
6612 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6613 return false;
6616 return true;
6619 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6620 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6621 // range, then 0 is placed into the resulting vector. So pretty much any mask
6622 // of 8 elements can work here.
6623 return VT == MVT::v8i8 && M.size() == 8;
6626 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6627 unsigned Index) {
6628 if (Mask.size() == Elements * 2)
6629 return Index / Elements;
6630 return Mask[Index] == 0 ? 0 : 1;
6633 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6634 // checking that pairs of elements in the shuffle mask represent the same index
6635 // in each vector, incrementing the expected index by 2 at each step.
6636 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6637 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6638 // v2={e,f,g,h}
6639 // WhichResult gives the offset for each element in the mask based on which
6640 // of the two results it belongs to.
6642 // The transpose can be represented either as:
6643 // result1 = shufflevector v1, v2, result1_shuffle_mask
6644 // result2 = shufflevector v1, v2, result2_shuffle_mask
6645 // where v1/v2 and the shuffle masks have the same number of elements
6646 // (here WhichResult (see below) indicates which result is being checked)
6648 // or as:
6649 // results = shufflevector v1, v2, shuffle_mask
6650 // where both results are returned in one vector and the shuffle mask has twice
6651 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6652 // want to check the low half and high half of the shuffle mask as if it were
6653 // the other case
6654 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6655 unsigned EltSz = VT.getScalarSizeInBits();
6656 if (EltSz == 64)
6657 return false;
6659 unsigned NumElts = VT.getVectorNumElements();
6660 if (M.size() != NumElts && M.size() != NumElts*2)
6661 return false;
6663 // If the mask is twice as long as the input vector then we need to check the
6664 // upper and lower parts of the mask with a matching value for WhichResult
6665 // FIXME: A mask with only even values will be rejected in case the first
6666 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6667 // M[0] is used to determine WhichResult
6668 for (unsigned i = 0; i < M.size(); i += NumElts) {
6669 WhichResult = SelectPairHalf(NumElts, M, i);
6670 for (unsigned j = 0; j < NumElts; j += 2) {
6671 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6672 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6673 return false;
6677 if (M.size() == NumElts*2)
6678 WhichResult = 0;
6680 return true;
6683 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6684 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6685 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6686 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6687 unsigned EltSz = VT.getScalarSizeInBits();
6688 if (EltSz == 64)
6689 return false;
6691 unsigned NumElts = VT.getVectorNumElements();
6692 if (M.size() != NumElts && M.size() != NumElts*2)
6693 return false;
6695 for (unsigned i = 0; i < M.size(); i += NumElts) {
6696 WhichResult = SelectPairHalf(NumElts, M, i);
6697 for (unsigned j = 0; j < NumElts; j += 2) {
6698 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6699 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6700 return false;
6704 if (M.size() == NumElts*2)
6705 WhichResult = 0;
6707 return true;
6710 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6711 // that the mask elements are either all even and in steps of size 2 or all odd
6712 // and in steps of size 2.
6713 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6714 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6715 // v2={e,f,g,h}
6716 // Requires similar checks to that of isVTRNMask with
6717 // respect the how results are returned.
6718 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6719 unsigned EltSz = VT.getScalarSizeInBits();
6720 if (EltSz == 64)
6721 return false;
6723 unsigned NumElts = VT.getVectorNumElements();
6724 if (M.size() != NumElts && M.size() != NumElts*2)
6725 return false;
6727 for (unsigned i = 0; i < M.size(); i += NumElts) {
6728 WhichResult = SelectPairHalf(NumElts, M, i);
6729 for (unsigned j = 0; j < NumElts; ++j) {
6730 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6731 return false;
6735 if (M.size() == NumElts*2)
6736 WhichResult = 0;
6738 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6739 if (VT.is64BitVector() && EltSz == 32)
6740 return false;
6742 return true;
6745 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6746 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6747 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6748 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6749 unsigned EltSz = VT.getScalarSizeInBits();
6750 if (EltSz == 64)
6751 return false;
6753 unsigned NumElts = VT.getVectorNumElements();
6754 if (M.size() != NumElts && M.size() != NumElts*2)
6755 return false;
6757 unsigned Half = NumElts / 2;
6758 for (unsigned i = 0; i < M.size(); i += NumElts) {
6759 WhichResult = SelectPairHalf(NumElts, M, i);
6760 for (unsigned j = 0; j < NumElts; j += Half) {
6761 unsigned Idx = WhichResult;
6762 for (unsigned k = 0; k < Half; ++k) {
6763 int MIdx = M[i + j + k];
6764 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6765 return false;
6766 Idx += 2;
6771 if (M.size() == NumElts*2)
6772 WhichResult = 0;
6774 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6775 if (VT.is64BitVector() && EltSz == 32)
6776 return false;
6778 return true;
6781 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6782 // that pairs of elements of the shufflemask represent the same index in each
6783 // vector incrementing sequentially through the vectors.
6784 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6785 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6786 // v2={e,f,g,h}
6787 // Requires similar checks to that of isVTRNMask with respect the how results
6788 // are returned.
6789 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6790 unsigned EltSz = VT.getScalarSizeInBits();
6791 if (EltSz == 64)
6792 return false;
6794 unsigned NumElts = VT.getVectorNumElements();
6795 if (M.size() != NumElts && M.size() != NumElts*2)
6796 return false;
6798 for (unsigned i = 0; i < M.size(); i += NumElts) {
6799 WhichResult = SelectPairHalf(NumElts, M, i);
6800 unsigned Idx = WhichResult * NumElts / 2;
6801 for (unsigned j = 0; j < NumElts; j += 2) {
6802 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6803 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6804 return false;
6805 Idx += 1;
6809 if (M.size() == NumElts*2)
6810 WhichResult = 0;
6812 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6813 if (VT.is64BitVector() && EltSz == 32)
6814 return false;
6816 return true;
6819 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6820 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6821 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6822 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6823 unsigned EltSz = VT.getScalarSizeInBits();
6824 if (EltSz == 64)
6825 return false;
6827 unsigned NumElts = VT.getVectorNumElements();
6828 if (M.size() != NumElts && M.size() != NumElts*2)
6829 return false;
6831 for (unsigned i = 0; i < M.size(); i += NumElts) {
6832 WhichResult = SelectPairHalf(NumElts, M, i);
6833 unsigned Idx = WhichResult * NumElts / 2;
6834 for (unsigned j = 0; j < NumElts; j += 2) {
6835 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6836 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6837 return false;
6838 Idx += 1;
6842 if (M.size() == NumElts*2)
6843 WhichResult = 0;
6845 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6846 if (VT.is64BitVector() && EltSz == 32)
6847 return false;
6849 return true;
6852 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6853 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6854 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6855 unsigned &WhichResult,
6856 bool &isV_UNDEF) {
6857 isV_UNDEF = false;
6858 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6859 return ARMISD::VTRN;
6860 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6861 return ARMISD::VUZP;
6862 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6863 return ARMISD::VZIP;
6865 isV_UNDEF = true;
6866 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6867 return ARMISD::VTRN;
6868 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6869 return ARMISD::VUZP;
6870 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6871 return ARMISD::VZIP;
6873 return 0;
6876 /// \return true if this is a reverse operation on an vector.
6877 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6878 unsigned NumElts = VT.getVectorNumElements();
6879 // Make sure the mask has the right size.
6880 if (NumElts != M.size())
6881 return false;
6883 // Look for <15, ..., 3, -1, 1, 0>.
6884 for (unsigned i = 0; i != NumElts; ++i)
6885 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6886 return false;
6888 return true;
6891 // If N is an integer constant that can be moved into a register in one
6892 // instruction, return an SDValue of such a constant (will become a MOV
6893 // instruction). Otherwise return null.
6894 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6895 const ARMSubtarget *ST, const SDLoc &dl) {
6896 uint64_t Val;
6897 if (!isa<ConstantSDNode>(N))
6898 return SDValue();
6899 Val = cast<ConstantSDNode>(N)->getZExtValue();
6901 if (ST->isThumb1Only()) {
6902 if (Val <= 255 || ~Val <= 255)
6903 return DAG.getConstant(Val, dl, MVT::i32);
6904 } else {
6905 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6906 return DAG.getConstant(Val, dl, MVT::i32);
6908 return SDValue();
6911 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6912 const ARMSubtarget *ST) {
6913 SDLoc dl(Op);
6914 EVT VT = Op.getValueType();
6916 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6918 unsigned NumElts = VT.getVectorNumElements();
6919 unsigned BoolMask;
6920 unsigned BitsPerBool;
6921 if (NumElts == 4) {
6922 BitsPerBool = 4;
6923 BoolMask = 0xf;
6924 } else if (NumElts == 8) {
6925 BitsPerBool = 2;
6926 BoolMask = 0x3;
6927 } else if (NumElts == 16) {
6928 BitsPerBool = 1;
6929 BoolMask = 0x1;
6930 } else
6931 return SDValue();
6933 // First create base with bits set where known
6934 unsigned Bits32 = 0;
6935 for (unsigned i = 0; i < NumElts; ++i) {
6936 SDValue V = Op.getOperand(i);
6937 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6938 continue;
6939 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6940 if (BitSet)
6941 Bits32 |= BoolMask << (i * BitsPerBool);
6944 // Add in unknown nodes
6945 // FIXME: Handle splats of the same value better.
6946 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6947 DAG.getConstant(Bits32, dl, MVT::i32));
6948 for (unsigned i = 0; i < NumElts; ++i) {
6949 SDValue V = Op.getOperand(i);
6950 if (isa<ConstantSDNode>(V) || V.isUndef())
6951 continue;
6952 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6953 DAG.getConstant(i, dl, MVT::i32));
6956 return Base;
6959 // If this is a case we can't handle, return null and let the default
6960 // expansion code take care of it.
6961 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6962 const ARMSubtarget *ST) const {
6963 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6964 SDLoc dl(Op);
6965 EVT VT = Op.getValueType();
6967 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6968 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6970 APInt SplatBits, SplatUndef;
6971 unsigned SplatBitSize;
6972 bool HasAnyUndefs;
6973 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6974 if (SplatUndef.isAllOnesValue())
6975 return DAG.getUNDEF(VT);
6977 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6978 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6979 // Check if an immediate VMOV works.
6980 EVT VmovVT;
6981 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6982 SplatUndef.getZExtValue(), SplatBitSize,
6983 DAG, dl, VmovVT, VT.is128BitVector(),
6984 VMOVModImm);
6986 if (Val.getNode()) {
6987 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6988 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6991 // Try an immediate VMVN.
6992 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6993 Val = isVMOVModifiedImm(
6994 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6995 DAG, dl, VmovVT, VT.is128BitVector(),
6996 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6997 if (Val.getNode()) {
6998 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6999 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7002 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7003 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7004 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7005 if (ImmVal != -1) {
7006 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7007 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7013 // Scan through the operands to see if only one value is used.
7015 // As an optimisation, even if more than one value is used it may be more
7016 // profitable to splat with one value then change some lanes.
7018 // Heuristically we decide to do this if the vector has a "dominant" value,
7019 // defined as splatted to more than half of the lanes.
7020 unsigned NumElts = VT.getVectorNumElements();
7021 bool isOnlyLowElement = true;
7022 bool usesOnlyOneValue = true;
7023 bool hasDominantValue = false;
7024 bool isConstant = true;
7026 // Map of the number of times a particular SDValue appears in the
7027 // element list.
7028 DenseMap<SDValue, unsigned> ValueCounts;
7029 SDValue Value;
7030 for (unsigned i = 0; i < NumElts; ++i) {
7031 SDValue V = Op.getOperand(i);
7032 if (V.isUndef())
7033 continue;
7034 if (i > 0)
7035 isOnlyLowElement = false;
7036 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7037 isConstant = false;
7039 ValueCounts.insert(std::make_pair(V, 0));
7040 unsigned &Count = ValueCounts[V];
7042 // Is this value dominant? (takes up more than half of the lanes)
7043 if (++Count > (NumElts / 2)) {
7044 hasDominantValue = true;
7045 Value = V;
7048 if (ValueCounts.size() != 1)
7049 usesOnlyOneValue = false;
7050 if (!Value.getNode() && !ValueCounts.empty())
7051 Value = ValueCounts.begin()->first;
7053 if (ValueCounts.empty())
7054 return DAG.getUNDEF(VT);
7056 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7057 // Keep going if we are hitting this case.
7058 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7059 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7061 unsigned EltSize = VT.getScalarSizeInBits();
7063 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7064 // i32 and try again.
7065 if (hasDominantValue && EltSize <= 32) {
7066 if (!isConstant) {
7067 SDValue N;
7069 // If we are VDUPing a value that comes directly from a vector, that will
7070 // cause an unnecessary move to and from a GPR, where instead we could
7071 // just use VDUPLANE. We can only do this if the lane being extracted
7072 // is at a constant index, as the VDUP from lane instructions only have
7073 // constant-index forms.
7074 ConstantSDNode *constIndex;
7075 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7076 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7077 // We need to create a new undef vector to use for the VDUPLANE if the
7078 // size of the vector from which we get the value is different than the
7079 // size of the vector that we need to create. We will insert the element
7080 // such that the register coalescer will remove unnecessary copies.
7081 if (VT != Value->getOperand(0).getValueType()) {
7082 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7083 VT.getVectorNumElements();
7084 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7085 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7086 Value, DAG.getConstant(index, dl, MVT::i32)),
7087 DAG.getConstant(index, dl, MVT::i32));
7088 } else
7089 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7090 Value->getOperand(0), Value->getOperand(1));
7091 } else
7092 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7094 if (!usesOnlyOneValue) {
7095 // The dominant value was splatted as 'N', but we now have to insert
7096 // all differing elements.
7097 for (unsigned I = 0; I < NumElts; ++I) {
7098 if (Op.getOperand(I) == Value)
7099 continue;
7100 SmallVector<SDValue, 3> Ops;
7101 Ops.push_back(N);
7102 Ops.push_back(Op.getOperand(I));
7103 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7104 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7107 return N;
7109 if (VT.getVectorElementType().isFloatingPoint()) {
7110 SmallVector<SDValue, 8> Ops;
7111 MVT FVT = VT.getVectorElementType().getSimpleVT();
7112 assert(FVT == MVT::f32 || FVT == MVT::f16);
7113 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7114 for (unsigned i = 0; i < NumElts; ++i)
7115 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7116 Op.getOperand(i)));
7117 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7118 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7119 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7120 if (Val.getNode())
7121 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7123 if (usesOnlyOneValue) {
7124 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7125 if (isConstant && Val.getNode())
7126 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7130 // If all elements are constants and the case above didn't get hit, fall back
7131 // to the default expansion, which will generate a load from the constant
7132 // pool.
7133 if (isConstant)
7134 return SDValue();
7136 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7137 if (NumElts >= 4) {
7138 SDValue shuffle = ReconstructShuffle(Op, DAG);
7139 if (shuffle != SDValue())
7140 return shuffle;
7143 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7144 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7145 // into two 64-bit vectors; we might discover a better way to lower it.
7146 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7147 EVT ExtVT = VT.getVectorElementType();
7148 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7149 SDValue Lower =
7150 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7151 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7152 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7153 SDValue Upper = DAG.getBuildVector(
7154 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7155 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7156 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7157 if (Lower && Upper)
7158 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7161 // Vectors with 32- or 64-bit elements can be built by directly assigning
7162 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7163 // will be legalized.
7164 if (EltSize >= 32) {
7165 // Do the expansion with floating-point types, since that is what the VFP
7166 // registers are defined to use, and since i64 is not legal.
7167 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7168 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7169 SmallVector<SDValue, 8> Ops;
7170 for (unsigned i = 0; i < NumElts; ++i)
7171 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7172 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7173 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7176 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7177 // know the default expansion would otherwise fall back on something even
7178 // worse. For a vector with one or two non-undef values, that's
7179 // scalar_to_vector for the elements followed by a shuffle (provided the
7180 // shuffle is valid for the target) and materialization element by element
7181 // on the stack followed by a load for everything else.
7182 if (!isConstant && !usesOnlyOneValue) {
7183 SDValue Vec = DAG.getUNDEF(VT);
7184 for (unsigned i = 0 ; i < NumElts; ++i) {
7185 SDValue V = Op.getOperand(i);
7186 if (V.isUndef())
7187 continue;
7188 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7189 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7191 return Vec;
7194 return SDValue();
7197 // Gather data to see if the operation can be modelled as a
7198 // shuffle in combination with VEXTs.
7199 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7200 SelectionDAG &DAG) const {
7201 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7202 SDLoc dl(Op);
7203 EVT VT = Op.getValueType();
7204 unsigned NumElts = VT.getVectorNumElements();
7206 struct ShuffleSourceInfo {
7207 SDValue Vec;
7208 unsigned MinElt = std::numeric_limits<unsigned>::max();
7209 unsigned MaxElt = 0;
7211 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7212 // be compatible with the shuffle we intend to construct. As a result
7213 // ShuffleVec will be some sliding window into the original Vec.
7214 SDValue ShuffleVec;
7216 // Code should guarantee that element i in Vec starts at element "WindowBase
7217 // + i * WindowScale in ShuffleVec".
7218 int WindowBase = 0;
7219 int WindowScale = 1;
7221 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7223 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7226 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7227 // node.
7228 SmallVector<ShuffleSourceInfo, 2> Sources;
7229 for (unsigned i = 0; i < NumElts; ++i) {
7230 SDValue V = Op.getOperand(i);
7231 if (V.isUndef())
7232 continue;
7233 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7234 // A shuffle can only come from building a vector from various
7235 // elements of other vectors.
7236 return SDValue();
7237 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7238 // Furthermore, shuffles require a constant mask, whereas extractelts
7239 // accept variable indices.
7240 return SDValue();
7243 // Add this element source to the list if it's not already there.
7244 SDValue SourceVec = V.getOperand(0);
7245 auto Source = llvm::find(Sources, SourceVec);
7246 if (Source == Sources.end())
7247 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7249 // Update the minimum and maximum lane number seen.
7250 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7251 Source->MinElt = std::min(Source->MinElt, EltNo);
7252 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7255 // Currently only do something sane when at most two source vectors
7256 // are involved.
7257 if (Sources.size() > 2)
7258 return SDValue();
7260 // Find out the smallest element size among result and two sources, and use
7261 // it as element size to build the shuffle_vector.
7262 EVT SmallestEltTy = VT.getVectorElementType();
7263 for (auto &Source : Sources) {
7264 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7265 if (SrcEltTy.bitsLT(SmallestEltTy))
7266 SmallestEltTy = SrcEltTy;
7268 unsigned ResMultiplier =
7269 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7270 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7271 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7273 // If the source vector is too wide or too narrow, we may nevertheless be able
7274 // to construct a compatible shuffle either by concatenating it with UNDEF or
7275 // extracting a suitable range of elements.
7276 for (auto &Src : Sources) {
7277 EVT SrcVT = Src.ShuffleVec.getValueType();
7279 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7280 continue;
7282 // This stage of the search produces a source with the same element type as
7283 // the original, but with a total width matching the BUILD_VECTOR output.
7284 EVT EltVT = SrcVT.getVectorElementType();
7285 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7286 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7288 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7289 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7290 return SDValue();
7291 // We can pad out the smaller vector for free, so if it's part of a
7292 // shuffle...
7293 Src.ShuffleVec =
7294 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7295 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7296 continue;
7299 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7300 return SDValue();
7302 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7303 // Span too large for a VEXT to cope
7304 return SDValue();
7307 if (Src.MinElt >= NumSrcElts) {
7308 // The extraction can just take the second half
7309 Src.ShuffleVec =
7310 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7311 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7312 Src.WindowBase = -NumSrcElts;
7313 } else if (Src.MaxElt < NumSrcElts) {
7314 // The extraction can just take the first half
7315 Src.ShuffleVec =
7316 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7317 DAG.getConstant(0, dl, MVT::i32));
7318 } else {
7319 // An actual VEXT is needed
7320 SDValue VEXTSrc1 =
7321 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7322 DAG.getConstant(0, dl, MVT::i32));
7323 SDValue VEXTSrc2 =
7324 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7325 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7327 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7328 VEXTSrc2,
7329 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7330 Src.WindowBase = -Src.MinElt;
7334 // Another possible incompatibility occurs from the vector element types. We
7335 // can fix this by bitcasting the source vectors to the same type we intend
7336 // for the shuffle.
7337 for (auto &Src : Sources) {
7338 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7339 if (SrcEltTy == SmallestEltTy)
7340 continue;
7341 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7342 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7343 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7344 Src.WindowBase *= Src.WindowScale;
7347 // Final sanity check before we try to actually produce a shuffle.
7348 LLVM_DEBUG(for (auto Src
7349 : Sources)
7350 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7352 // The stars all align, our next step is to produce the mask for the shuffle.
7353 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7354 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7355 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7356 SDValue Entry = Op.getOperand(i);
7357 if (Entry.isUndef())
7358 continue;
7360 auto Src = llvm::find(Sources, Entry.getOperand(0));
7361 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7363 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7364 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7365 // segment.
7366 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7367 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7368 VT.getScalarSizeInBits());
7369 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7371 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7372 // starting at the appropriate offset.
7373 int *LaneMask = &Mask[i * ResMultiplier];
7375 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7376 ExtractBase += NumElts * (Src - Sources.begin());
7377 for (int j = 0; j < LanesDefined; ++j)
7378 LaneMask[j] = ExtractBase + j;
7382 // We can't handle more than two sources. This should have already
7383 // been checked before this point.
7384 assert(Sources.size() <= 2 && "Too many sources!");
7386 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7387 for (unsigned i = 0; i < Sources.size(); ++i)
7388 ShuffleOps[i] = Sources[i].ShuffleVec;
7390 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7391 ShuffleOps[1], Mask, DAG);
7392 if (!Shuffle)
7393 return SDValue();
7394 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7397 enum ShuffleOpCodes {
7398 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7399 OP_VREV,
7400 OP_VDUP0,
7401 OP_VDUP1,
7402 OP_VDUP2,
7403 OP_VDUP3,
7404 OP_VEXT1,
7405 OP_VEXT2,
7406 OP_VEXT3,
7407 OP_VUZPL, // VUZP, left result
7408 OP_VUZPR, // VUZP, right result
7409 OP_VZIPL, // VZIP, left result
7410 OP_VZIPR, // VZIP, right result
7411 OP_VTRNL, // VTRN, left result
7412 OP_VTRNR // VTRN, right result
7415 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7416 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7417 switch (OpNum) {
7418 case OP_COPY:
7419 case OP_VREV:
7420 case OP_VDUP0:
7421 case OP_VDUP1:
7422 case OP_VDUP2:
7423 case OP_VDUP3:
7424 return true;
7426 return false;
7429 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7430 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7431 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7432 /// are assumed to be legal.
7433 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7434 if (VT.getVectorNumElements() == 4 &&
7435 (VT.is128BitVector() || VT.is64BitVector())) {
7436 unsigned PFIndexes[4];
7437 for (unsigned i = 0; i != 4; ++i) {
7438 if (M[i] < 0)
7439 PFIndexes[i] = 8;
7440 else
7441 PFIndexes[i] = M[i];
7444 // Compute the index in the perfect shuffle table.
7445 unsigned PFTableIndex =
7446 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7447 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7448 unsigned Cost = (PFEntry >> 30);
7450 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7451 return true;
7454 bool ReverseVEXT, isV_UNDEF;
7455 unsigned Imm, WhichResult;
7457 unsigned EltSize = VT.getScalarSizeInBits();
7458 if (EltSize >= 32 ||
7459 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7460 isVREVMask(M, VT, 64) ||
7461 isVREVMask(M, VT, 32) ||
7462 isVREVMask(M, VT, 16))
7463 return true;
7464 else if (Subtarget->hasNEON() &&
7465 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7466 isVTBLMask(M, VT) ||
7467 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7468 return true;
7469 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7470 isReverseMask(M, VT))
7471 return true;
7472 else
7473 return false;
7476 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7477 /// the specified operations to build the shuffle.
7478 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7479 SDValue RHS, SelectionDAG &DAG,
7480 const SDLoc &dl) {
7481 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7482 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7483 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7485 if (OpNum == OP_COPY) {
7486 if (LHSID == (1*9+2)*9+3) return LHS;
7487 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7488 return RHS;
7491 SDValue OpLHS, OpRHS;
7492 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7493 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7494 EVT VT = OpLHS.getValueType();
7496 switch (OpNum) {
7497 default: llvm_unreachable("Unknown shuffle opcode!");
7498 case OP_VREV:
7499 // VREV divides the vector in half and swaps within the half.
7500 if (VT.getVectorElementType() == MVT::i32 ||
7501 VT.getVectorElementType() == MVT::f32)
7502 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7503 // vrev <4 x i16> -> VREV32
7504 if (VT.getVectorElementType() == MVT::i16)
7505 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7506 // vrev <4 x i8> -> VREV16
7507 assert(VT.getVectorElementType() == MVT::i8);
7508 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7509 case OP_VDUP0:
7510 case OP_VDUP1:
7511 case OP_VDUP2:
7512 case OP_VDUP3:
7513 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7514 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7515 case OP_VEXT1:
7516 case OP_VEXT2:
7517 case OP_VEXT3:
7518 return DAG.getNode(ARMISD::VEXT, dl, VT,
7519 OpLHS, OpRHS,
7520 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7521 case OP_VUZPL:
7522 case OP_VUZPR:
7523 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7524 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7525 case OP_VZIPL:
7526 case OP_VZIPR:
7527 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7528 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7529 case OP_VTRNL:
7530 case OP_VTRNR:
7531 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7532 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7536 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7537 ArrayRef<int> ShuffleMask,
7538 SelectionDAG &DAG) {
7539 // Check to see if we can use the VTBL instruction.
7540 SDValue V1 = Op.getOperand(0);
7541 SDValue V2 = Op.getOperand(1);
7542 SDLoc DL(Op);
7544 SmallVector<SDValue, 8> VTBLMask;
7545 for (ArrayRef<int>::iterator
7546 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7547 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7549 if (V2.getNode()->isUndef())
7550 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7551 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7553 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7554 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7557 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7558 SelectionDAG &DAG) {
7559 SDLoc DL(Op);
7560 SDValue OpLHS = Op.getOperand(0);
7561 EVT VT = OpLHS.getValueType();
7563 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7564 "Expect an v8i16/v16i8 type");
7565 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7566 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7567 // extract the first 8 bytes into the top double word and the last 8 bytes
7568 // into the bottom double word. The v8i16 case is similar.
7569 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7570 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7571 DAG.getConstant(ExtractNum, DL, MVT::i32));
7574 static EVT getVectorTyFromPredicateVector(EVT VT) {
7575 switch (VT.getSimpleVT().SimpleTy) {
7576 case MVT::v4i1:
7577 return MVT::v4i32;
7578 case MVT::v8i1:
7579 return MVT::v8i16;
7580 case MVT::v16i1:
7581 return MVT::v16i8;
7582 default:
7583 llvm_unreachable("Unexpected vector predicate type");
7587 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7588 SelectionDAG &DAG) {
7589 // Converting from boolean predicates to integers involves creating a vector
7590 // of all ones or all zeroes and selecting the lanes based upon the real
7591 // predicate.
7592 SDValue AllOnes =
7593 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7594 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7596 SDValue AllZeroes =
7597 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7598 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7600 // Get full vector type from predicate type
7601 EVT NewVT = getVectorTyFromPredicateVector(VT);
7603 SDValue RecastV1;
7604 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7605 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7606 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7607 // since we know in hardware the sizes are really the same.
7608 if (VT != MVT::v16i1)
7609 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7610 else
7611 RecastV1 = Pred;
7613 // Select either all ones or zeroes depending upon the real predicate bits.
7614 SDValue PredAsVector =
7615 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7617 // Recast our new predicate-as-integer v16i8 vector into something
7618 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7619 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7622 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7623 const ARMSubtarget *ST) {
7624 EVT VT = Op.getValueType();
7625 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7626 ArrayRef<int> ShuffleMask = SVN->getMask();
7628 assert(ST->hasMVEIntegerOps() &&
7629 "No support for vector shuffle of boolean predicates");
7631 SDValue V1 = Op.getOperand(0);
7632 SDLoc dl(Op);
7633 if (isReverseMask(ShuffleMask, VT)) {
7634 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7635 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7636 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7637 DAG.getConstant(16, dl, MVT::i32));
7638 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7641 // Until we can come up with optimised cases for every single vector
7642 // shuffle in existence we have chosen the least painful strategy. This is
7643 // to essentially promote the boolean predicate to a 8-bit integer, where
7644 // each predicate represents a byte. Then we fall back on a normal integer
7645 // vector shuffle and convert the result back into a predicate vector. In
7646 // many cases the generated code might be even better than scalar code
7647 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7648 // fields in a register into 8 other arbitrary 2-bit fields!
7649 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7650 EVT NewVT = PredAsVector.getValueType();
7652 // Do the shuffle!
7653 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7654 DAG.getUNDEF(NewVT), ShuffleMask);
7656 // Now return the result of comparing the shuffled vector with zero,
7657 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7658 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7659 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7662 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7663 const ARMSubtarget *ST) {
7664 SDValue V1 = Op.getOperand(0);
7665 SDValue V2 = Op.getOperand(1);
7666 SDLoc dl(Op);
7667 EVT VT = Op.getValueType();
7668 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7669 unsigned EltSize = VT.getScalarSizeInBits();
7671 if (ST->hasMVEIntegerOps() && EltSize == 1)
7672 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7674 // Convert shuffles that are directly supported on NEON to target-specific
7675 // DAG nodes, instead of keeping them as shuffles and matching them again
7676 // during code selection. This is more efficient and avoids the possibility
7677 // of inconsistencies between legalization and selection.
7678 // FIXME: floating-point vectors should be canonicalized to integer vectors
7679 // of the same time so that they get CSEd properly.
7680 ArrayRef<int> ShuffleMask = SVN->getMask();
7682 if (EltSize <= 32) {
7683 if (SVN->isSplat()) {
7684 int Lane = SVN->getSplatIndex();
7685 // If this is undef splat, generate it via "just" vdup, if possible.
7686 if (Lane == -1) Lane = 0;
7688 // Test if V1 is a SCALAR_TO_VECTOR.
7689 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7690 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7692 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7693 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7694 // reaches it).
7695 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7696 !isa<ConstantSDNode>(V1.getOperand(0))) {
7697 bool IsScalarToVector = true;
7698 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7699 if (!V1.getOperand(i).isUndef()) {
7700 IsScalarToVector = false;
7701 break;
7703 if (IsScalarToVector)
7704 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7706 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7707 DAG.getConstant(Lane, dl, MVT::i32));
7710 bool ReverseVEXT = false;
7711 unsigned Imm = 0;
7712 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7713 if (ReverseVEXT)
7714 std::swap(V1, V2);
7715 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7716 DAG.getConstant(Imm, dl, MVT::i32));
7719 if (isVREVMask(ShuffleMask, VT, 64))
7720 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7721 if (isVREVMask(ShuffleMask, VT, 32))
7722 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7723 if (isVREVMask(ShuffleMask, VT, 16))
7724 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7726 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7727 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7728 DAG.getConstant(Imm, dl, MVT::i32));
7731 // Check for Neon shuffles that modify both input vectors in place.
7732 // If both results are used, i.e., if there are two shuffles with the same
7733 // source operands and with masks corresponding to both results of one of
7734 // these operations, DAG memoization will ensure that a single node is
7735 // used for both shuffles.
7736 unsigned WhichResult = 0;
7737 bool isV_UNDEF = false;
7738 if (ST->hasNEON()) {
7739 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7740 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7741 if (isV_UNDEF)
7742 V2 = V1;
7743 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7744 .getValue(WhichResult);
7748 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7749 // shuffles that produce a result larger than their operands with:
7750 // shuffle(concat(v1, undef), concat(v2, undef))
7751 // ->
7752 // shuffle(concat(v1, v2), undef)
7753 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7755 // This is useful in the general case, but there are special cases where
7756 // native shuffles produce larger results: the two-result ops.
7758 // Look through the concat when lowering them:
7759 // shuffle(concat(v1, v2), undef)
7760 // ->
7761 // concat(VZIP(v1, v2):0, :1)
7763 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7764 SDValue SubV1 = V1->getOperand(0);
7765 SDValue SubV2 = V1->getOperand(1);
7766 EVT SubVT = SubV1.getValueType();
7768 // We expect these to have been canonicalized to -1.
7769 assert(llvm::all_of(ShuffleMask, [&](int i) {
7770 return i < (int)VT.getVectorNumElements();
7771 }) && "Unexpected shuffle index into UNDEF operand!");
7773 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7774 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7775 if (isV_UNDEF)
7776 SubV2 = SubV1;
7777 assert((WhichResult == 0) &&
7778 "In-place shuffle of concat can only have one result!");
7779 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7780 SubV1, SubV2);
7781 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7782 Res.getValue(1));
7787 // If the shuffle is not directly supported and it has 4 elements, use
7788 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7789 unsigned NumElts = VT.getVectorNumElements();
7790 if (NumElts == 4) {
7791 unsigned PFIndexes[4];
7792 for (unsigned i = 0; i != 4; ++i) {
7793 if (ShuffleMask[i] < 0)
7794 PFIndexes[i] = 8;
7795 else
7796 PFIndexes[i] = ShuffleMask[i];
7799 // Compute the index in the perfect shuffle table.
7800 unsigned PFTableIndex =
7801 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7802 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7803 unsigned Cost = (PFEntry >> 30);
7805 if (Cost <= 4) {
7806 if (ST->hasNEON())
7807 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7808 else if (isLegalMVEShuffleOp(PFEntry)) {
7809 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7810 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7811 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7812 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7813 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7814 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7819 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7820 if (EltSize >= 32) {
7821 // Do the expansion with floating-point types, since that is what the VFP
7822 // registers are defined to use, and since i64 is not legal.
7823 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7824 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7825 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7826 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7827 SmallVector<SDValue, 8> Ops;
7828 for (unsigned i = 0; i < NumElts; ++i) {
7829 if (ShuffleMask[i] < 0)
7830 Ops.push_back(DAG.getUNDEF(EltVT));
7831 else
7832 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7833 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7834 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7835 dl, MVT::i32)));
7837 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7838 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7841 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7842 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7844 if (ST->hasNEON() && VT == MVT::v8i8)
7845 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7846 return NewOp;
7848 return SDValue();
7851 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7852 const ARMSubtarget *ST) {
7853 EVT VecVT = Op.getOperand(0).getValueType();
7854 SDLoc dl(Op);
7856 assert(ST->hasMVEIntegerOps() &&
7857 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7859 SDValue Conv =
7860 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7861 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7862 unsigned LaneWidth =
7863 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7864 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7865 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7866 Op.getOperand(1), DAG.getValueType(MVT::i1));
7867 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7868 DAG.getConstant(~Mask, dl, MVT::i32));
7869 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7872 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7873 SelectionDAG &DAG) const {
7874 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7875 SDValue Lane = Op.getOperand(2);
7876 if (!isa<ConstantSDNode>(Lane))
7877 return SDValue();
7879 SDValue Elt = Op.getOperand(1);
7880 EVT EltVT = Elt.getValueType();
7882 if (Subtarget->hasMVEIntegerOps() &&
7883 Op.getValueType().getScalarSizeInBits() == 1)
7884 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7886 if (getTypeAction(*DAG.getContext(), EltVT) ==
7887 TargetLowering::TypePromoteFloat) {
7888 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7889 // but the type system will try to do that if we don't intervene.
7890 // Reinterpret any such vector-element insertion as one with the
7891 // corresponding integer types.
7893 SDLoc dl(Op);
7895 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7896 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7897 TargetLowering::TypePromoteFloat);
7899 SDValue VecIn = Op.getOperand(0);
7900 EVT VecVT = VecIn.getValueType();
7901 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7902 VecVT.getVectorNumElements());
7904 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7905 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7906 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7907 IVecIn, IElt, Lane);
7908 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7911 return Op;
7914 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7915 const ARMSubtarget *ST) {
7916 EVT VecVT = Op.getOperand(0).getValueType();
7917 SDLoc dl(Op);
7919 assert(ST->hasMVEIntegerOps() &&
7920 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7922 SDValue Conv =
7923 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7924 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7925 unsigned LaneWidth =
7926 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7927 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7928 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7929 return Shift;
7932 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7933 const ARMSubtarget *ST) {
7934 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7935 SDValue Lane = Op.getOperand(1);
7936 if (!isa<ConstantSDNode>(Lane))
7937 return SDValue();
7939 SDValue Vec = Op.getOperand(0);
7940 EVT VT = Vec.getValueType();
7942 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7943 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7945 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7946 SDLoc dl(Op);
7947 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7950 return Op;
7953 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7954 const ARMSubtarget *ST) {
7955 SDValue V1 = Op.getOperand(0);
7956 SDValue V2 = Op.getOperand(1);
7957 SDLoc dl(Op);
7958 EVT VT = Op.getValueType();
7959 EVT Op1VT = V1.getValueType();
7960 EVT Op2VT = V2.getValueType();
7961 unsigned NumElts = VT.getVectorNumElements();
7963 assert(Op1VT == Op2VT && "Operand types don't match!");
7964 assert(VT.getScalarSizeInBits() == 1 &&
7965 "Unexpected custom CONCAT_VECTORS lowering");
7966 assert(ST->hasMVEIntegerOps() &&
7967 "CONCAT_VECTORS lowering only supported for MVE");
7969 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7970 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7972 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7973 // promoted to v8i16, etc.
7975 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7977 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7978 // to be the right size for the destination. For example, if Op1 is v4i1 then
7979 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7980 // which when promoted is v8i16. That means each i32 element from Op1 needs
7981 // truncating to i16 and inserting in the result.
7982 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7983 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7984 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7985 EVT NewVT = NewV.getValueType();
7986 EVT ConcatVT = ConVec.getValueType();
7987 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7988 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7989 DAG.getIntPtrConstant(i, dl));
7990 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7991 DAG.getConstant(j, dl, MVT::i32));
7993 return ConVec;
7995 unsigned j = 0;
7996 ConVec = ExractInto(NewV1, ConVec, j);
7997 ConVec = ExractInto(NewV2, ConVec, j);
7999 // Now return the result of comparing the subvector with zero,
8000 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8001 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8002 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8005 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8006 const ARMSubtarget *ST) {
8007 EVT VT = Op->getValueType(0);
8008 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8009 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8011 // The only time a CONCAT_VECTORS operation can have legal types is when
8012 // two 64-bit vectors are concatenated to a 128-bit vector.
8013 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8014 "unexpected CONCAT_VECTORS");
8015 SDLoc dl(Op);
8016 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8017 SDValue Op0 = Op.getOperand(0);
8018 SDValue Op1 = Op.getOperand(1);
8019 if (!Op0.isUndef())
8020 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8021 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8022 DAG.getIntPtrConstant(0, dl));
8023 if (!Op1.isUndef())
8024 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8025 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8026 DAG.getIntPtrConstant(1, dl));
8027 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8030 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8031 const ARMSubtarget *ST) {
8032 SDValue V1 = Op.getOperand(0);
8033 SDValue V2 = Op.getOperand(1);
8034 SDLoc dl(Op);
8035 EVT VT = Op.getValueType();
8036 EVT Op1VT = V1.getValueType();
8037 unsigned NumElts = VT.getVectorNumElements();
8038 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8040 assert(VT.getScalarSizeInBits() == 1 &&
8041 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8042 assert(ST->hasMVEIntegerOps() &&
8043 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8045 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8047 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8048 // promoted to v8i16, etc.
8050 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8052 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8053 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8054 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8055 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8056 DAG.getIntPtrConstant(i, dl));
8057 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8058 DAG.getConstant(j, dl, MVT::i32));
8061 // Now return the result of comparing the subvector with zero,
8062 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8063 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8064 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8067 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8068 /// element has been zero/sign-extended, depending on the isSigned parameter,
8069 /// from an integer type half its size.
8070 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8071 bool isSigned) {
8072 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8073 EVT VT = N->getValueType(0);
8074 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8075 SDNode *BVN = N->getOperand(0).getNode();
8076 if (BVN->getValueType(0) != MVT::v4i32 ||
8077 BVN->getOpcode() != ISD::BUILD_VECTOR)
8078 return false;
8079 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8080 unsigned HiElt = 1 - LoElt;
8081 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8082 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8083 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8084 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8085 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8086 return false;
8087 if (isSigned) {
8088 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8089 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8090 return true;
8091 } else {
8092 if (Hi0->isNullValue() && Hi1->isNullValue())
8093 return true;
8095 return false;
8098 if (N->getOpcode() != ISD::BUILD_VECTOR)
8099 return false;
8101 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8102 SDNode *Elt = N->getOperand(i).getNode();
8103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8104 unsigned EltSize = VT.getScalarSizeInBits();
8105 unsigned HalfSize = EltSize / 2;
8106 if (isSigned) {
8107 if (!isIntN(HalfSize, C->getSExtValue()))
8108 return false;
8109 } else {
8110 if (!isUIntN(HalfSize, C->getZExtValue()))
8111 return false;
8113 continue;
8115 return false;
8118 return true;
8121 /// isSignExtended - Check if a node is a vector value that is sign-extended
8122 /// or a constant BUILD_VECTOR with sign-extended elements.
8123 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8124 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8125 return true;
8126 if (isExtendedBUILD_VECTOR(N, DAG, true))
8127 return true;
8128 return false;
8131 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8132 /// or a constant BUILD_VECTOR with zero-extended elements.
8133 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8134 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8135 return true;
8136 if (isExtendedBUILD_VECTOR(N, DAG, false))
8137 return true;
8138 return false;
8141 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8142 if (OrigVT.getSizeInBits() >= 64)
8143 return OrigVT;
8145 assert(OrigVT.isSimple() && "Expecting a simple value type");
8147 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8148 switch (OrigSimpleTy) {
8149 default: llvm_unreachable("Unexpected Vector Type");
8150 case MVT::v2i8:
8151 case MVT::v2i16:
8152 return MVT::v2i32;
8153 case MVT::v4i8:
8154 return MVT::v4i16;
8158 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8159 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8160 /// We insert the required extension here to get the vector to fill a D register.
8161 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8162 const EVT &OrigTy,
8163 const EVT &ExtTy,
8164 unsigned ExtOpcode) {
8165 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8166 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8167 // 64-bits we need to insert a new extension so that it will be 64-bits.
8168 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8169 if (OrigTy.getSizeInBits() >= 64)
8170 return N;
8172 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8173 EVT NewVT = getExtensionTo64Bits(OrigTy);
8175 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8178 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8179 /// does not do any sign/zero extension. If the original vector is less
8180 /// than 64 bits, an appropriate extension will be added after the load to
8181 /// reach a total size of 64 bits. We have to add the extension separately
8182 /// because ARM does not have a sign/zero extending load for vectors.
8183 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8184 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8186 // The load already has the right type.
8187 if (ExtendedTy == LD->getMemoryVT())
8188 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8189 LD->getBasePtr(), LD->getPointerInfo(),
8190 LD->getAlignment(), LD->getMemOperand()->getFlags());
8192 // We need to create a zextload/sextload. We cannot just create a load
8193 // followed by a zext/zext node because LowerMUL is also run during normal
8194 // operation legalization where we can't create illegal types.
8195 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8196 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8197 LD->getMemoryVT(), LD->getAlignment(),
8198 LD->getMemOperand()->getFlags());
8201 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8202 /// extending load, or BUILD_VECTOR with extended elements, return the
8203 /// unextended value. The unextended vector should be 64 bits so that it can
8204 /// be used as an operand to a VMULL instruction. If the original vector size
8205 /// before extension is less than 64 bits we add a an extension to resize
8206 /// the vector to 64 bits.
8207 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8208 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8209 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8210 N->getOperand(0)->getValueType(0),
8211 N->getValueType(0),
8212 N->getOpcode());
8214 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8215 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8216 "Expected extending load");
8218 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8219 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8220 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8221 SDValue extLoad =
8222 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8223 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8225 return newLoad;
8228 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8229 // have been legalized as a BITCAST from v4i32.
8230 if (N->getOpcode() == ISD::BITCAST) {
8231 SDNode *BVN = N->getOperand(0).getNode();
8232 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8233 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8234 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8235 return DAG.getBuildVector(
8236 MVT::v2i32, SDLoc(N),
8237 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8239 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8240 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8241 EVT VT = N->getValueType(0);
8242 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8243 unsigned NumElts = VT.getVectorNumElements();
8244 MVT TruncVT = MVT::getIntegerVT(EltSize);
8245 SmallVector<SDValue, 8> Ops;
8246 SDLoc dl(N);
8247 for (unsigned i = 0; i != NumElts; ++i) {
8248 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8249 const APInt &CInt = C->getAPIntValue();
8250 // Element types smaller than 32 bits are not legal, so use i32 elements.
8251 // The values are implicitly truncated so sext vs. zext doesn't matter.
8252 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8254 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8257 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8258 unsigned Opcode = N->getOpcode();
8259 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8260 SDNode *N0 = N->getOperand(0).getNode();
8261 SDNode *N1 = N->getOperand(1).getNode();
8262 return N0->hasOneUse() && N1->hasOneUse() &&
8263 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8265 return false;
8268 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8269 unsigned Opcode = N->getOpcode();
8270 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8271 SDNode *N0 = N->getOperand(0).getNode();
8272 SDNode *N1 = N->getOperand(1).getNode();
8273 return N0->hasOneUse() && N1->hasOneUse() &&
8274 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8276 return false;
8279 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8280 // Multiplications are only custom-lowered for 128-bit vectors so that
8281 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8282 EVT VT = Op.getValueType();
8283 assert(VT.is128BitVector() && VT.isInteger() &&
8284 "unexpected type for custom-lowering ISD::MUL");
8285 SDNode *N0 = Op.getOperand(0).getNode();
8286 SDNode *N1 = Op.getOperand(1).getNode();
8287 unsigned NewOpc = 0;
8288 bool isMLA = false;
8289 bool isN0SExt = isSignExtended(N0, DAG);
8290 bool isN1SExt = isSignExtended(N1, DAG);
8291 if (isN0SExt && isN1SExt)
8292 NewOpc = ARMISD::VMULLs;
8293 else {
8294 bool isN0ZExt = isZeroExtended(N0, DAG);
8295 bool isN1ZExt = isZeroExtended(N1, DAG);
8296 if (isN0ZExt && isN1ZExt)
8297 NewOpc = ARMISD::VMULLu;
8298 else if (isN1SExt || isN1ZExt) {
8299 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8300 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8301 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8302 NewOpc = ARMISD::VMULLs;
8303 isMLA = true;
8304 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8305 NewOpc = ARMISD::VMULLu;
8306 isMLA = true;
8307 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8308 std::swap(N0, N1);
8309 NewOpc = ARMISD::VMULLu;
8310 isMLA = true;
8314 if (!NewOpc) {
8315 if (VT == MVT::v2i64)
8316 // Fall through to expand this. It is not legal.
8317 return SDValue();
8318 else
8319 // Other vector multiplications are legal.
8320 return Op;
8324 // Legalize to a VMULL instruction.
8325 SDLoc DL(Op);
8326 SDValue Op0;
8327 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8328 if (!isMLA) {
8329 Op0 = SkipExtensionForVMULL(N0, DAG);
8330 assert(Op0.getValueType().is64BitVector() &&
8331 Op1.getValueType().is64BitVector() &&
8332 "unexpected types for extended operands to VMULL");
8333 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8336 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8337 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8338 // vmull q0, d4, d6
8339 // vmlal q0, d5, d6
8340 // is faster than
8341 // vaddl q0, d4, d5
8342 // vmovl q1, d6
8343 // vmul q0, q0, q1
8344 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8345 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8346 EVT Op1VT = Op1.getValueType();
8347 return DAG.getNode(N0->getOpcode(), DL, VT,
8348 DAG.getNode(NewOpc, DL, VT,
8349 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8350 DAG.getNode(NewOpc, DL, VT,
8351 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8354 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8355 SelectionDAG &DAG) {
8356 // TODO: Should this propagate fast-math-flags?
8358 // Convert to float
8359 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8360 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8361 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8362 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8363 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8364 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8365 // Get reciprocal estimate.
8366 // float4 recip = vrecpeq_f32(yf);
8367 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8368 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8370 // Because char has a smaller range than uchar, we can actually get away
8371 // without any newton steps. This requires that we use a weird bias
8372 // of 0xb000, however (again, this has been exhaustively tested).
8373 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8374 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8375 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8376 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8377 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8378 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8379 // Convert back to short.
8380 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8381 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8382 return X;
8385 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8386 SelectionDAG &DAG) {
8387 // TODO: Should this propagate fast-math-flags?
8389 SDValue N2;
8390 // Convert to float.
8391 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8392 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8393 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8394 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8395 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8396 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8398 // Use reciprocal estimate and one refinement step.
8399 // float4 recip = vrecpeq_f32(yf);
8400 // recip *= vrecpsq_f32(yf, recip);
8401 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8402 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8403 N1);
8404 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8405 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8406 N1, N2);
8407 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8408 // Because short has a smaller range than ushort, we can actually get away
8409 // with only a single newton step. This requires that we use a weird bias
8410 // of 89, however (again, this has been exhaustively tested).
8411 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8412 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8413 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8414 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8415 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8416 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8417 // Convert back to integer and return.
8418 // return vmovn_s32(vcvt_s32_f32(result));
8419 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8420 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8421 return N0;
8424 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8425 const ARMSubtarget *ST) {
8426 EVT VT = Op.getValueType();
8427 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8428 "unexpected type for custom-lowering ISD::SDIV");
8430 SDLoc dl(Op);
8431 SDValue N0 = Op.getOperand(0);
8432 SDValue N1 = Op.getOperand(1);
8433 SDValue N2, N3;
8435 if (VT == MVT::v8i8) {
8436 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8437 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8439 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8440 DAG.getIntPtrConstant(4, dl));
8441 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8442 DAG.getIntPtrConstant(4, dl));
8443 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8444 DAG.getIntPtrConstant(0, dl));
8445 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8446 DAG.getIntPtrConstant(0, dl));
8448 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8449 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8451 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8452 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8454 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8455 return N0;
8457 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8460 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8461 const ARMSubtarget *ST) {
8462 // TODO: Should this propagate fast-math-flags?
8463 EVT VT = Op.getValueType();
8464 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8465 "unexpected type for custom-lowering ISD::UDIV");
8467 SDLoc dl(Op);
8468 SDValue N0 = Op.getOperand(0);
8469 SDValue N1 = Op.getOperand(1);
8470 SDValue N2, N3;
8472 if (VT == MVT::v8i8) {
8473 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8474 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8476 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8477 DAG.getIntPtrConstant(4, dl));
8478 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8479 DAG.getIntPtrConstant(4, dl));
8480 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8481 DAG.getIntPtrConstant(0, dl));
8482 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8483 DAG.getIntPtrConstant(0, dl));
8485 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8486 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8488 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8489 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8491 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8492 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8493 MVT::i32),
8494 N0);
8495 return N0;
8498 // v4i16 sdiv ... Convert to float.
8499 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8500 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8501 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8502 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8503 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8504 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8506 // Use reciprocal estimate and two refinement steps.
8507 // float4 recip = vrecpeq_f32(yf);
8508 // recip *= vrecpsq_f32(yf, recip);
8509 // recip *= vrecpsq_f32(yf, recip);
8510 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8511 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8512 BN1);
8513 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8514 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8515 BN1, N2);
8516 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8517 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8518 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8519 BN1, N2);
8520 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8521 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8522 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8523 // and that it will never cause us to return an answer too large).
8524 // float4 result = as_float4(as_int4(xf*recip) + 2);
8525 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8526 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8527 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8528 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8529 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8530 // Convert back to integer and return.
8531 // return vmovn_u32(vcvt_s32_f32(result));
8532 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8533 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8534 return N0;
8537 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8538 SDNode *N = Op.getNode();
8539 EVT VT = N->getValueType(0);
8540 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8542 SDValue Carry = Op.getOperand(2);
8544 SDLoc DL(Op);
8546 SDValue Result;
8547 if (Op.getOpcode() == ISD::ADDCARRY) {
8548 // This converts the boolean value carry into the carry flag.
8549 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8551 // Do the addition proper using the carry flag we wanted.
8552 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8553 Op.getOperand(1), Carry);
8555 // Now convert the carry flag into a boolean value.
8556 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8557 } else {
8558 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8559 // have to invert the carry first.
8560 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8561 DAG.getConstant(1, DL, MVT::i32), Carry);
8562 // This converts the boolean value carry into the carry flag.
8563 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8565 // Do the subtraction proper using the carry flag we wanted.
8566 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8567 Op.getOperand(1), Carry);
8569 // Now convert the carry flag into a boolean value.
8570 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8571 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8572 // by ISD::SUBCARRY, so compute 1 - C.
8573 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8574 DAG.getConstant(1, DL, MVT::i32), Carry);
8577 // Return both values.
8578 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8581 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8582 assert(Subtarget->isTargetDarwin());
8584 // For iOS, we want to call an alternative entry point: __sincos_stret,
8585 // return values are passed via sret.
8586 SDLoc dl(Op);
8587 SDValue Arg = Op.getOperand(0);
8588 EVT ArgVT = Arg.getValueType();
8589 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8590 auto PtrVT = getPointerTy(DAG.getDataLayout());
8592 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8595 // Pair of floats / doubles used to pass the result.
8596 Type *RetTy = StructType::get(ArgTy, ArgTy);
8597 auto &DL = DAG.getDataLayout();
8599 ArgListTy Args;
8600 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8601 SDValue SRet;
8602 if (ShouldUseSRet) {
8603 // Create stack object for sret.
8604 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8605 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8606 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8607 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8609 ArgListEntry Entry;
8610 Entry.Node = SRet;
8611 Entry.Ty = RetTy->getPointerTo();
8612 Entry.IsSExt = false;
8613 Entry.IsZExt = false;
8614 Entry.IsSRet = true;
8615 Args.push_back(Entry);
8616 RetTy = Type::getVoidTy(*DAG.getContext());
8619 ArgListEntry Entry;
8620 Entry.Node = Arg;
8621 Entry.Ty = ArgTy;
8622 Entry.IsSExt = false;
8623 Entry.IsZExt = false;
8624 Args.push_back(Entry);
8626 RTLIB::Libcall LC =
8627 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8628 const char *LibcallName = getLibcallName(LC);
8629 CallingConv::ID CC = getLibcallCallingConv(LC);
8630 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8632 TargetLowering::CallLoweringInfo CLI(DAG);
8633 CLI.setDebugLoc(dl)
8634 .setChain(DAG.getEntryNode())
8635 .setCallee(CC, RetTy, Callee, std::move(Args))
8636 .setDiscardResult(ShouldUseSRet);
8637 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8639 if (!ShouldUseSRet)
8640 return CallResult.first;
8642 SDValue LoadSin =
8643 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8645 // Address of cos field.
8646 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8647 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8648 SDValue LoadCos =
8649 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8651 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8652 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8653 LoadSin.getValue(0), LoadCos.getValue(0));
8656 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8657 bool Signed,
8658 SDValue &Chain) const {
8659 EVT VT = Op.getValueType();
8660 assert((VT == MVT::i32 || VT == MVT::i64) &&
8661 "unexpected type for custom lowering DIV");
8662 SDLoc dl(Op);
8664 const auto &DL = DAG.getDataLayout();
8665 const auto &TLI = DAG.getTargetLoweringInfo();
8667 const char *Name = nullptr;
8668 if (Signed)
8669 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8670 else
8671 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8673 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8675 ARMTargetLowering::ArgListTy Args;
8677 for (auto AI : {1, 0}) {
8678 ArgListEntry Arg;
8679 Arg.Node = Op.getOperand(AI);
8680 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8681 Args.push_back(Arg);
8684 CallLoweringInfo CLI(DAG);
8685 CLI.setDebugLoc(dl)
8686 .setChain(Chain)
8687 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8688 ES, std::move(Args));
8690 return LowerCallTo(CLI).first;
8693 // This is a code size optimisation: return the original SDIV node to
8694 // DAGCombiner when we don't want to expand SDIV into a sequence of
8695 // instructions, and an empty node otherwise which will cause the
8696 // SDIV to be expanded in DAGCombine.
8697 SDValue
8698 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8699 SelectionDAG &DAG,
8700 SmallVectorImpl<SDNode *> &Created) const {
8701 // TODO: Support SREM
8702 if (N->getOpcode() != ISD::SDIV)
8703 return SDValue();
8705 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8706 const bool MinSize = ST.hasMinSize();
8707 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8708 : ST.hasDivideInARMMode();
8710 // Don't touch vector types; rewriting this may lead to scalarizing
8711 // the int divs.
8712 if (N->getOperand(0).getValueType().isVector())
8713 return SDValue();
8715 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8716 // hwdiv support for this to be really profitable.
8717 if (!(MinSize && HasDivide))
8718 return SDValue();
8720 // ARM mode is a bit simpler than Thumb: we can handle large power
8721 // of 2 immediates with 1 mov instruction; no further checks required,
8722 // just return the sdiv node.
8723 if (!ST.isThumb())
8724 return SDValue(N, 0);
8726 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8727 // and thus lose the code size benefits of a MOVS that requires only 2.
8728 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8729 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8730 if (Divisor.sgt(128))
8731 return SDValue();
8733 return SDValue(N, 0);
8736 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8737 bool Signed) const {
8738 assert(Op.getValueType() == MVT::i32 &&
8739 "unexpected type for custom lowering DIV");
8740 SDLoc dl(Op);
8742 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8743 DAG.getEntryNode(), Op.getOperand(1));
8745 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8748 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8749 SDLoc DL(N);
8750 SDValue Op = N->getOperand(1);
8751 if (N->getValueType(0) == MVT::i32)
8752 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8753 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8754 DAG.getConstant(0, DL, MVT::i32));
8755 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8756 DAG.getConstant(1, DL, MVT::i32));
8757 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8758 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8761 void ARMTargetLowering::ExpandDIV_Windows(
8762 SDValue Op, SelectionDAG &DAG, bool Signed,
8763 SmallVectorImpl<SDValue> &Results) const {
8764 const auto &DL = DAG.getDataLayout();
8765 const auto &TLI = DAG.getTargetLoweringInfo();
8767 assert(Op.getValueType() == MVT::i64 &&
8768 "unexpected type for custom lowering DIV");
8769 SDLoc dl(Op);
8771 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8773 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8775 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8776 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8777 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8778 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8780 Results.push_back(Lower);
8781 Results.push_back(Upper);
8784 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8785 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8786 // Acquire/Release load/store is not legal for targets without a dmb or
8787 // equivalent available.
8788 return SDValue();
8790 // Monotonic load/store is legal for all targets.
8791 return Op;
8794 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8795 SmallVectorImpl<SDValue> &Results,
8796 SelectionDAG &DAG,
8797 const ARMSubtarget *Subtarget) {
8798 SDLoc DL(N);
8799 // Under Power Management extensions, the cycle-count is:
8800 // mrc p15, #0, <Rt>, c9, c13, #0
8801 SDValue Ops[] = { N->getOperand(0), // Chain
8802 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8803 DAG.getConstant(15, DL, MVT::i32),
8804 DAG.getConstant(0, DL, MVT::i32),
8805 DAG.getConstant(9, DL, MVT::i32),
8806 DAG.getConstant(13, DL, MVT::i32),
8807 DAG.getConstant(0, DL, MVT::i32)
8810 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8811 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8812 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8813 DAG.getConstant(0, DL, MVT::i32)));
8814 Results.push_back(Cycles32.getValue(1));
8817 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8818 SDLoc dl(V.getNode());
8819 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8820 SDValue VHi = DAG.getAnyExtOrTrunc(
8821 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8822 dl, MVT::i32);
8823 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8824 if (isBigEndian)
8825 std::swap (VLo, VHi);
8826 SDValue RegClass =
8827 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8828 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8829 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8830 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8831 return SDValue(
8832 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8835 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8836 SmallVectorImpl<SDValue> & Results,
8837 SelectionDAG &DAG) {
8838 assert(N->getValueType(0) == MVT::i64 &&
8839 "AtomicCmpSwap on types less than 64 should be legal");
8840 SDValue Ops[] = {N->getOperand(1),
8841 createGPRPairNode(DAG, N->getOperand(2)),
8842 createGPRPairNode(DAG, N->getOperand(3)),
8843 N->getOperand(0)};
8844 SDNode *CmpSwap = DAG.getMachineNode(
8845 ARM::CMP_SWAP_64, SDLoc(N),
8846 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8848 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8849 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8851 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8853 Results.push_back(
8854 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8855 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8856 Results.push_back(
8857 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8858 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8859 Results.push_back(SDValue(CmpSwap, 2));
8862 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8863 SelectionDAG &DAG) {
8864 const auto &TLI = DAG.getTargetLoweringInfo();
8866 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8867 "Custom lowering is MSVCRT specific!");
8869 SDLoc dl(Op);
8870 SDValue Val = Op.getOperand(0);
8871 MVT Ty = Val->getSimpleValueType(0);
8872 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8873 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8874 TLI.getPointerTy(DAG.getDataLayout()));
8876 TargetLowering::ArgListTy Args;
8877 TargetLowering::ArgListEntry Entry;
8879 Entry.Node = Val;
8880 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8881 Entry.IsZExt = true;
8882 Args.push_back(Entry);
8884 Entry.Node = Exponent;
8885 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8886 Entry.IsZExt = true;
8887 Args.push_back(Entry);
8889 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8891 // In the in-chain to the call is the entry node If we are emitting a
8892 // tailcall, the chain will be mutated if the node has a non-entry input
8893 // chain.
8894 SDValue InChain = DAG.getEntryNode();
8895 SDValue TCChain = InChain;
8897 const Function &F = DAG.getMachineFunction().getFunction();
8898 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8899 F.getReturnType() == LCRTy;
8900 if (IsTC)
8901 InChain = TCChain;
8903 TargetLowering::CallLoweringInfo CLI(DAG);
8904 CLI.setDebugLoc(dl)
8905 .setChain(InChain)
8906 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8907 .setTailCall(IsTC);
8908 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8910 // Return the chain (the DAG root) if it is a tail call
8911 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8914 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8915 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8916 switch (Op.getOpcode()) {
8917 default: llvm_unreachable("Don't know how to custom lower this!");
8918 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8919 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8920 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8921 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8922 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8923 case ISD::SELECT: return LowerSELECT(Op, DAG);
8924 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8925 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8926 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8927 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8928 case ISD::VASTART: return LowerVASTART(Op, DAG);
8929 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8930 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8931 case ISD::SINT_TO_FP:
8932 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8933 case ISD::FP_TO_SINT:
8934 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8935 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8936 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8937 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8938 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8939 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8940 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8941 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
8942 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8943 Subtarget);
8944 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8945 case ISD::SHL:
8946 case ISD::SRL:
8947 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8948 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8949 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8950 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8951 case ISD::SRL_PARTS:
8952 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8953 case ISD::CTTZ:
8954 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8955 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8956 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8957 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8958 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8959 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8960 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8961 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8962 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8963 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8964 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8965 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8966 case ISD::MUL: return LowerMUL(Op, DAG);
8967 case ISD::SDIV:
8968 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8969 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8970 return LowerSDIV(Op, DAG, Subtarget);
8971 case ISD::UDIV:
8972 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8973 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8974 return LowerUDIV(Op, DAG, Subtarget);
8975 case ISD::ADDCARRY:
8976 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8977 case ISD::SADDO:
8978 case ISD::SSUBO:
8979 return LowerSignedALUO(Op, DAG);
8980 case ISD::UADDO:
8981 case ISD::USUBO:
8982 return LowerUnsignedALUO(Op, DAG);
8983 case ISD::ATOMIC_LOAD:
8984 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8985 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8986 case ISD::SDIVREM:
8987 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8988 case ISD::DYNAMIC_STACKALLOC:
8989 if (Subtarget->isTargetWindows())
8990 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8991 llvm_unreachable("Don't know how to custom lower this!");
8992 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8993 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8994 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8995 case ARMISD::WIN__DBZCHK: return SDValue();
8999 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9000 SelectionDAG &DAG) {
9001 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9002 unsigned Opc = 0;
9003 if (IntNo == Intrinsic::arm_smlald)
9004 Opc = ARMISD::SMLALD;
9005 else if (IntNo == Intrinsic::arm_smlaldx)
9006 Opc = ARMISD::SMLALDX;
9007 else if (IntNo == Intrinsic::arm_smlsld)
9008 Opc = ARMISD::SMLSLD;
9009 else if (IntNo == Intrinsic::arm_smlsldx)
9010 Opc = ARMISD::SMLSLDX;
9011 else
9012 return;
9014 SDLoc dl(N);
9015 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9016 N->getOperand(3),
9017 DAG.getConstant(0, dl, MVT::i32));
9018 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9019 N->getOperand(3),
9020 DAG.getConstant(1, dl, MVT::i32));
9022 SDValue LongMul = DAG.getNode(Opc, dl,
9023 DAG.getVTList(MVT::i32, MVT::i32),
9024 N->getOperand(1), N->getOperand(2),
9025 Lo, Hi);
9026 Results.push_back(LongMul.getValue(0));
9027 Results.push_back(LongMul.getValue(1));
9030 /// ReplaceNodeResults - Replace the results of node with an illegal result
9031 /// type with new values built out of custom code.
9032 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9033 SmallVectorImpl<SDValue> &Results,
9034 SelectionDAG &DAG) const {
9035 SDValue Res;
9036 switch (N->getOpcode()) {
9037 default:
9038 llvm_unreachable("Don't know how to custom expand this!");
9039 case ISD::READ_REGISTER:
9040 ExpandREAD_REGISTER(N, Results, DAG);
9041 break;
9042 case ISD::BITCAST:
9043 Res = ExpandBITCAST(N, DAG, Subtarget);
9044 break;
9045 case ISD::SRL:
9046 case ISD::SRA:
9047 case ISD::SHL:
9048 Res = Expand64BitShift(N, DAG, Subtarget);
9049 break;
9050 case ISD::SREM:
9051 case ISD::UREM:
9052 Res = LowerREM(N, DAG);
9053 break;
9054 case ISD::SDIVREM:
9055 case ISD::UDIVREM:
9056 Res = LowerDivRem(SDValue(N, 0), DAG);
9057 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9058 Results.push_back(Res.getValue(0));
9059 Results.push_back(Res.getValue(1));
9060 return;
9061 case ISD::READCYCLECOUNTER:
9062 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9063 return;
9064 case ISD::UDIV:
9065 case ISD::SDIV:
9066 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9067 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9068 Results);
9069 case ISD::ATOMIC_CMP_SWAP:
9070 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9071 return;
9072 case ISD::INTRINSIC_WO_CHAIN:
9073 return ReplaceLongIntrinsic(N, Results, DAG);
9074 case ISD::ABS:
9075 lowerABS(N, Results, DAG);
9076 return ;
9079 if (Res.getNode())
9080 Results.push_back(Res);
9083 //===----------------------------------------------------------------------===//
9084 // ARM Scheduler Hooks
9085 //===----------------------------------------------------------------------===//
9087 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9088 /// registers the function context.
9089 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9090 MachineBasicBlock *MBB,
9091 MachineBasicBlock *DispatchBB,
9092 int FI) const {
9093 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9094 "ROPI/RWPI not currently supported with SjLj");
9095 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9096 DebugLoc dl = MI.getDebugLoc();
9097 MachineFunction *MF = MBB->getParent();
9098 MachineRegisterInfo *MRI = &MF->getRegInfo();
9099 MachineConstantPool *MCP = MF->getConstantPool();
9100 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9101 const Function &F = MF->getFunction();
9103 bool isThumb = Subtarget->isThumb();
9104 bool isThumb2 = Subtarget->isThumb2();
9106 unsigned PCLabelId = AFI->createPICLabelUId();
9107 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9108 ARMConstantPoolValue *CPV =
9109 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9110 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9112 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9113 : &ARM::GPRRegClass;
9115 // Grab constant pool and fixed stack memory operands.
9116 MachineMemOperand *CPMMO =
9117 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9118 MachineMemOperand::MOLoad, 4, 4);
9120 MachineMemOperand *FIMMOSt =
9121 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9122 MachineMemOperand::MOStore, 4, 4);
9124 // Load the address of the dispatch MBB into the jump buffer.
9125 if (isThumb2) {
9126 // Incoming value: jbuf
9127 // ldr.n r5, LCPI1_1
9128 // orr r5, r5, #1
9129 // add r5, pc
9130 // str r5, [$jbuf, #+4] ; &jbuf[1]
9131 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9132 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9133 .addConstantPoolIndex(CPI)
9134 .addMemOperand(CPMMO)
9135 .add(predOps(ARMCC::AL));
9136 // Set the low bit because of thumb mode.
9137 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9138 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9139 .addReg(NewVReg1, RegState::Kill)
9140 .addImm(0x01)
9141 .add(predOps(ARMCC::AL))
9142 .add(condCodeOp());
9143 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9144 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9145 .addReg(NewVReg2, RegState::Kill)
9146 .addImm(PCLabelId);
9147 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9148 .addReg(NewVReg3, RegState::Kill)
9149 .addFrameIndex(FI)
9150 .addImm(36) // &jbuf[1] :: pc
9151 .addMemOperand(FIMMOSt)
9152 .add(predOps(ARMCC::AL));
9153 } else if (isThumb) {
9154 // Incoming value: jbuf
9155 // ldr.n r1, LCPI1_4
9156 // add r1, pc
9157 // mov r2, #1
9158 // orrs r1, r2
9159 // add r2, $jbuf, #+4 ; &jbuf[1]
9160 // str r1, [r2]
9161 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9162 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9163 .addConstantPoolIndex(CPI)
9164 .addMemOperand(CPMMO)
9165 .add(predOps(ARMCC::AL));
9166 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9167 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9168 .addReg(NewVReg1, RegState::Kill)
9169 .addImm(PCLabelId);
9170 // Set the low bit because of thumb mode.
9171 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9172 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9173 .addReg(ARM::CPSR, RegState::Define)
9174 .addImm(1)
9175 .add(predOps(ARMCC::AL));
9176 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9177 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9178 .addReg(ARM::CPSR, RegState::Define)
9179 .addReg(NewVReg2, RegState::Kill)
9180 .addReg(NewVReg3, RegState::Kill)
9181 .add(predOps(ARMCC::AL));
9182 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9183 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9184 .addFrameIndex(FI)
9185 .addImm(36); // &jbuf[1] :: pc
9186 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9187 .addReg(NewVReg4, RegState::Kill)
9188 .addReg(NewVReg5, RegState::Kill)
9189 .addImm(0)
9190 .addMemOperand(FIMMOSt)
9191 .add(predOps(ARMCC::AL));
9192 } else {
9193 // Incoming value: jbuf
9194 // ldr r1, LCPI1_1
9195 // add r1, pc, r1
9196 // str r1, [$jbuf, #+4] ; &jbuf[1]
9197 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9198 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9199 .addConstantPoolIndex(CPI)
9200 .addImm(0)
9201 .addMemOperand(CPMMO)
9202 .add(predOps(ARMCC::AL));
9203 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9204 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9205 .addReg(NewVReg1, RegState::Kill)
9206 .addImm(PCLabelId)
9207 .add(predOps(ARMCC::AL));
9208 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9209 .addReg(NewVReg2, RegState::Kill)
9210 .addFrameIndex(FI)
9211 .addImm(36) // &jbuf[1] :: pc
9212 .addMemOperand(FIMMOSt)
9213 .add(predOps(ARMCC::AL));
9217 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9218 MachineBasicBlock *MBB) const {
9219 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9220 DebugLoc dl = MI.getDebugLoc();
9221 MachineFunction *MF = MBB->getParent();
9222 MachineRegisterInfo *MRI = &MF->getRegInfo();
9223 MachineFrameInfo &MFI = MF->getFrameInfo();
9224 int FI = MFI.getFunctionContextIndex();
9226 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9227 : &ARM::GPRnopcRegClass;
9229 // Get a mapping of the call site numbers to all of the landing pads they're
9230 // associated with.
9231 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9232 unsigned MaxCSNum = 0;
9233 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9234 ++BB) {
9235 if (!BB->isEHPad()) continue;
9237 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9238 // pad.
9239 for (MachineBasicBlock::iterator
9240 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9241 if (!II->isEHLabel()) continue;
9243 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9244 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9246 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9247 for (SmallVectorImpl<unsigned>::iterator
9248 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9249 CSI != CSE; ++CSI) {
9250 CallSiteNumToLPad[*CSI].push_back(&*BB);
9251 MaxCSNum = std::max(MaxCSNum, *CSI);
9253 break;
9257 // Get an ordered list of the machine basic blocks for the jump table.
9258 std::vector<MachineBasicBlock*> LPadList;
9259 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9260 LPadList.reserve(CallSiteNumToLPad.size());
9261 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9262 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9263 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9264 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9265 LPadList.push_back(*II);
9266 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9270 assert(!LPadList.empty() &&
9271 "No landing pad destinations for the dispatch jump table!");
9273 // Create the jump table and associated information.
9274 MachineJumpTableInfo *JTI =
9275 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9276 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9278 // Create the MBBs for the dispatch code.
9280 // Shove the dispatch's address into the return slot in the function context.
9281 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9282 DispatchBB->setIsEHPad();
9284 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9285 unsigned trap_opcode;
9286 if (Subtarget->isThumb())
9287 trap_opcode = ARM::tTRAP;
9288 else
9289 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9291 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9292 DispatchBB->addSuccessor(TrapBB);
9294 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9295 DispatchBB->addSuccessor(DispContBB);
9297 // Insert and MBBs.
9298 MF->insert(MF->end(), DispatchBB);
9299 MF->insert(MF->end(), DispContBB);
9300 MF->insert(MF->end(), TrapBB);
9302 // Insert code into the entry block that creates and registers the function
9303 // context.
9304 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9306 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9307 MachinePointerInfo::getFixedStack(*MF, FI),
9308 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9310 MachineInstrBuilder MIB;
9311 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9313 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9314 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9316 // Add a register mask with no preserved registers. This results in all
9317 // registers being marked as clobbered. This can't work if the dispatch block
9318 // is in a Thumb1 function and is linked with ARM code which uses the FP
9319 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9320 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9322 bool IsPositionIndependent = isPositionIndependent();
9323 unsigned NumLPads = LPadList.size();
9324 if (Subtarget->isThumb2()) {
9325 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9326 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9327 .addFrameIndex(FI)
9328 .addImm(4)
9329 .addMemOperand(FIMMOLd)
9330 .add(predOps(ARMCC::AL));
9332 if (NumLPads < 256) {
9333 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9334 .addReg(NewVReg1)
9335 .addImm(LPadList.size())
9336 .add(predOps(ARMCC::AL));
9337 } else {
9338 Register VReg1 = MRI->createVirtualRegister(TRC);
9339 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9340 .addImm(NumLPads & 0xFFFF)
9341 .add(predOps(ARMCC::AL));
9343 unsigned VReg2 = VReg1;
9344 if ((NumLPads & 0xFFFF0000) != 0) {
9345 VReg2 = MRI->createVirtualRegister(TRC);
9346 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9347 .addReg(VReg1)
9348 .addImm(NumLPads >> 16)
9349 .add(predOps(ARMCC::AL));
9352 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9353 .addReg(NewVReg1)
9354 .addReg(VReg2)
9355 .add(predOps(ARMCC::AL));
9358 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9359 .addMBB(TrapBB)
9360 .addImm(ARMCC::HI)
9361 .addReg(ARM::CPSR);
9363 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9364 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9365 .addJumpTableIndex(MJTI)
9366 .add(predOps(ARMCC::AL));
9368 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9369 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9370 .addReg(NewVReg3, RegState::Kill)
9371 .addReg(NewVReg1)
9372 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9373 .add(predOps(ARMCC::AL))
9374 .add(condCodeOp());
9376 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9377 .addReg(NewVReg4, RegState::Kill)
9378 .addReg(NewVReg1)
9379 .addJumpTableIndex(MJTI);
9380 } else if (Subtarget->isThumb()) {
9381 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9382 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9383 .addFrameIndex(FI)
9384 .addImm(1)
9385 .addMemOperand(FIMMOLd)
9386 .add(predOps(ARMCC::AL));
9388 if (NumLPads < 256) {
9389 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9390 .addReg(NewVReg1)
9391 .addImm(NumLPads)
9392 .add(predOps(ARMCC::AL));
9393 } else {
9394 MachineConstantPool *ConstantPool = MF->getConstantPool();
9395 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9396 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9398 // MachineConstantPool wants an explicit alignment.
9399 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9400 if (Align == 0)
9401 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9402 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9404 Register VReg1 = MRI->createVirtualRegister(TRC);
9405 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9406 .addReg(VReg1, RegState::Define)
9407 .addConstantPoolIndex(Idx)
9408 .add(predOps(ARMCC::AL));
9409 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9410 .addReg(NewVReg1)
9411 .addReg(VReg1)
9412 .add(predOps(ARMCC::AL));
9415 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9416 .addMBB(TrapBB)
9417 .addImm(ARMCC::HI)
9418 .addReg(ARM::CPSR);
9420 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9421 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9422 .addReg(ARM::CPSR, RegState::Define)
9423 .addReg(NewVReg1)
9424 .addImm(2)
9425 .add(predOps(ARMCC::AL));
9427 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9428 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9429 .addJumpTableIndex(MJTI)
9430 .add(predOps(ARMCC::AL));
9432 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9433 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9434 .addReg(ARM::CPSR, RegState::Define)
9435 .addReg(NewVReg2, RegState::Kill)
9436 .addReg(NewVReg3)
9437 .add(predOps(ARMCC::AL));
9439 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9440 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9442 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9443 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9444 .addReg(NewVReg4, RegState::Kill)
9445 .addImm(0)
9446 .addMemOperand(JTMMOLd)
9447 .add(predOps(ARMCC::AL));
9449 unsigned NewVReg6 = NewVReg5;
9450 if (IsPositionIndependent) {
9451 NewVReg6 = MRI->createVirtualRegister(TRC);
9452 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9453 .addReg(ARM::CPSR, RegState::Define)
9454 .addReg(NewVReg5, RegState::Kill)
9455 .addReg(NewVReg3)
9456 .add(predOps(ARMCC::AL));
9459 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9460 .addReg(NewVReg6, RegState::Kill)
9461 .addJumpTableIndex(MJTI);
9462 } else {
9463 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9464 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9465 .addFrameIndex(FI)
9466 .addImm(4)
9467 .addMemOperand(FIMMOLd)
9468 .add(predOps(ARMCC::AL));
9470 if (NumLPads < 256) {
9471 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9472 .addReg(NewVReg1)
9473 .addImm(NumLPads)
9474 .add(predOps(ARMCC::AL));
9475 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9476 Register VReg1 = MRI->createVirtualRegister(TRC);
9477 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9478 .addImm(NumLPads & 0xFFFF)
9479 .add(predOps(ARMCC::AL));
9481 unsigned VReg2 = VReg1;
9482 if ((NumLPads & 0xFFFF0000) != 0) {
9483 VReg2 = MRI->createVirtualRegister(TRC);
9484 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9485 .addReg(VReg1)
9486 .addImm(NumLPads >> 16)
9487 .add(predOps(ARMCC::AL));
9490 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9491 .addReg(NewVReg1)
9492 .addReg(VReg2)
9493 .add(predOps(ARMCC::AL));
9494 } else {
9495 MachineConstantPool *ConstantPool = MF->getConstantPool();
9496 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9497 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9499 // MachineConstantPool wants an explicit alignment.
9500 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9501 if (Align == 0)
9502 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9503 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9505 Register VReg1 = MRI->createVirtualRegister(TRC);
9506 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9507 .addReg(VReg1, RegState::Define)
9508 .addConstantPoolIndex(Idx)
9509 .addImm(0)
9510 .add(predOps(ARMCC::AL));
9511 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9512 .addReg(NewVReg1)
9513 .addReg(VReg1, RegState::Kill)
9514 .add(predOps(ARMCC::AL));
9517 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9518 .addMBB(TrapBB)
9519 .addImm(ARMCC::HI)
9520 .addReg(ARM::CPSR);
9522 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9523 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9524 .addReg(NewVReg1)
9525 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9526 .add(predOps(ARMCC::AL))
9527 .add(condCodeOp());
9528 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9529 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9530 .addJumpTableIndex(MJTI)
9531 .add(predOps(ARMCC::AL));
9533 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9534 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9535 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9536 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9537 .addReg(NewVReg3, RegState::Kill)
9538 .addReg(NewVReg4)
9539 .addImm(0)
9540 .addMemOperand(JTMMOLd)
9541 .add(predOps(ARMCC::AL));
9543 if (IsPositionIndependent) {
9544 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9545 .addReg(NewVReg5, RegState::Kill)
9546 .addReg(NewVReg4)
9547 .addJumpTableIndex(MJTI);
9548 } else {
9549 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9550 .addReg(NewVReg5, RegState::Kill)
9551 .addJumpTableIndex(MJTI);
9555 // Add the jump table entries as successors to the MBB.
9556 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9557 for (std::vector<MachineBasicBlock*>::iterator
9558 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9559 MachineBasicBlock *CurMBB = *I;
9560 if (SeenMBBs.insert(CurMBB).second)
9561 DispContBB->addSuccessor(CurMBB);
9564 // N.B. the order the invoke BBs are processed in doesn't matter here.
9565 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9566 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9567 for (MachineBasicBlock *BB : InvokeBBs) {
9569 // Remove the landing pad successor from the invoke block and replace it
9570 // with the new dispatch block.
9571 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9572 BB->succ_end());
9573 while (!Successors.empty()) {
9574 MachineBasicBlock *SMBB = Successors.pop_back_val();
9575 if (SMBB->isEHPad()) {
9576 BB->removeSuccessor(SMBB);
9577 MBBLPads.push_back(SMBB);
9581 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9582 BB->normalizeSuccProbs();
9584 // Find the invoke call and mark all of the callee-saved registers as
9585 // 'implicit defined' so that they're spilled. This prevents code from
9586 // moving instructions to before the EH block, where they will never be
9587 // executed.
9588 for (MachineBasicBlock::reverse_iterator
9589 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9590 if (!II->isCall()) continue;
9592 DenseMap<unsigned, bool> DefRegs;
9593 for (MachineInstr::mop_iterator
9594 OI = II->operands_begin(), OE = II->operands_end();
9595 OI != OE; ++OI) {
9596 if (!OI->isReg()) continue;
9597 DefRegs[OI->getReg()] = true;
9600 MachineInstrBuilder MIB(*MF, &*II);
9602 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9603 unsigned Reg = SavedRegs[i];
9604 if (Subtarget->isThumb2() &&
9605 !ARM::tGPRRegClass.contains(Reg) &&
9606 !ARM::hGPRRegClass.contains(Reg))
9607 continue;
9608 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9609 continue;
9610 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9611 continue;
9612 if (!DefRegs[Reg])
9613 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9616 break;
9620 // Mark all former landing pads as non-landing pads. The dispatch is the only
9621 // landing pad now.
9622 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9623 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9624 (*I)->setIsEHPad(false);
9626 // The instruction is gone now.
9627 MI.eraseFromParent();
9630 static
9631 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9632 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9633 E = MBB->succ_end(); I != E; ++I)
9634 if (*I != Succ)
9635 return *I;
9636 llvm_unreachable("Expecting a BB with two successors!");
9639 /// Return the load opcode for a given load size. If load size >= 8,
9640 /// neon opcode will be returned.
9641 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9642 if (LdSize >= 8)
9643 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9644 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9645 if (IsThumb1)
9646 return LdSize == 4 ? ARM::tLDRi
9647 : LdSize == 2 ? ARM::tLDRHi
9648 : LdSize == 1 ? ARM::tLDRBi : 0;
9649 if (IsThumb2)
9650 return LdSize == 4 ? ARM::t2LDR_POST
9651 : LdSize == 2 ? ARM::t2LDRH_POST
9652 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9653 return LdSize == 4 ? ARM::LDR_POST_IMM
9654 : LdSize == 2 ? ARM::LDRH_POST
9655 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9658 /// Return the store opcode for a given store size. If store size >= 8,
9659 /// neon opcode will be returned.
9660 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9661 if (StSize >= 8)
9662 return StSize == 16 ? ARM::VST1q32wb_fixed
9663 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9664 if (IsThumb1)
9665 return StSize == 4 ? ARM::tSTRi
9666 : StSize == 2 ? ARM::tSTRHi
9667 : StSize == 1 ? ARM::tSTRBi : 0;
9668 if (IsThumb2)
9669 return StSize == 4 ? ARM::t2STR_POST
9670 : StSize == 2 ? ARM::t2STRH_POST
9671 : StSize == 1 ? ARM::t2STRB_POST : 0;
9672 return StSize == 4 ? ARM::STR_POST_IMM
9673 : StSize == 2 ? ARM::STRH_POST
9674 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9677 /// Emit a post-increment load operation with given size. The instructions
9678 /// will be added to BB at Pos.
9679 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9680 const TargetInstrInfo *TII, const DebugLoc &dl,
9681 unsigned LdSize, unsigned Data, unsigned AddrIn,
9682 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9683 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9684 assert(LdOpc != 0 && "Should have a load opcode");
9685 if (LdSize >= 8) {
9686 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9687 .addReg(AddrOut, RegState::Define)
9688 .addReg(AddrIn)
9689 .addImm(0)
9690 .add(predOps(ARMCC::AL));
9691 } else if (IsThumb1) {
9692 // load + update AddrIn
9693 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9694 .addReg(AddrIn)
9695 .addImm(0)
9696 .add(predOps(ARMCC::AL));
9697 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9698 .add(t1CondCodeOp())
9699 .addReg(AddrIn)
9700 .addImm(LdSize)
9701 .add(predOps(ARMCC::AL));
9702 } else if (IsThumb2) {
9703 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9704 .addReg(AddrOut, RegState::Define)
9705 .addReg(AddrIn)
9706 .addImm(LdSize)
9707 .add(predOps(ARMCC::AL));
9708 } else { // arm
9709 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9710 .addReg(AddrOut, RegState::Define)
9711 .addReg(AddrIn)
9712 .addReg(0)
9713 .addImm(LdSize)
9714 .add(predOps(ARMCC::AL));
9718 /// Emit a post-increment store operation with given size. The instructions
9719 /// will be added to BB at Pos.
9720 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9721 const TargetInstrInfo *TII, const DebugLoc &dl,
9722 unsigned StSize, unsigned Data, unsigned AddrIn,
9723 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9724 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9725 assert(StOpc != 0 && "Should have a store opcode");
9726 if (StSize >= 8) {
9727 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9728 .addReg(AddrIn)
9729 .addImm(0)
9730 .addReg(Data)
9731 .add(predOps(ARMCC::AL));
9732 } else if (IsThumb1) {
9733 // store + update AddrIn
9734 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9735 .addReg(Data)
9736 .addReg(AddrIn)
9737 .addImm(0)
9738 .add(predOps(ARMCC::AL));
9739 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9740 .add(t1CondCodeOp())
9741 .addReg(AddrIn)
9742 .addImm(StSize)
9743 .add(predOps(ARMCC::AL));
9744 } else if (IsThumb2) {
9745 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9746 .addReg(Data)
9747 .addReg(AddrIn)
9748 .addImm(StSize)
9749 .add(predOps(ARMCC::AL));
9750 } else { // arm
9751 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9752 .addReg(Data)
9753 .addReg(AddrIn)
9754 .addReg(0)
9755 .addImm(StSize)
9756 .add(predOps(ARMCC::AL));
9760 MachineBasicBlock *
9761 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9762 MachineBasicBlock *BB) const {
9763 // This pseudo instruction has 3 operands: dst, src, size
9764 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9765 // Otherwise, we will generate unrolled scalar copies.
9766 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9767 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9768 MachineFunction::iterator It = ++BB->getIterator();
9770 Register dest = MI.getOperand(0).getReg();
9771 Register src = MI.getOperand(1).getReg();
9772 unsigned SizeVal = MI.getOperand(2).getImm();
9773 unsigned Align = MI.getOperand(3).getImm();
9774 DebugLoc dl = MI.getDebugLoc();
9776 MachineFunction *MF = BB->getParent();
9777 MachineRegisterInfo &MRI = MF->getRegInfo();
9778 unsigned UnitSize = 0;
9779 const TargetRegisterClass *TRC = nullptr;
9780 const TargetRegisterClass *VecTRC = nullptr;
9782 bool IsThumb1 = Subtarget->isThumb1Only();
9783 bool IsThumb2 = Subtarget->isThumb2();
9784 bool IsThumb = Subtarget->isThumb();
9786 if (Align & 1) {
9787 UnitSize = 1;
9788 } else if (Align & 2) {
9789 UnitSize = 2;
9790 } else {
9791 // Check whether we can use NEON instructions.
9792 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9793 Subtarget->hasNEON()) {
9794 if ((Align % 16 == 0) && SizeVal >= 16)
9795 UnitSize = 16;
9796 else if ((Align % 8 == 0) && SizeVal >= 8)
9797 UnitSize = 8;
9799 // Can't use NEON instructions.
9800 if (UnitSize == 0)
9801 UnitSize = 4;
9804 // Select the correct opcode and register class for unit size load/store
9805 bool IsNeon = UnitSize >= 8;
9806 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9807 if (IsNeon)
9808 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9809 : UnitSize == 8 ? &ARM::DPRRegClass
9810 : nullptr;
9812 unsigned BytesLeft = SizeVal % UnitSize;
9813 unsigned LoopSize = SizeVal - BytesLeft;
9815 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9816 // Use LDR and STR to copy.
9817 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9818 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9819 unsigned srcIn = src;
9820 unsigned destIn = dest;
9821 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9822 Register srcOut = MRI.createVirtualRegister(TRC);
9823 Register destOut = MRI.createVirtualRegister(TRC);
9824 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9825 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9826 IsThumb1, IsThumb2);
9827 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9828 IsThumb1, IsThumb2);
9829 srcIn = srcOut;
9830 destIn = destOut;
9833 // Handle the leftover bytes with LDRB and STRB.
9834 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9835 // [destOut] = STRB_POST(scratch, destIn, 1)
9836 for (unsigned i = 0; i < BytesLeft; i++) {
9837 Register srcOut = MRI.createVirtualRegister(TRC);
9838 Register destOut = MRI.createVirtualRegister(TRC);
9839 Register scratch = MRI.createVirtualRegister(TRC);
9840 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9841 IsThumb1, IsThumb2);
9842 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9843 IsThumb1, IsThumb2);
9844 srcIn = srcOut;
9845 destIn = destOut;
9847 MI.eraseFromParent(); // The instruction is gone now.
9848 return BB;
9851 // Expand the pseudo op to a loop.
9852 // thisMBB:
9853 // ...
9854 // movw varEnd, # --> with thumb2
9855 // movt varEnd, #
9856 // ldrcp varEnd, idx --> without thumb2
9857 // fallthrough --> loopMBB
9858 // loopMBB:
9859 // PHI varPhi, varEnd, varLoop
9860 // PHI srcPhi, src, srcLoop
9861 // PHI destPhi, dst, destLoop
9862 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9863 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9864 // subs varLoop, varPhi, #UnitSize
9865 // bne loopMBB
9866 // fallthrough --> exitMBB
9867 // exitMBB:
9868 // epilogue to handle left-over bytes
9869 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9870 // [destOut] = STRB_POST(scratch, destLoop, 1)
9871 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9872 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9873 MF->insert(It, loopMBB);
9874 MF->insert(It, exitMBB);
9876 // Transfer the remainder of BB and its successor edges to exitMBB.
9877 exitMBB->splice(exitMBB->begin(), BB,
9878 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9879 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9881 // Load an immediate to varEnd.
9882 Register varEnd = MRI.createVirtualRegister(TRC);
9883 if (Subtarget->useMovt()) {
9884 unsigned Vtmp = varEnd;
9885 if ((LoopSize & 0xFFFF0000) != 0)
9886 Vtmp = MRI.createVirtualRegister(TRC);
9887 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9888 .addImm(LoopSize & 0xFFFF)
9889 .add(predOps(ARMCC::AL));
9891 if ((LoopSize & 0xFFFF0000) != 0)
9892 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9893 .addReg(Vtmp)
9894 .addImm(LoopSize >> 16)
9895 .add(predOps(ARMCC::AL));
9896 } else {
9897 MachineConstantPool *ConstantPool = MF->getConstantPool();
9898 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9899 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9901 // MachineConstantPool wants an explicit alignment.
9902 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9903 if (Align == 0)
9904 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9905 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9906 MachineMemOperand *CPMMO =
9907 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9908 MachineMemOperand::MOLoad, 4, 4);
9910 if (IsThumb)
9911 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9912 .addReg(varEnd, RegState::Define)
9913 .addConstantPoolIndex(Idx)
9914 .add(predOps(ARMCC::AL))
9915 .addMemOperand(CPMMO);
9916 else
9917 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9918 .addReg(varEnd, RegState::Define)
9919 .addConstantPoolIndex(Idx)
9920 .addImm(0)
9921 .add(predOps(ARMCC::AL))
9922 .addMemOperand(CPMMO);
9924 BB->addSuccessor(loopMBB);
9926 // Generate the loop body:
9927 // varPhi = PHI(varLoop, varEnd)
9928 // srcPhi = PHI(srcLoop, src)
9929 // destPhi = PHI(destLoop, dst)
9930 MachineBasicBlock *entryBB = BB;
9931 BB = loopMBB;
9932 Register varLoop = MRI.createVirtualRegister(TRC);
9933 Register varPhi = MRI.createVirtualRegister(TRC);
9934 Register srcLoop = MRI.createVirtualRegister(TRC);
9935 Register srcPhi = MRI.createVirtualRegister(TRC);
9936 Register destLoop = MRI.createVirtualRegister(TRC);
9937 Register destPhi = MRI.createVirtualRegister(TRC);
9939 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9940 .addReg(varLoop).addMBB(loopMBB)
9941 .addReg(varEnd).addMBB(entryBB);
9942 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9943 .addReg(srcLoop).addMBB(loopMBB)
9944 .addReg(src).addMBB(entryBB);
9945 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9946 .addReg(destLoop).addMBB(loopMBB)
9947 .addReg(dest).addMBB(entryBB);
9949 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9950 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9951 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9952 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9953 IsThumb1, IsThumb2);
9954 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9955 IsThumb1, IsThumb2);
9957 // Decrement loop variable by UnitSize.
9958 if (IsThumb1) {
9959 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9960 .add(t1CondCodeOp())
9961 .addReg(varPhi)
9962 .addImm(UnitSize)
9963 .add(predOps(ARMCC::AL));
9964 } else {
9965 MachineInstrBuilder MIB =
9966 BuildMI(*BB, BB->end(), dl,
9967 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9968 MIB.addReg(varPhi)
9969 .addImm(UnitSize)
9970 .add(predOps(ARMCC::AL))
9971 .add(condCodeOp());
9972 MIB->getOperand(5).setReg(ARM::CPSR);
9973 MIB->getOperand(5).setIsDef(true);
9975 BuildMI(*BB, BB->end(), dl,
9976 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9977 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9979 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9980 BB->addSuccessor(loopMBB);
9981 BB->addSuccessor(exitMBB);
9983 // Add epilogue to handle BytesLeft.
9984 BB = exitMBB;
9985 auto StartOfExit = exitMBB->begin();
9987 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9988 // [destOut] = STRB_POST(scratch, destLoop, 1)
9989 unsigned srcIn = srcLoop;
9990 unsigned destIn = destLoop;
9991 for (unsigned i = 0; i < BytesLeft; i++) {
9992 Register srcOut = MRI.createVirtualRegister(TRC);
9993 Register destOut = MRI.createVirtualRegister(TRC);
9994 Register scratch = MRI.createVirtualRegister(TRC);
9995 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9996 IsThumb1, IsThumb2);
9997 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9998 IsThumb1, IsThumb2);
9999 srcIn = srcOut;
10000 destIn = destOut;
10003 MI.eraseFromParent(); // The instruction is gone now.
10004 return BB;
10007 MachineBasicBlock *
10008 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10009 MachineBasicBlock *MBB) const {
10010 const TargetMachine &TM = getTargetMachine();
10011 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10012 DebugLoc DL = MI.getDebugLoc();
10014 assert(Subtarget->isTargetWindows() &&
10015 "__chkstk is only supported on Windows");
10016 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10018 // __chkstk takes the number of words to allocate on the stack in R4, and
10019 // returns the stack adjustment in number of bytes in R4. This will not
10020 // clober any other registers (other than the obvious lr).
10022 // Although, technically, IP should be considered a register which may be
10023 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10024 // thumb-2 environment, so there is no interworking required. As a result, we
10025 // do not expect a veneer to be emitted by the linker, clobbering IP.
10027 // Each module receives its own copy of __chkstk, so no import thunk is
10028 // required, again, ensuring that IP is not clobbered.
10030 // Finally, although some linkers may theoretically provide a trampoline for
10031 // out of range calls (which is quite common due to a 32M range limitation of
10032 // branches for Thumb), we can generate the long-call version via
10033 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10034 // IP.
10036 switch (TM.getCodeModel()) {
10037 case CodeModel::Tiny:
10038 llvm_unreachable("Tiny code model not available on ARM.");
10039 case CodeModel::Small:
10040 case CodeModel::Medium:
10041 case CodeModel::Kernel:
10042 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10043 .add(predOps(ARMCC::AL))
10044 .addExternalSymbol("__chkstk")
10045 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10046 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10047 .addReg(ARM::R12,
10048 RegState::Implicit | RegState::Define | RegState::Dead)
10049 .addReg(ARM::CPSR,
10050 RegState::Implicit | RegState::Define | RegState::Dead);
10051 break;
10052 case CodeModel::Large: {
10053 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10054 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10056 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10057 .addExternalSymbol("__chkstk");
10058 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10059 .add(predOps(ARMCC::AL))
10060 .addReg(Reg, RegState::Kill)
10061 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10062 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10063 .addReg(ARM::R12,
10064 RegState::Implicit | RegState::Define | RegState::Dead)
10065 .addReg(ARM::CPSR,
10066 RegState::Implicit | RegState::Define | RegState::Dead);
10067 break;
10071 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10072 .addReg(ARM::SP, RegState::Kill)
10073 .addReg(ARM::R4, RegState::Kill)
10074 .setMIFlags(MachineInstr::FrameSetup)
10075 .add(predOps(ARMCC::AL))
10076 .add(condCodeOp());
10078 MI.eraseFromParent();
10079 return MBB;
10082 MachineBasicBlock *
10083 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10084 MachineBasicBlock *MBB) const {
10085 DebugLoc DL = MI.getDebugLoc();
10086 MachineFunction *MF = MBB->getParent();
10087 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10089 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10090 MF->insert(++MBB->getIterator(), ContBB);
10091 ContBB->splice(ContBB->begin(), MBB,
10092 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10093 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10094 MBB->addSuccessor(ContBB);
10096 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10097 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10098 MF->push_back(TrapBB);
10099 MBB->addSuccessor(TrapBB);
10101 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10102 .addReg(MI.getOperand(0).getReg())
10103 .addImm(0)
10104 .add(predOps(ARMCC::AL));
10105 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10106 .addMBB(TrapBB)
10107 .addImm(ARMCC::EQ)
10108 .addReg(ARM::CPSR);
10110 MI.eraseFromParent();
10111 return ContBB;
10114 // The CPSR operand of SelectItr might be missing a kill marker
10115 // because there were multiple uses of CPSR, and ISel didn't know
10116 // which to mark. Figure out whether SelectItr should have had a
10117 // kill marker, and set it if it should. Returns the correct kill
10118 // marker value.
10119 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10120 MachineBasicBlock* BB,
10121 const TargetRegisterInfo* TRI) {
10122 // Scan forward through BB for a use/def of CPSR.
10123 MachineBasicBlock::iterator miI(std::next(SelectItr));
10124 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10125 const MachineInstr& mi = *miI;
10126 if (mi.readsRegister(ARM::CPSR))
10127 return false;
10128 if (mi.definesRegister(ARM::CPSR))
10129 break; // Should have kill-flag - update below.
10132 // If we hit the end of the block, check whether CPSR is live into a
10133 // successor.
10134 if (miI == BB->end()) {
10135 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10136 sEnd = BB->succ_end();
10137 sItr != sEnd; ++sItr) {
10138 MachineBasicBlock* succ = *sItr;
10139 if (succ->isLiveIn(ARM::CPSR))
10140 return false;
10144 // We found a def, or hit the end of the basic block and CPSR wasn't live
10145 // out. SelectMI should have a kill flag on CPSR.
10146 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10147 return true;
10150 MachineBasicBlock *
10151 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10152 MachineBasicBlock *BB) const {
10153 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10154 DebugLoc dl = MI.getDebugLoc();
10155 bool isThumb2 = Subtarget->isThumb2();
10156 switch (MI.getOpcode()) {
10157 default: {
10158 MI.print(errs());
10159 llvm_unreachable("Unexpected instr type to insert");
10162 // Thumb1 post-indexed loads are really just single-register LDMs.
10163 case ARM::tLDR_postidx: {
10164 MachineOperand Def(MI.getOperand(1));
10165 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10166 .add(Def) // Rn_wb
10167 .add(MI.getOperand(2)) // Rn
10168 .add(MI.getOperand(3)) // PredImm
10169 .add(MI.getOperand(4)) // PredReg
10170 .add(MI.getOperand(0)) // Rt
10171 .cloneMemRefs(MI);
10172 MI.eraseFromParent();
10173 return BB;
10176 // The Thumb2 pre-indexed stores have the same MI operands, they just
10177 // define them differently in the .td files from the isel patterns, so
10178 // they need pseudos.
10179 case ARM::t2STR_preidx:
10180 MI.setDesc(TII->get(ARM::t2STR_PRE));
10181 return BB;
10182 case ARM::t2STRB_preidx:
10183 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10184 return BB;
10185 case ARM::t2STRH_preidx:
10186 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10187 return BB;
10189 case ARM::STRi_preidx:
10190 case ARM::STRBi_preidx: {
10191 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10192 : ARM::STRB_PRE_IMM;
10193 // Decode the offset.
10194 unsigned Offset = MI.getOperand(4).getImm();
10195 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10196 Offset = ARM_AM::getAM2Offset(Offset);
10197 if (isSub)
10198 Offset = -Offset;
10200 MachineMemOperand *MMO = *MI.memoperands_begin();
10201 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10202 .add(MI.getOperand(0)) // Rn_wb
10203 .add(MI.getOperand(1)) // Rt
10204 .add(MI.getOperand(2)) // Rn
10205 .addImm(Offset) // offset (skip GPR==zero_reg)
10206 .add(MI.getOperand(5)) // pred
10207 .add(MI.getOperand(6))
10208 .addMemOperand(MMO);
10209 MI.eraseFromParent();
10210 return BB;
10212 case ARM::STRr_preidx:
10213 case ARM::STRBr_preidx:
10214 case ARM::STRH_preidx: {
10215 unsigned NewOpc;
10216 switch (MI.getOpcode()) {
10217 default: llvm_unreachable("unexpected opcode!");
10218 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10219 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10220 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10222 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10223 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10224 MIB.add(MI.getOperand(i));
10225 MI.eraseFromParent();
10226 return BB;
10229 case ARM::tMOVCCr_pseudo: {
10230 // To "insert" a SELECT_CC instruction, we actually have to insert the
10231 // diamond control-flow pattern. The incoming instruction knows the
10232 // destination vreg to set, the condition code register to branch on, the
10233 // true/false values to select between, and a branch opcode to use.
10234 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10235 MachineFunction::iterator It = ++BB->getIterator();
10237 // thisMBB:
10238 // ...
10239 // TrueVal = ...
10240 // cmpTY ccX, r1, r2
10241 // bCC copy1MBB
10242 // fallthrough --> copy0MBB
10243 MachineBasicBlock *thisMBB = BB;
10244 MachineFunction *F = BB->getParent();
10245 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10246 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10247 F->insert(It, copy0MBB);
10248 F->insert(It, sinkMBB);
10250 // Check whether CPSR is live past the tMOVCCr_pseudo.
10251 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10252 if (!MI.killsRegister(ARM::CPSR) &&
10253 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10254 copy0MBB->addLiveIn(ARM::CPSR);
10255 sinkMBB->addLiveIn(ARM::CPSR);
10258 // Transfer the remainder of BB and its successor edges to sinkMBB.
10259 sinkMBB->splice(sinkMBB->begin(), BB,
10260 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10261 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10263 BB->addSuccessor(copy0MBB);
10264 BB->addSuccessor(sinkMBB);
10266 BuildMI(BB, dl, TII->get(ARM::tBcc))
10267 .addMBB(sinkMBB)
10268 .addImm(MI.getOperand(3).getImm())
10269 .addReg(MI.getOperand(4).getReg());
10271 // copy0MBB:
10272 // %FalseValue = ...
10273 // # fallthrough to sinkMBB
10274 BB = copy0MBB;
10276 // Update machine-CFG edges
10277 BB->addSuccessor(sinkMBB);
10279 // sinkMBB:
10280 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10281 // ...
10282 BB = sinkMBB;
10283 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10284 .addReg(MI.getOperand(1).getReg())
10285 .addMBB(copy0MBB)
10286 .addReg(MI.getOperand(2).getReg())
10287 .addMBB(thisMBB);
10289 MI.eraseFromParent(); // The pseudo instruction is gone now.
10290 return BB;
10293 case ARM::BCCi64:
10294 case ARM::BCCZi64: {
10295 // If there is an unconditional branch to the other successor, remove it.
10296 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10298 // Compare both parts that make up the double comparison separately for
10299 // equality.
10300 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10302 Register LHS1 = MI.getOperand(1).getReg();
10303 Register LHS2 = MI.getOperand(2).getReg();
10304 if (RHSisZero) {
10305 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10306 .addReg(LHS1)
10307 .addImm(0)
10308 .add(predOps(ARMCC::AL));
10309 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10310 .addReg(LHS2).addImm(0)
10311 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10312 } else {
10313 Register RHS1 = MI.getOperand(3).getReg();
10314 Register RHS2 = MI.getOperand(4).getReg();
10315 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10316 .addReg(LHS1)
10317 .addReg(RHS1)
10318 .add(predOps(ARMCC::AL));
10319 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10320 .addReg(LHS2).addReg(RHS2)
10321 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10324 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10325 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10326 if (MI.getOperand(0).getImm() == ARMCC::NE)
10327 std::swap(destMBB, exitMBB);
10329 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10330 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10331 if (isThumb2)
10332 BuildMI(BB, dl, TII->get(ARM::t2B))
10333 .addMBB(exitMBB)
10334 .add(predOps(ARMCC::AL));
10335 else
10336 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10338 MI.eraseFromParent(); // The pseudo instruction is gone now.
10339 return BB;
10342 case ARM::Int_eh_sjlj_setjmp:
10343 case ARM::Int_eh_sjlj_setjmp_nofp:
10344 case ARM::tInt_eh_sjlj_setjmp:
10345 case ARM::t2Int_eh_sjlj_setjmp:
10346 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10347 return BB;
10349 case ARM::Int_eh_sjlj_setup_dispatch:
10350 EmitSjLjDispatchBlock(MI, BB);
10351 return BB;
10353 case ARM::ABS:
10354 case ARM::t2ABS: {
10355 // To insert an ABS instruction, we have to insert the
10356 // diamond control-flow pattern. The incoming instruction knows the
10357 // source vreg to test against 0, the destination vreg to set,
10358 // the condition code register to branch on, the
10359 // true/false values to select between, and a branch opcode to use.
10360 // It transforms
10361 // V1 = ABS V0
10362 // into
10363 // V2 = MOVS V0
10364 // BCC (branch to SinkBB if V0 >= 0)
10365 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10366 // SinkBB: V1 = PHI(V2, V3)
10367 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10368 MachineFunction::iterator BBI = ++BB->getIterator();
10369 MachineFunction *Fn = BB->getParent();
10370 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10371 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10372 Fn->insert(BBI, RSBBB);
10373 Fn->insert(BBI, SinkBB);
10375 Register ABSSrcReg = MI.getOperand(1).getReg();
10376 Register ABSDstReg = MI.getOperand(0).getReg();
10377 bool ABSSrcKIll = MI.getOperand(1).isKill();
10378 bool isThumb2 = Subtarget->isThumb2();
10379 MachineRegisterInfo &MRI = Fn->getRegInfo();
10380 // In Thumb mode S must not be specified if source register is the SP or
10381 // PC and if destination register is the SP, so restrict register class
10382 Register NewRsbDstReg = MRI.createVirtualRegister(
10383 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10385 // Transfer the remainder of BB and its successor edges to sinkMBB.
10386 SinkBB->splice(SinkBB->begin(), BB,
10387 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10388 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10390 BB->addSuccessor(RSBBB);
10391 BB->addSuccessor(SinkBB);
10393 // fall through to SinkMBB
10394 RSBBB->addSuccessor(SinkBB);
10396 // insert a cmp at the end of BB
10397 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10398 .addReg(ABSSrcReg)
10399 .addImm(0)
10400 .add(predOps(ARMCC::AL));
10402 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10403 BuildMI(BB, dl,
10404 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10405 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10407 // insert rsbri in RSBBB
10408 // Note: BCC and rsbri will be converted into predicated rsbmi
10409 // by if-conversion pass
10410 BuildMI(*RSBBB, RSBBB->begin(), dl,
10411 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10412 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10413 .addImm(0)
10414 .add(predOps(ARMCC::AL))
10415 .add(condCodeOp());
10417 // insert PHI in SinkBB,
10418 // reuse ABSDstReg to not change uses of ABS instruction
10419 BuildMI(*SinkBB, SinkBB->begin(), dl,
10420 TII->get(ARM::PHI), ABSDstReg)
10421 .addReg(NewRsbDstReg).addMBB(RSBBB)
10422 .addReg(ABSSrcReg).addMBB(BB);
10424 // remove ABS instruction
10425 MI.eraseFromParent();
10427 // return last added BB
10428 return SinkBB;
10430 case ARM::COPY_STRUCT_BYVAL_I32:
10431 ++NumLoopByVals;
10432 return EmitStructByval(MI, BB);
10433 case ARM::WIN__CHKSTK:
10434 return EmitLowered__chkstk(MI, BB);
10435 case ARM::WIN__DBZCHK:
10436 return EmitLowered__dbzchk(MI, BB);
10440 /// Attaches vregs to MEMCPY that it will use as scratch registers
10441 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10442 /// instead of as a custom inserter because we need the use list from the SDNode.
10443 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10444 MachineInstr &MI, const SDNode *Node) {
10445 bool isThumb1 = Subtarget->isThumb1Only();
10447 DebugLoc DL = MI.getDebugLoc();
10448 MachineFunction *MF = MI.getParent()->getParent();
10449 MachineRegisterInfo &MRI = MF->getRegInfo();
10450 MachineInstrBuilder MIB(*MF, MI);
10452 // If the new dst/src is unused mark it as dead.
10453 if (!Node->hasAnyUseOfValue(0)) {
10454 MI.getOperand(0).setIsDead(true);
10456 if (!Node->hasAnyUseOfValue(1)) {
10457 MI.getOperand(1).setIsDead(true);
10460 // The MEMCPY both defines and kills the scratch registers.
10461 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10462 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10463 : &ARM::GPRRegClass);
10464 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10468 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10469 SDNode *Node) const {
10470 if (MI.getOpcode() == ARM::MEMCPY) {
10471 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10472 return;
10475 const MCInstrDesc *MCID = &MI.getDesc();
10476 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10477 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10478 // operand is still set to noreg. If needed, set the optional operand's
10479 // register to CPSR, and remove the redundant implicit def.
10481 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10483 // Rename pseudo opcodes.
10484 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10485 unsigned ccOutIdx;
10486 if (NewOpc) {
10487 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10488 MCID = &TII->get(NewOpc);
10490 assert(MCID->getNumOperands() ==
10491 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10492 && "converted opcode should be the same except for cc_out"
10493 " (and, on Thumb1, pred)");
10495 MI.setDesc(*MCID);
10497 // Add the optional cc_out operand
10498 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10500 // On Thumb1, move all input operands to the end, then add the predicate
10501 if (Subtarget->isThumb1Only()) {
10502 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10503 MI.addOperand(MI.getOperand(1));
10504 MI.RemoveOperand(1);
10507 // Restore the ties
10508 for (unsigned i = MI.getNumOperands(); i--;) {
10509 const MachineOperand& op = MI.getOperand(i);
10510 if (op.isReg() && op.isUse()) {
10511 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10512 if (DefIdx != -1)
10513 MI.tieOperands(DefIdx, i);
10517 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10518 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10519 ccOutIdx = 1;
10520 } else
10521 ccOutIdx = MCID->getNumOperands() - 1;
10522 } else
10523 ccOutIdx = MCID->getNumOperands() - 1;
10525 // Any ARM instruction that sets the 's' bit should specify an optional
10526 // "cc_out" operand in the last operand position.
10527 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10528 assert(!NewOpc && "Optional cc_out operand required");
10529 return;
10531 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10532 // since we already have an optional CPSR def.
10533 bool definesCPSR = false;
10534 bool deadCPSR = false;
10535 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10536 ++i) {
10537 const MachineOperand &MO = MI.getOperand(i);
10538 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10539 definesCPSR = true;
10540 if (MO.isDead())
10541 deadCPSR = true;
10542 MI.RemoveOperand(i);
10543 break;
10546 if (!definesCPSR) {
10547 assert(!NewOpc && "Optional cc_out operand required");
10548 return;
10550 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10551 if (deadCPSR) {
10552 assert(!MI.getOperand(ccOutIdx).getReg() &&
10553 "expect uninitialized optional cc_out operand");
10554 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10555 if (!Subtarget->isThumb1Only())
10556 return;
10559 // If this instruction was defined with an optional CPSR def and its dag node
10560 // had a live implicit CPSR def, then activate the optional CPSR def.
10561 MachineOperand &MO = MI.getOperand(ccOutIdx);
10562 MO.setReg(ARM::CPSR);
10563 MO.setIsDef(true);
10566 //===----------------------------------------------------------------------===//
10567 // ARM Optimization Hooks
10568 //===----------------------------------------------------------------------===//
10570 // Helper function that checks if N is a null or all ones constant.
10571 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10572 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10575 // Return true if N is conditionally 0 or all ones.
10576 // Detects these expressions where cc is an i1 value:
10578 // (select cc 0, y) [AllOnes=0]
10579 // (select cc y, 0) [AllOnes=0]
10580 // (zext cc) [AllOnes=0]
10581 // (sext cc) [AllOnes=0/1]
10582 // (select cc -1, y) [AllOnes=1]
10583 // (select cc y, -1) [AllOnes=1]
10585 // Invert is set when N is the null/all ones constant when CC is false.
10586 // OtherOp is set to the alternative value of N.
10587 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10588 SDValue &CC, bool &Invert,
10589 SDValue &OtherOp,
10590 SelectionDAG &DAG) {
10591 switch (N->getOpcode()) {
10592 default: return false;
10593 case ISD::SELECT: {
10594 CC = N->getOperand(0);
10595 SDValue N1 = N->getOperand(1);
10596 SDValue N2 = N->getOperand(2);
10597 if (isZeroOrAllOnes(N1, AllOnes)) {
10598 Invert = false;
10599 OtherOp = N2;
10600 return true;
10602 if (isZeroOrAllOnes(N2, AllOnes)) {
10603 Invert = true;
10604 OtherOp = N1;
10605 return true;
10607 return false;
10609 case ISD::ZERO_EXTEND:
10610 // (zext cc) can never be the all ones value.
10611 if (AllOnes)
10612 return false;
10613 LLVM_FALLTHROUGH;
10614 case ISD::SIGN_EXTEND: {
10615 SDLoc dl(N);
10616 EVT VT = N->getValueType(0);
10617 CC = N->getOperand(0);
10618 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10619 return false;
10620 Invert = !AllOnes;
10621 if (AllOnes)
10622 // When looking for an AllOnes constant, N is an sext, and the 'other'
10623 // value is 0.
10624 OtherOp = DAG.getConstant(0, dl, VT);
10625 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10626 // When looking for a 0 constant, N can be zext or sext.
10627 OtherOp = DAG.getConstant(1, dl, VT);
10628 else
10629 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10630 VT);
10631 return true;
10636 // Combine a constant select operand into its use:
10638 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10639 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10640 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10641 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10642 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10644 // The transform is rejected if the select doesn't have a constant operand that
10645 // is null, or all ones when AllOnes is set.
10647 // Also recognize sext/zext from i1:
10649 // (add (zext cc), x) -> (select cc (add x, 1), x)
10650 // (add (sext cc), x) -> (select cc (add x, -1), x)
10652 // These transformations eventually create predicated instructions.
10654 // @param N The node to transform.
10655 // @param Slct The N operand that is a select.
10656 // @param OtherOp The other N operand (x above).
10657 // @param DCI Context.
10658 // @param AllOnes Require the select constant to be all ones instead of null.
10659 // @returns The new node, or SDValue() on failure.
10660 static
10661 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10662 TargetLowering::DAGCombinerInfo &DCI,
10663 bool AllOnes = false) {
10664 SelectionDAG &DAG = DCI.DAG;
10665 EVT VT = N->getValueType(0);
10666 SDValue NonConstantVal;
10667 SDValue CCOp;
10668 bool SwapSelectOps;
10669 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10670 NonConstantVal, DAG))
10671 return SDValue();
10673 // Slct is now know to be the desired identity constant when CC is true.
10674 SDValue TrueVal = OtherOp;
10675 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10676 OtherOp, NonConstantVal);
10677 // Unless SwapSelectOps says CC should be false.
10678 if (SwapSelectOps)
10679 std::swap(TrueVal, FalseVal);
10681 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10682 CCOp, TrueVal, FalseVal);
10685 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10686 static
10687 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10688 TargetLowering::DAGCombinerInfo &DCI) {
10689 SDValue N0 = N->getOperand(0);
10690 SDValue N1 = N->getOperand(1);
10691 if (N0.getNode()->hasOneUse())
10692 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10693 return Result;
10694 if (N1.getNode()->hasOneUse())
10695 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10696 return Result;
10697 return SDValue();
10700 static bool IsVUZPShuffleNode(SDNode *N) {
10701 // VUZP shuffle node.
10702 if (N->getOpcode() == ARMISD::VUZP)
10703 return true;
10705 // "VUZP" on i32 is an alias for VTRN.
10706 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10707 return true;
10709 return false;
10712 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10713 TargetLowering::DAGCombinerInfo &DCI,
10714 const ARMSubtarget *Subtarget) {
10715 // Look for ADD(VUZP.0, VUZP.1).
10716 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10717 N0 == N1)
10718 return SDValue();
10720 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10721 if (!N->getValueType(0).is64BitVector())
10722 return SDValue();
10724 // Generate vpadd.
10725 SelectionDAG &DAG = DCI.DAG;
10726 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10727 SDLoc dl(N);
10728 SDNode *Unzip = N0.getNode();
10729 EVT VT = N->getValueType(0);
10731 SmallVector<SDValue, 8> Ops;
10732 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10733 TLI.getPointerTy(DAG.getDataLayout())));
10734 Ops.push_back(Unzip->getOperand(0));
10735 Ops.push_back(Unzip->getOperand(1));
10737 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10740 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10741 TargetLowering::DAGCombinerInfo &DCI,
10742 const ARMSubtarget *Subtarget) {
10743 // Check for two extended operands.
10744 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10745 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10746 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10747 N1.getOpcode() == ISD::ZERO_EXTEND))
10748 return SDValue();
10750 SDValue N00 = N0.getOperand(0);
10751 SDValue N10 = N1.getOperand(0);
10753 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10754 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10755 N00 == N10)
10756 return SDValue();
10758 // We only recognize Q register paddl here; this can't be reached until
10759 // after type legalization.
10760 if (!N00.getValueType().is64BitVector() ||
10761 !N0.getValueType().is128BitVector())
10762 return SDValue();
10764 // Generate vpaddl.
10765 SelectionDAG &DAG = DCI.DAG;
10766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10767 SDLoc dl(N);
10768 EVT VT = N->getValueType(0);
10770 SmallVector<SDValue, 8> Ops;
10771 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10772 unsigned Opcode;
10773 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10774 Opcode = Intrinsic::arm_neon_vpaddls;
10775 else
10776 Opcode = Intrinsic::arm_neon_vpaddlu;
10777 Ops.push_back(DAG.getConstant(Opcode, dl,
10778 TLI.getPointerTy(DAG.getDataLayout())));
10779 EVT ElemTy = N00.getValueType().getVectorElementType();
10780 unsigned NumElts = VT.getVectorNumElements();
10781 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10782 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10783 N00.getOperand(0), N00.getOperand(1));
10784 Ops.push_back(Concat);
10786 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10789 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10790 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10791 // much easier to match.
10792 static SDValue
10793 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10794 TargetLowering::DAGCombinerInfo &DCI,
10795 const ARMSubtarget *Subtarget) {
10796 // Only perform optimization if after legalize, and if NEON is available. We
10797 // also expected both operands to be BUILD_VECTORs.
10798 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10799 || N0.getOpcode() != ISD::BUILD_VECTOR
10800 || N1.getOpcode() != ISD::BUILD_VECTOR)
10801 return SDValue();
10803 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10804 EVT VT = N->getValueType(0);
10805 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10806 return SDValue();
10808 // Check that the vector operands are of the right form.
10809 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10810 // operands, where N is the size of the formed vector.
10811 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10812 // index such that we have a pair wise add pattern.
10814 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10815 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10816 return SDValue();
10817 SDValue Vec = N0->getOperand(0)->getOperand(0);
10818 SDNode *V = Vec.getNode();
10819 unsigned nextIndex = 0;
10821 // For each operands to the ADD which are BUILD_VECTORs,
10822 // check to see if each of their operands are an EXTRACT_VECTOR with
10823 // the same vector and appropriate index.
10824 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10825 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10826 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10828 SDValue ExtVec0 = N0->getOperand(i);
10829 SDValue ExtVec1 = N1->getOperand(i);
10831 // First operand is the vector, verify its the same.
10832 if (V != ExtVec0->getOperand(0).getNode() ||
10833 V != ExtVec1->getOperand(0).getNode())
10834 return SDValue();
10836 // Second is the constant, verify its correct.
10837 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10838 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10840 // For the constant, we want to see all the even or all the odd.
10841 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10842 || C1->getZExtValue() != nextIndex+1)
10843 return SDValue();
10845 // Increment index.
10846 nextIndex+=2;
10847 } else
10848 return SDValue();
10851 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10852 // we're using the entire input vector, otherwise there's a size/legality
10853 // mismatch somewhere.
10854 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10855 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10856 return SDValue();
10858 // Create VPADDL node.
10859 SelectionDAG &DAG = DCI.DAG;
10860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10862 SDLoc dl(N);
10864 // Build operand list.
10865 SmallVector<SDValue, 8> Ops;
10866 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10867 TLI.getPointerTy(DAG.getDataLayout())));
10869 // Input is the vector.
10870 Ops.push_back(Vec);
10872 // Get widened type and narrowed type.
10873 MVT widenType;
10874 unsigned numElem = VT.getVectorNumElements();
10876 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10877 switch (inputLaneType.getSimpleVT().SimpleTy) {
10878 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10879 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10880 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10881 default:
10882 llvm_unreachable("Invalid vector element type for padd optimization.");
10885 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10886 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10887 return DAG.getNode(ExtOp, dl, VT, tmp);
10890 static SDValue findMUL_LOHI(SDValue V) {
10891 if (V->getOpcode() == ISD::UMUL_LOHI ||
10892 V->getOpcode() == ISD::SMUL_LOHI)
10893 return V;
10894 return SDValue();
10897 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10898 TargetLowering::DAGCombinerInfo &DCI,
10899 const ARMSubtarget *Subtarget) {
10900 if (Subtarget->isThumb()) {
10901 if (!Subtarget->hasDSP())
10902 return SDValue();
10903 } else if (!Subtarget->hasV5TEOps())
10904 return SDValue();
10906 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10907 // accumulates the product into a 64-bit value. The 16-bit values will
10908 // be sign extended somehow or SRA'd into 32-bit values
10909 // (addc (adde (mul 16bit, 16bit), lo), hi)
10910 SDValue Mul = AddcNode->getOperand(0);
10911 SDValue Lo = AddcNode->getOperand(1);
10912 if (Mul.getOpcode() != ISD::MUL) {
10913 Lo = AddcNode->getOperand(0);
10914 Mul = AddcNode->getOperand(1);
10915 if (Mul.getOpcode() != ISD::MUL)
10916 return SDValue();
10919 SDValue SRA = AddeNode->getOperand(0);
10920 SDValue Hi = AddeNode->getOperand(1);
10921 if (SRA.getOpcode() != ISD::SRA) {
10922 SRA = AddeNode->getOperand(1);
10923 Hi = AddeNode->getOperand(0);
10924 if (SRA.getOpcode() != ISD::SRA)
10925 return SDValue();
10927 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10928 if (Const->getZExtValue() != 31)
10929 return SDValue();
10930 } else
10931 return SDValue();
10933 if (SRA.getOperand(0) != Mul)
10934 return SDValue();
10936 SelectionDAG &DAG = DCI.DAG;
10937 SDLoc dl(AddcNode);
10938 unsigned Opcode = 0;
10939 SDValue Op0;
10940 SDValue Op1;
10942 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10943 Opcode = ARMISD::SMLALBB;
10944 Op0 = Mul.getOperand(0);
10945 Op1 = Mul.getOperand(1);
10946 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10947 Opcode = ARMISD::SMLALBT;
10948 Op0 = Mul.getOperand(0);
10949 Op1 = Mul.getOperand(1).getOperand(0);
10950 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10951 Opcode = ARMISD::SMLALTB;
10952 Op0 = Mul.getOperand(0).getOperand(0);
10953 Op1 = Mul.getOperand(1);
10954 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10955 Opcode = ARMISD::SMLALTT;
10956 Op0 = Mul->getOperand(0).getOperand(0);
10957 Op1 = Mul->getOperand(1).getOperand(0);
10960 if (!Op0 || !Op1)
10961 return SDValue();
10963 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10964 Op0, Op1, Lo, Hi);
10965 // Replace the ADDs' nodes uses by the MLA node's values.
10966 SDValue HiMLALResult(SMLAL.getNode(), 1);
10967 SDValue LoMLALResult(SMLAL.getNode(), 0);
10969 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10970 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10972 // Return original node to notify the driver to stop replacing.
10973 SDValue resNode(AddcNode, 0);
10974 return resNode;
10977 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10978 TargetLowering::DAGCombinerInfo &DCI,
10979 const ARMSubtarget *Subtarget) {
10980 // Look for multiply add opportunities.
10981 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10982 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10983 // a glue link from the first add to the second add.
10984 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10985 // a S/UMLAL instruction.
10986 // UMUL_LOHI
10987 // / :lo \ :hi
10988 // V \ [no multiline comment]
10989 // loAdd -> ADDC |
10990 // \ :carry /
10991 // V V
10992 // ADDE <- hiAdd
10994 // In the special case where only the higher part of a signed result is used
10995 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10996 // a constant with the exact value of 0x80000000, we recognize we are dealing
10997 // with a "rounded multiply and add" (or subtract) and transform it into
10998 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11000 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11001 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11002 "Expect an ADDE or SUBE");
11004 assert(AddeSubeNode->getNumOperands() == 3 &&
11005 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11006 "ADDE node has the wrong inputs");
11008 // Check that we are chained to the right ADDC or SUBC node.
11009 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11010 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11011 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11012 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11013 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11014 return SDValue();
11016 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11017 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11019 // Check if the two operands are from the same mul_lohi node.
11020 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11021 return SDValue();
11023 assert(AddcSubcNode->getNumValues() == 2 &&
11024 AddcSubcNode->getValueType(0) == MVT::i32 &&
11025 "Expect ADDC with two result values. First: i32");
11027 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11028 // maybe a SMLAL which multiplies two 16-bit values.
11029 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11030 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11031 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11032 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11033 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11034 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11036 // Check for the triangle shape.
11037 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11038 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11040 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11041 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11042 return SDValue();
11044 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11045 bool IsLeftOperandMUL = false;
11046 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11047 if (MULOp == SDValue())
11048 MULOp = findMUL_LOHI(AddeSubeOp1);
11049 else
11050 IsLeftOperandMUL = true;
11051 if (MULOp == SDValue())
11052 return SDValue();
11054 // Figure out the right opcode.
11055 unsigned Opc = MULOp->getOpcode();
11056 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11058 // Figure out the high and low input values to the MLAL node.
11059 SDValue *HiAddSub = nullptr;
11060 SDValue *LoMul = nullptr;
11061 SDValue *LowAddSub = nullptr;
11063 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11064 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11065 return SDValue();
11067 if (IsLeftOperandMUL)
11068 HiAddSub = &AddeSubeOp1;
11069 else
11070 HiAddSub = &AddeSubeOp0;
11072 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11073 // whose low result is fed to the ADDC/SUBC we are checking.
11075 if (AddcSubcOp0 == MULOp.getValue(0)) {
11076 LoMul = &AddcSubcOp0;
11077 LowAddSub = &AddcSubcOp1;
11079 if (AddcSubcOp1 == MULOp.getValue(0)) {
11080 LoMul = &AddcSubcOp1;
11081 LowAddSub = &AddcSubcOp0;
11084 if (!LoMul)
11085 return SDValue();
11087 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11088 // the replacement below will create a cycle.
11089 if (AddcSubcNode == HiAddSub->getNode() ||
11090 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11091 return SDValue();
11093 // Create the merged node.
11094 SelectionDAG &DAG = DCI.DAG;
11096 // Start building operand list.
11097 SmallVector<SDValue, 8> Ops;
11098 Ops.push_back(LoMul->getOperand(0));
11099 Ops.push_back(LoMul->getOperand(1));
11101 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11102 // the case, we must be doing signed multiplication and only use the higher
11103 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11104 // addition or subtraction with the value of 0x800000.
11105 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11106 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11107 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11108 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11109 0x80000000) {
11110 Ops.push_back(*HiAddSub);
11111 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11112 FinalOpc = ARMISD::SMMLSR;
11113 } else {
11114 FinalOpc = ARMISD::SMMLAR;
11116 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11117 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11119 return SDValue(AddeSubeNode, 0);
11120 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11121 // SMMLS is generated during instruction selection and the rest of this
11122 // function can not handle the case where AddcSubcNode is a SUBC.
11123 return SDValue();
11125 // Finish building the operand list for {U/S}MLAL
11126 Ops.push_back(*LowAddSub);
11127 Ops.push_back(*HiAddSub);
11129 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11130 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11132 // Replace the ADDs' nodes uses by the MLA node's values.
11133 SDValue HiMLALResult(MLALNode.getNode(), 1);
11134 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11136 SDValue LoMLALResult(MLALNode.getNode(), 0);
11137 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11139 // Return original node to notify the driver to stop replacing.
11140 return SDValue(AddeSubeNode, 0);
11143 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11144 TargetLowering::DAGCombinerInfo &DCI,
11145 const ARMSubtarget *Subtarget) {
11146 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11147 // While trying to combine for the other MLAL nodes, first search for the
11148 // chance to use UMAAL. Check if Addc uses a node which has already
11149 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11150 // as the addend, and it's handled in PerformUMLALCombine.
11152 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11153 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11155 // Check that we have a glued ADDC node.
11156 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11157 if (AddcNode->getOpcode() != ARMISD::ADDC)
11158 return SDValue();
11160 // Find the converted UMAAL or quit if it doesn't exist.
11161 SDNode *UmlalNode = nullptr;
11162 SDValue AddHi;
11163 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11164 UmlalNode = AddcNode->getOperand(0).getNode();
11165 AddHi = AddcNode->getOperand(1);
11166 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11167 UmlalNode = AddcNode->getOperand(1).getNode();
11168 AddHi = AddcNode->getOperand(0);
11169 } else {
11170 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11173 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11174 // the ADDC as well as Zero.
11175 if (!isNullConstant(UmlalNode->getOperand(3)))
11176 return SDValue();
11178 if ((isNullConstant(AddeNode->getOperand(0)) &&
11179 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11180 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11181 isNullConstant(AddeNode->getOperand(1)))) {
11182 SelectionDAG &DAG = DCI.DAG;
11183 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11184 UmlalNode->getOperand(2), AddHi };
11185 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11186 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11188 // Replace the ADDs' nodes uses by the UMAAL node's values.
11189 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11190 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11192 // Return original node to notify the driver to stop replacing.
11193 return SDValue(AddeNode, 0);
11195 return SDValue();
11198 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11199 const ARMSubtarget *Subtarget) {
11200 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11201 return SDValue();
11203 // Check that we have a pair of ADDC and ADDE as operands.
11204 // Both addends of the ADDE must be zero.
11205 SDNode* AddcNode = N->getOperand(2).getNode();
11206 SDNode* AddeNode = N->getOperand(3).getNode();
11207 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11208 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11209 isNullConstant(AddeNode->getOperand(0)) &&
11210 isNullConstant(AddeNode->getOperand(1)) &&
11211 (AddeNode->getOperand(2).getNode() == AddcNode))
11212 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11213 DAG.getVTList(MVT::i32, MVT::i32),
11214 {N->getOperand(0), N->getOperand(1),
11215 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11216 else
11217 return SDValue();
11220 static SDValue PerformAddcSubcCombine(SDNode *N,
11221 TargetLowering::DAGCombinerInfo &DCI,
11222 const ARMSubtarget *Subtarget) {
11223 SelectionDAG &DAG(DCI.DAG);
11225 if (N->getOpcode() == ARMISD::SUBC) {
11226 // (SUBC (ADDE 0, 0, C), 1) -> C
11227 SDValue LHS = N->getOperand(0);
11228 SDValue RHS = N->getOperand(1);
11229 if (LHS->getOpcode() == ARMISD::ADDE &&
11230 isNullConstant(LHS->getOperand(0)) &&
11231 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11232 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11236 if (Subtarget->isThumb1Only()) {
11237 SDValue RHS = N->getOperand(1);
11238 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11239 int32_t imm = C->getSExtValue();
11240 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11241 SDLoc DL(N);
11242 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11243 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11244 : ARMISD::ADDC;
11245 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11250 return SDValue();
11253 static SDValue PerformAddeSubeCombine(SDNode *N,
11254 TargetLowering::DAGCombinerInfo &DCI,
11255 const ARMSubtarget *Subtarget) {
11256 if (Subtarget->isThumb1Only()) {
11257 SelectionDAG &DAG = DCI.DAG;
11258 SDValue RHS = N->getOperand(1);
11259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11260 int64_t imm = C->getSExtValue();
11261 if (imm < 0) {
11262 SDLoc DL(N);
11264 // The with-carry-in form matches bitwise not instead of the negation.
11265 // Effectively, the inverse interpretation of the carry flag already
11266 // accounts for part of the negation.
11267 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11269 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11270 : ARMISD::ADDE;
11271 return DAG.getNode(Opcode, DL, N->getVTList(),
11272 N->getOperand(0), RHS, N->getOperand(2));
11275 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11276 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11278 return SDValue();
11281 static SDValue PerformABSCombine(SDNode *N,
11282 TargetLowering::DAGCombinerInfo &DCI,
11283 const ARMSubtarget *Subtarget) {
11284 SDValue res;
11285 SelectionDAG &DAG = DCI.DAG;
11286 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11288 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11289 return SDValue();
11291 if (!TLI.expandABS(N, res, DAG))
11292 return SDValue();
11294 return res;
11297 /// PerformADDECombine - Target-specific dag combine transform from
11298 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11299 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11300 static SDValue PerformADDECombine(SDNode *N,
11301 TargetLowering::DAGCombinerInfo &DCI,
11302 const ARMSubtarget *Subtarget) {
11303 // Only ARM and Thumb2 support UMLAL/SMLAL.
11304 if (Subtarget->isThumb1Only())
11305 return PerformAddeSubeCombine(N, DCI, Subtarget);
11307 // Only perform the checks after legalize when the pattern is available.
11308 if (DCI.isBeforeLegalize()) return SDValue();
11310 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11313 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11314 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11315 /// called with the default operands, and if that fails, with commuted
11316 /// operands.
11317 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11318 TargetLowering::DAGCombinerInfo &DCI,
11319 const ARMSubtarget *Subtarget){
11320 // Attempt to create vpadd for this add.
11321 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11322 return Result;
11324 // Attempt to create vpaddl for this add.
11325 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11326 return Result;
11327 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11328 Subtarget))
11329 return Result;
11331 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11332 if (N0.getNode()->hasOneUse())
11333 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11334 return Result;
11335 return SDValue();
11338 bool
11339 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11340 CombineLevel Level) const {
11341 if (Level == BeforeLegalizeTypes)
11342 return true;
11344 if (N->getOpcode() != ISD::SHL)
11345 return true;
11347 if (Subtarget->isThumb1Only()) {
11348 // Avoid making expensive immediates by commuting shifts. (This logic
11349 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11350 // for free.)
11351 if (N->getOpcode() != ISD::SHL)
11352 return true;
11353 SDValue N1 = N->getOperand(0);
11354 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11355 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11356 return true;
11357 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11358 if (Const->getAPIntValue().ult(256))
11359 return false;
11360 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11361 Const->getAPIntValue().sgt(-256))
11362 return false;
11364 return true;
11367 // Turn off commute-with-shift transform after legalization, so it doesn't
11368 // conflict with PerformSHLSimplify. (We could try to detect when
11369 // PerformSHLSimplify would trigger more precisely, but it isn't
11370 // really necessary.)
11371 return false;
11374 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11375 const SDNode *N, CombineLevel Level) const {
11376 if (!Subtarget->isThumb1Only())
11377 return true;
11379 if (Level == BeforeLegalizeTypes)
11380 return true;
11382 return false;
11385 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11386 if (!Subtarget->hasNEON()) {
11387 if (Subtarget->isThumb1Only())
11388 return VT.getScalarSizeInBits() <= 32;
11389 return true;
11391 return VT.isScalarInteger();
11394 static SDValue PerformSHLSimplify(SDNode *N,
11395 TargetLowering::DAGCombinerInfo &DCI,
11396 const ARMSubtarget *ST) {
11397 // Allow the generic combiner to identify potential bswaps.
11398 if (DCI.isBeforeLegalize())
11399 return SDValue();
11401 // DAG combiner will fold:
11402 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11403 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11404 // Other code patterns that can be also be modified have the following form:
11405 // b + ((a << 1) | 510)
11406 // b + ((a << 1) & 510)
11407 // b + ((a << 1) ^ 510)
11408 // b + ((a << 1) + 510)
11410 // Many instructions can perform the shift for free, but it requires both
11411 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11412 // instruction will needed. So, unfold back to the original pattern if:
11413 // - if c1 and c2 are small enough that they don't require mov imms.
11414 // - the user(s) of the node can perform an shl
11416 // No shifted operands for 16-bit instructions.
11417 if (ST->isThumb() && ST->isThumb1Only())
11418 return SDValue();
11420 // Check that all the users could perform the shl themselves.
11421 for (auto U : N->uses()) {
11422 switch(U->getOpcode()) {
11423 default:
11424 return SDValue();
11425 case ISD::SUB:
11426 case ISD::ADD:
11427 case ISD::AND:
11428 case ISD::OR:
11429 case ISD::XOR:
11430 case ISD::SETCC:
11431 case ARMISD::CMP:
11432 // Check that the user isn't already using a constant because there
11433 // aren't any instructions that support an immediate operand and a
11434 // shifted operand.
11435 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11436 isa<ConstantSDNode>(U->getOperand(1)))
11437 return SDValue();
11439 // Check that it's not already using a shift.
11440 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11441 U->getOperand(1).getOpcode() == ISD::SHL)
11442 return SDValue();
11443 break;
11447 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11448 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11449 return SDValue();
11451 if (N->getOperand(0).getOpcode() != ISD::SHL)
11452 return SDValue();
11454 SDValue SHL = N->getOperand(0);
11456 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11457 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11458 if (!C1ShlC2 || !C2)
11459 return SDValue();
11461 APInt C2Int = C2->getAPIntValue();
11462 APInt C1Int = C1ShlC2->getAPIntValue();
11464 // Check that performing a lshr will not lose any information.
11465 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11466 C2Int.getBitWidth() - C2->getZExtValue());
11467 if ((C1Int & Mask) != C1Int)
11468 return SDValue();
11470 // Shift the first constant.
11471 C1Int.lshrInPlace(C2Int);
11473 // The immediates are encoded as an 8-bit value that can be rotated.
11474 auto LargeImm = [](const APInt &Imm) {
11475 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11476 return Imm.getBitWidth() - Zeros > 8;
11479 if (LargeImm(C1Int) || LargeImm(C2Int))
11480 return SDValue();
11482 SelectionDAG &DAG = DCI.DAG;
11483 SDLoc dl(N);
11484 SDValue X = SHL.getOperand(0);
11485 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11486 DAG.getConstant(C1Int, dl, MVT::i32));
11487 // Shift left to compensate for the lshr of C1Int.
11488 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11490 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11491 SHL.dump(); N->dump());
11492 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11493 return Res;
11497 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11499 static SDValue PerformADDCombine(SDNode *N,
11500 TargetLowering::DAGCombinerInfo &DCI,
11501 const ARMSubtarget *Subtarget) {
11502 SDValue N0 = N->getOperand(0);
11503 SDValue N1 = N->getOperand(1);
11505 // Only works one way, because it needs an immediate operand.
11506 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11507 return Result;
11509 // First try with the default operand order.
11510 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11511 return Result;
11513 // If that didn't work, try again with the operands commuted.
11514 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11517 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11519 static SDValue PerformSUBCombine(SDNode *N,
11520 TargetLowering::DAGCombinerInfo &DCI) {
11521 SDValue N0 = N->getOperand(0);
11522 SDValue N1 = N->getOperand(1);
11524 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11525 if (N1.getNode()->hasOneUse())
11526 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11527 return Result;
11529 return SDValue();
11532 /// PerformVMULCombine
11533 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11534 /// special multiplier accumulator forwarding.
11535 /// vmul d3, d0, d2
11536 /// vmla d3, d1, d2
11537 /// is faster than
11538 /// vadd d3, d0, d1
11539 /// vmul d3, d3, d2
11540 // However, for (A + B) * (A + B),
11541 // vadd d2, d0, d1
11542 // vmul d3, d0, d2
11543 // vmla d3, d1, d2
11544 // is slower than
11545 // vadd d2, d0, d1
11546 // vmul d3, d2, d2
11547 static SDValue PerformVMULCombine(SDNode *N,
11548 TargetLowering::DAGCombinerInfo &DCI,
11549 const ARMSubtarget *Subtarget) {
11550 if (!Subtarget->hasVMLxForwarding())
11551 return SDValue();
11553 SelectionDAG &DAG = DCI.DAG;
11554 SDValue N0 = N->getOperand(0);
11555 SDValue N1 = N->getOperand(1);
11556 unsigned Opcode = N0.getOpcode();
11557 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11558 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11559 Opcode = N1.getOpcode();
11560 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11561 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11562 return SDValue();
11563 std::swap(N0, N1);
11566 if (N0 == N1)
11567 return SDValue();
11569 EVT VT = N->getValueType(0);
11570 SDLoc DL(N);
11571 SDValue N00 = N0->getOperand(0);
11572 SDValue N01 = N0->getOperand(1);
11573 return DAG.getNode(Opcode, DL, VT,
11574 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11575 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11578 static SDValue PerformMULCombine(SDNode *N,
11579 TargetLowering::DAGCombinerInfo &DCI,
11580 const ARMSubtarget *Subtarget) {
11581 SelectionDAG &DAG = DCI.DAG;
11583 if (Subtarget->isThumb1Only())
11584 return SDValue();
11586 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11587 return SDValue();
11589 EVT VT = N->getValueType(0);
11590 if (VT.is64BitVector() || VT.is128BitVector())
11591 return PerformVMULCombine(N, DCI, Subtarget);
11592 if (VT != MVT::i32)
11593 return SDValue();
11595 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11596 if (!C)
11597 return SDValue();
11599 int64_t MulAmt = C->getSExtValue();
11600 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11602 ShiftAmt = ShiftAmt & (32 - 1);
11603 SDValue V = N->getOperand(0);
11604 SDLoc DL(N);
11606 SDValue Res;
11607 MulAmt >>= ShiftAmt;
11609 if (MulAmt >= 0) {
11610 if (isPowerOf2_32(MulAmt - 1)) {
11611 // (mul x, 2^N + 1) => (add (shl x, N), x)
11612 Res = DAG.getNode(ISD::ADD, DL, VT,
11614 DAG.getNode(ISD::SHL, DL, VT,
11616 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11617 MVT::i32)));
11618 } else if (isPowerOf2_32(MulAmt + 1)) {
11619 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11620 Res = DAG.getNode(ISD::SUB, DL, VT,
11621 DAG.getNode(ISD::SHL, DL, VT,
11623 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11624 MVT::i32)),
11626 } else
11627 return SDValue();
11628 } else {
11629 uint64_t MulAmtAbs = -MulAmt;
11630 if (isPowerOf2_32(MulAmtAbs + 1)) {
11631 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11632 Res = DAG.getNode(ISD::SUB, DL, VT,
11634 DAG.getNode(ISD::SHL, DL, VT,
11636 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11637 MVT::i32)));
11638 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11639 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11640 Res = DAG.getNode(ISD::ADD, DL, VT,
11642 DAG.getNode(ISD::SHL, DL, VT,
11644 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11645 MVT::i32)));
11646 Res = DAG.getNode(ISD::SUB, DL, VT,
11647 DAG.getConstant(0, DL, MVT::i32), Res);
11648 } else
11649 return SDValue();
11652 if (ShiftAmt != 0)
11653 Res = DAG.getNode(ISD::SHL, DL, VT,
11654 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11656 // Do not add new nodes to DAG combiner worklist.
11657 DCI.CombineTo(N, Res, false);
11658 return SDValue();
11661 static SDValue CombineANDShift(SDNode *N,
11662 TargetLowering::DAGCombinerInfo &DCI,
11663 const ARMSubtarget *Subtarget) {
11664 // Allow DAGCombine to pattern-match before we touch the canonical form.
11665 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11666 return SDValue();
11668 if (N->getValueType(0) != MVT::i32)
11669 return SDValue();
11671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11672 if (!N1C)
11673 return SDValue();
11675 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11676 // Don't transform uxtb/uxth.
11677 if (C1 == 255 || C1 == 65535)
11678 return SDValue();
11680 SDNode *N0 = N->getOperand(0).getNode();
11681 if (!N0->hasOneUse())
11682 return SDValue();
11684 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11685 return SDValue();
11687 bool LeftShift = N0->getOpcode() == ISD::SHL;
11689 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11690 if (!N01C)
11691 return SDValue();
11693 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11694 if (!C2 || C2 >= 32)
11695 return SDValue();
11697 // Clear irrelevant bits in the mask.
11698 if (LeftShift)
11699 C1 &= (-1U << C2);
11700 else
11701 C1 &= (-1U >> C2);
11703 SelectionDAG &DAG = DCI.DAG;
11704 SDLoc DL(N);
11706 // We have a pattern of the form "(and (shl x, c2) c1)" or
11707 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11708 // transform to a pair of shifts, to save materializing c1.
11710 // First pattern: right shift, then mask off leading bits.
11711 // FIXME: Use demanded bits?
11712 if (!LeftShift && isMask_32(C1)) {
11713 uint32_t C3 = countLeadingZeros(C1);
11714 if (C2 < C3) {
11715 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11716 DAG.getConstant(C3 - C2, DL, MVT::i32));
11717 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11718 DAG.getConstant(C3, DL, MVT::i32));
11722 // First pattern, reversed: left shift, then mask off trailing bits.
11723 if (LeftShift && isMask_32(~C1)) {
11724 uint32_t C3 = countTrailingZeros(C1);
11725 if (C2 < C3) {
11726 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11727 DAG.getConstant(C3 - C2, DL, MVT::i32));
11728 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11729 DAG.getConstant(C3, DL, MVT::i32));
11733 // Second pattern: left shift, then mask off leading bits.
11734 // FIXME: Use demanded bits?
11735 if (LeftShift && isShiftedMask_32(C1)) {
11736 uint32_t Trailing = countTrailingZeros(C1);
11737 uint32_t C3 = countLeadingZeros(C1);
11738 if (Trailing == C2 && C2 + C3 < 32) {
11739 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11740 DAG.getConstant(C2 + C3, DL, MVT::i32));
11741 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11742 DAG.getConstant(C3, DL, MVT::i32));
11746 // Second pattern, reversed: right shift, then mask off trailing bits.
11747 // FIXME: Handle other patterns of known/demanded bits.
11748 if (!LeftShift && isShiftedMask_32(C1)) {
11749 uint32_t Leading = countLeadingZeros(C1);
11750 uint32_t C3 = countTrailingZeros(C1);
11751 if (Leading == C2 && C2 + C3 < 32) {
11752 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11753 DAG.getConstant(C2 + C3, DL, MVT::i32));
11754 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11755 DAG.getConstant(C3, DL, MVT::i32));
11759 // FIXME: Transform "(and (shl x, c2) c1)" ->
11760 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11761 // c1.
11762 return SDValue();
11765 static SDValue PerformANDCombine(SDNode *N,
11766 TargetLowering::DAGCombinerInfo &DCI,
11767 const ARMSubtarget *Subtarget) {
11768 // Attempt to use immediate-form VBIC
11769 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11770 SDLoc dl(N);
11771 EVT VT = N->getValueType(0);
11772 SelectionDAG &DAG = DCI.DAG;
11774 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11775 return SDValue();
11777 APInt SplatBits, SplatUndef;
11778 unsigned SplatBitSize;
11779 bool HasAnyUndefs;
11780 if (BVN && Subtarget->hasNEON() &&
11781 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11782 if (SplatBitSize <= 64) {
11783 EVT VbicVT;
11784 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11785 SplatUndef.getZExtValue(), SplatBitSize,
11786 DAG, dl, VbicVT, VT.is128BitVector(),
11787 OtherModImm);
11788 if (Val.getNode()) {
11789 SDValue Input =
11790 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11791 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11792 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11797 if (!Subtarget->isThumb1Only()) {
11798 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11799 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11800 return Result;
11802 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11803 return Result;
11806 if (Subtarget->isThumb1Only())
11807 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11808 return Result;
11810 return SDValue();
11813 // Try combining OR nodes to SMULWB, SMULWT.
11814 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11815 TargetLowering::DAGCombinerInfo &DCI,
11816 const ARMSubtarget *Subtarget) {
11817 if (!Subtarget->hasV6Ops() ||
11818 (Subtarget->isThumb() &&
11819 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11820 return SDValue();
11822 SDValue SRL = OR->getOperand(0);
11823 SDValue SHL = OR->getOperand(1);
11825 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11826 SRL = OR->getOperand(1);
11827 SHL = OR->getOperand(0);
11829 if (!isSRL16(SRL) || !isSHL16(SHL))
11830 return SDValue();
11832 // The first operands to the shifts need to be the two results from the
11833 // same smul_lohi node.
11834 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11835 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11836 return SDValue();
11838 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11839 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11840 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11841 return SDValue();
11843 // Now we have:
11844 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11845 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11846 // For SMUWB the 16-bit value will signed extended somehow.
11847 // For SMULWT only the SRA is required.
11848 // Check both sides of SMUL_LOHI
11849 SDValue OpS16 = SMULLOHI->getOperand(0);
11850 SDValue OpS32 = SMULLOHI->getOperand(1);
11852 SelectionDAG &DAG = DCI.DAG;
11853 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11854 OpS16 = OpS32;
11855 OpS32 = SMULLOHI->getOperand(0);
11858 SDLoc dl(OR);
11859 unsigned Opcode = 0;
11860 if (isS16(OpS16, DAG))
11861 Opcode = ARMISD::SMULWB;
11862 else if (isSRA16(OpS16)) {
11863 Opcode = ARMISD::SMULWT;
11864 OpS16 = OpS16->getOperand(0);
11866 else
11867 return SDValue();
11869 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11870 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11871 return SDValue(OR, 0);
11874 static SDValue PerformORCombineToBFI(SDNode *N,
11875 TargetLowering::DAGCombinerInfo &DCI,
11876 const ARMSubtarget *Subtarget) {
11877 // BFI is only available on V6T2+
11878 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11879 return SDValue();
11881 EVT VT = N->getValueType(0);
11882 SDValue N0 = N->getOperand(0);
11883 SDValue N1 = N->getOperand(1);
11884 SelectionDAG &DAG = DCI.DAG;
11885 SDLoc DL(N);
11886 // 1) or (and A, mask), val => ARMbfi A, val, mask
11887 // iff (val & mask) == val
11889 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11890 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11891 // && mask == ~mask2
11892 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11893 // && ~mask == mask2
11894 // (i.e., copy a bitfield value into another bitfield of the same width)
11896 if (VT != MVT::i32)
11897 return SDValue();
11899 SDValue N00 = N0.getOperand(0);
11901 // The value and the mask need to be constants so we can verify this is
11902 // actually a bitfield set. If the mask is 0xffff, we can do better
11903 // via a movt instruction, so don't use BFI in that case.
11904 SDValue MaskOp = N0.getOperand(1);
11905 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11906 if (!MaskC)
11907 return SDValue();
11908 unsigned Mask = MaskC->getZExtValue();
11909 if (Mask == 0xffff)
11910 return SDValue();
11911 SDValue Res;
11912 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11913 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11914 if (N1C) {
11915 unsigned Val = N1C->getZExtValue();
11916 if ((Val & ~Mask) != Val)
11917 return SDValue();
11919 if (ARM::isBitFieldInvertedMask(Mask)) {
11920 Val >>= countTrailingZeros(~Mask);
11922 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11923 DAG.getConstant(Val, DL, MVT::i32),
11924 DAG.getConstant(Mask, DL, MVT::i32));
11926 DCI.CombineTo(N, Res, false);
11927 // Return value from the original node to inform the combiner than N is
11928 // now dead.
11929 return SDValue(N, 0);
11931 } else if (N1.getOpcode() == ISD::AND) {
11932 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11933 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11934 if (!N11C)
11935 return SDValue();
11936 unsigned Mask2 = N11C->getZExtValue();
11938 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11939 // as is to match.
11940 if (ARM::isBitFieldInvertedMask(Mask) &&
11941 (Mask == ~Mask2)) {
11942 // The pack halfword instruction works better for masks that fit it,
11943 // so use that when it's available.
11944 if (Subtarget->hasDSP() &&
11945 (Mask == 0xffff || Mask == 0xffff0000))
11946 return SDValue();
11947 // 2a
11948 unsigned amt = countTrailingZeros(Mask2);
11949 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11950 DAG.getConstant(amt, DL, MVT::i32));
11951 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11952 DAG.getConstant(Mask, DL, MVT::i32));
11953 DCI.CombineTo(N, Res, false);
11954 // Return value from the original node to inform the combiner than N is
11955 // now dead.
11956 return SDValue(N, 0);
11957 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11958 (~Mask == Mask2)) {
11959 // The pack halfword instruction works better for masks that fit it,
11960 // so use that when it's available.
11961 if (Subtarget->hasDSP() &&
11962 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11963 return SDValue();
11964 // 2b
11965 unsigned lsb = countTrailingZeros(Mask);
11966 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11967 DAG.getConstant(lsb, DL, MVT::i32));
11968 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11969 DAG.getConstant(Mask2, DL, MVT::i32));
11970 DCI.CombineTo(N, Res, false);
11971 // Return value from the original node to inform the combiner than N is
11972 // now dead.
11973 return SDValue(N, 0);
11977 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11978 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11979 ARM::isBitFieldInvertedMask(~Mask)) {
11980 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11981 // where lsb(mask) == #shamt and masked bits of B are known zero.
11982 SDValue ShAmt = N00.getOperand(1);
11983 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11984 unsigned LSB = countTrailingZeros(Mask);
11985 if (ShAmtC != LSB)
11986 return SDValue();
11988 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11989 DAG.getConstant(~Mask, DL, MVT::i32));
11991 DCI.CombineTo(N, Res, false);
11992 // Return value from the original node to inform the combiner than N is
11993 // now dead.
11994 return SDValue(N, 0);
11997 return SDValue();
12000 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12001 switch (CC) {
12002 case ARMCC::EQ:
12003 case ARMCC::NE:
12004 case ARMCC::LE:
12005 case ARMCC::GT:
12006 case ARMCC::GE:
12007 case ARMCC::LT:
12008 return true;
12009 case ARMCC::HS:
12010 case ARMCC::HI:
12011 return !IsFloat;
12012 default:
12013 return false;
12017 static SDValue PerformORCombine_i1(SDNode *N,
12018 TargetLowering::DAGCombinerInfo &DCI,
12019 const ARMSubtarget *Subtarget) {
12020 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12021 // together with predicates
12022 EVT VT = N->getValueType(0);
12023 SDValue N0 = N->getOperand(0);
12024 SDValue N1 = N->getOperand(1);
12026 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12027 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12028 if (N0->getOpcode() == ARMISD::VCMP)
12029 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12030 ->getZExtValue();
12031 else if (N0->getOpcode() == ARMISD::VCMPZ)
12032 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12033 ->getZExtValue();
12034 if (N1->getOpcode() == ARMISD::VCMP)
12035 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12036 ->getZExtValue();
12037 else if (N1->getOpcode() == ARMISD::VCMPZ)
12038 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12039 ->getZExtValue();
12041 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12042 return SDValue();
12044 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12045 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12047 if (!isValidMVECond(Opposite0,
12048 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12049 !isValidMVECond(Opposite1,
12050 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12051 return SDValue();
12053 SmallVector<SDValue, 4> Ops0;
12054 Ops0.push_back(N0->getOperand(0));
12055 if (N0->getOpcode() == ARMISD::VCMP)
12056 Ops0.push_back(N0->getOperand(1));
12057 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12058 SmallVector<SDValue, 4> Ops1;
12059 Ops1.push_back(N1->getOperand(0));
12060 if (N1->getOpcode() == ARMISD::VCMP)
12061 Ops1.push_back(N1->getOperand(1));
12062 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12064 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12065 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12066 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12067 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12068 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12071 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12072 static SDValue PerformORCombine(SDNode *N,
12073 TargetLowering::DAGCombinerInfo &DCI,
12074 const ARMSubtarget *Subtarget) {
12075 // Attempt to use immediate-form VORR
12076 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12077 SDLoc dl(N);
12078 EVT VT = N->getValueType(0);
12079 SelectionDAG &DAG = DCI.DAG;
12081 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12082 return SDValue();
12084 APInt SplatBits, SplatUndef;
12085 unsigned SplatBitSize;
12086 bool HasAnyUndefs;
12087 if (BVN && Subtarget->hasNEON() &&
12088 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12089 if (SplatBitSize <= 64) {
12090 EVT VorrVT;
12091 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12092 SplatUndef.getZExtValue(), SplatBitSize,
12093 DAG, dl, VorrVT, VT.is128BitVector(),
12094 OtherModImm);
12095 if (Val.getNode()) {
12096 SDValue Input =
12097 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12098 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12099 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12104 if (!Subtarget->isThumb1Only()) {
12105 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12106 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12107 return Result;
12108 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12109 return Result;
12112 SDValue N0 = N->getOperand(0);
12113 SDValue N1 = N->getOperand(1);
12115 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12116 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12117 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12119 // The code below optimizes (or (and X, Y), Z).
12120 // The AND operand needs to have a single user to make these optimizations
12121 // profitable.
12122 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12123 return SDValue();
12125 APInt SplatUndef;
12126 unsigned SplatBitSize;
12127 bool HasAnyUndefs;
12129 APInt SplatBits0, SplatBits1;
12130 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12131 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12132 // Ensure that the second operand of both ands are constants
12133 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12134 HasAnyUndefs) && !HasAnyUndefs) {
12135 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12136 HasAnyUndefs) && !HasAnyUndefs) {
12137 // Ensure that the bit width of the constants are the same and that
12138 // the splat arguments are logical inverses as per the pattern we
12139 // are trying to simplify.
12140 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12141 SplatBits0 == ~SplatBits1) {
12142 // Canonicalize the vector type to make instruction selection
12143 // simpler.
12144 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12145 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12146 N0->getOperand(1),
12147 N0->getOperand(0),
12148 N1->getOperand(0));
12149 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12155 if (Subtarget->hasMVEIntegerOps() &&
12156 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12157 return PerformORCombine_i1(N, DCI, Subtarget);
12159 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12160 // reasonable.
12161 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12162 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12163 return Res;
12166 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12167 return Result;
12169 return SDValue();
12172 static SDValue PerformXORCombine(SDNode *N,
12173 TargetLowering::DAGCombinerInfo &DCI,
12174 const ARMSubtarget *Subtarget) {
12175 EVT VT = N->getValueType(0);
12176 SelectionDAG &DAG = DCI.DAG;
12178 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12179 return SDValue();
12181 if (!Subtarget->isThumb1Only()) {
12182 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12183 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12184 return Result;
12186 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12187 return Result;
12190 return SDValue();
12193 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12194 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12195 // their position in "to" (Rd).
12196 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12197 assert(N->getOpcode() == ARMISD::BFI);
12199 SDValue From = N->getOperand(1);
12200 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12201 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12203 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12204 // #C in the base of the SHR.
12205 if (From->getOpcode() == ISD::SRL &&
12206 isa<ConstantSDNode>(From->getOperand(1))) {
12207 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12208 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12209 FromMask <<= Shift.getLimitedValue(31);
12210 From = From->getOperand(0);
12213 return From;
12216 // If A and B contain one contiguous set of bits, does A | B == A . B?
12218 // Neither A nor B must be zero.
12219 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12220 unsigned LastActiveBitInA = A.countTrailingZeros();
12221 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12222 return LastActiveBitInA - 1 == FirstActiveBitInB;
12225 static SDValue FindBFIToCombineWith(SDNode *N) {
12226 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12227 // if one exists.
12228 APInt ToMask, FromMask;
12229 SDValue From = ParseBFI(N, ToMask, FromMask);
12230 SDValue To = N->getOperand(0);
12232 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12233 // aren't compatible, but not if they set the same bit in their destination as
12234 // we do (or that of any BFI we're going to combine with).
12235 SDValue V = To;
12236 APInt CombinedToMask = ToMask;
12237 while (V.getOpcode() == ARMISD::BFI) {
12238 APInt NewToMask, NewFromMask;
12239 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12240 if (NewFrom != From) {
12241 // This BFI has a different base. Keep going.
12242 CombinedToMask |= NewToMask;
12243 V = V.getOperand(0);
12244 continue;
12247 // Do the written bits conflict with any we've seen so far?
12248 if ((NewToMask & CombinedToMask).getBoolValue())
12249 // Conflicting bits - bail out because going further is unsafe.
12250 return SDValue();
12252 // Are the new bits contiguous when combined with the old bits?
12253 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12254 BitsProperlyConcatenate(FromMask, NewFromMask))
12255 return V;
12256 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12257 BitsProperlyConcatenate(NewFromMask, FromMask))
12258 return V;
12260 // We've seen a write to some bits, so track it.
12261 CombinedToMask |= NewToMask;
12262 // Keep going...
12263 V = V.getOperand(0);
12266 return SDValue();
12269 static SDValue PerformBFICombine(SDNode *N,
12270 TargetLowering::DAGCombinerInfo &DCI) {
12271 SDValue N1 = N->getOperand(1);
12272 if (N1.getOpcode() == ISD::AND) {
12273 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12274 // the bits being cleared by the AND are not demanded by the BFI.
12275 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12276 if (!N11C)
12277 return SDValue();
12278 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12279 unsigned LSB = countTrailingZeros(~InvMask);
12280 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12281 assert(Width <
12282 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12283 "undefined behavior");
12284 unsigned Mask = (1u << Width) - 1;
12285 unsigned Mask2 = N11C->getZExtValue();
12286 if ((Mask & (~Mask2)) == 0)
12287 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12288 N->getOperand(0), N1.getOperand(0),
12289 N->getOperand(2));
12290 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12291 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12292 // Keep track of any consecutive bits set that all come from the same base
12293 // value. We can combine these together into a single BFI.
12294 SDValue CombineBFI = FindBFIToCombineWith(N);
12295 if (CombineBFI == SDValue())
12296 return SDValue();
12298 // We've found a BFI.
12299 APInt ToMask1, FromMask1;
12300 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12302 APInt ToMask2, FromMask2;
12303 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12304 assert(From1 == From2);
12305 (void)From2;
12307 // First, unlink CombineBFI.
12308 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12309 // Then create a new BFI, combining the two together.
12310 APInt NewFromMask = FromMask1 | FromMask2;
12311 APInt NewToMask = ToMask1 | ToMask2;
12313 EVT VT = N->getValueType(0);
12314 SDLoc dl(N);
12316 if (NewFromMask[0] == 0)
12317 From1 = DCI.DAG.getNode(
12318 ISD::SRL, dl, VT, From1,
12319 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12320 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12321 DCI.DAG.getConstant(~NewToMask, dl, VT));
12323 return SDValue();
12326 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12327 /// ARMISD::VMOVRRD.
12328 static SDValue PerformVMOVRRDCombine(SDNode *N,
12329 TargetLowering::DAGCombinerInfo &DCI,
12330 const ARMSubtarget *Subtarget) {
12331 // vmovrrd(vmovdrr x, y) -> x,y
12332 SDValue InDouble = N->getOperand(0);
12333 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12334 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12336 // vmovrrd(load f64) -> (load i32), (load i32)
12337 SDNode *InNode = InDouble.getNode();
12338 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12339 InNode->getValueType(0) == MVT::f64 &&
12340 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12341 !cast<LoadSDNode>(InNode)->isVolatile()) {
12342 // TODO: Should this be done for non-FrameIndex operands?
12343 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12345 SelectionDAG &DAG = DCI.DAG;
12346 SDLoc DL(LD);
12347 SDValue BasePtr = LD->getBasePtr();
12348 SDValue NewLD1 =
12349 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12350 LD->getAlignment(), LD->getMemOperand()->getFlags());
12352 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12353 DAG.getConstant(4, DL, MVT::i32));
12355 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12356 LD->getPointerInfo().getWithOffset(4),
12357 std::min(4U, LD->getAlignment()),
12358 LD->getMemOperand()->getFlags());
12360 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12361 if (DCI.DAG.getDataLayout().isBigEndian())
12362 std::swap (NewLD1, NewLD2);
12363 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12364 return Result;
12367 return SDValue();
12370 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12371 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12372 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12373 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12374 SDValue Op0 = N->getOperand(0);
12375 SDValue Op1 = N->getOperand(1);
12376 if (Op0.getOpcode() == ISD::BITCAST)
12377 Op0 = Op0.getOperand(0);
12378 if (Op1.getOpcode() == ISD::BITCAST)
12379 Op1 = Op1.getOperand(0);
12380 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12381 Op0.getNode() == Op1.getNode() &&
12382 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12383 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12384 N->getValueType(0), Op0.getOperand(0));
12385 return SDValue();
12388 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12389 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12390 /// i64 vector to have f64 elements, since the value can then be loaded
12391 /// directly into a VFP register.
12392 static bool hasNormalLoadOperand(SDNode *N) {
12393 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12394 for (unsigned i = 0; i < NumElts; ++i) {
12395 SDNode *Elt = N->getOperand(i).getNode();
12396 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12397 return true;
12399 return false;
12402 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12403 /// ISD::BUILD_VECTOR.
12404 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12405 TargetLowering::DAGCombinerInfo &DCI,
12406 const ARMSubtarget *Subtarget) {
12407 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12408 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12409 // into a pair of GPRs, which is fine when the value is used as a scalar,
12410 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12411 SelectionDAG &DAG = DCI.DAG;
12412 if (N->getNumOperands() == 2)
12413 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12414 return RV;
12416 // Load i64 elements as f64 values so that type legalization does not split
12417 // them up into i32 values.
12418 EVT VT = N->getValueType(0);
12419 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12420 return SDValue();
12421 SDLoc dl(N);
12422 SmallVector<SDValue, 8> Ops;
12423 unsigned NumElts = VT.getVectorNumElements();
12424 for (unsigned i = 0; i < NumElts; ++i) {
12425 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12426 Ops.push_back(V);
12427 // Make the DAGCombiner fold the bitcast.
12428 DCI.AddToWorklist(V.getNode());
12430 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12431 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12432 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12435 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12436 static SDValue
12437 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12438 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12439 // At that time, we may have inserted bitcasts from integer to float.
12440 // If these bitcasts have survived DAGCombine, change the lowering of this
12441 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12442 // force to use floating point types.
12444 // Make sure we can change the type of the vector.
12445 // This is possible iff:
12446 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12447 // 1.1. Vector is used only once.
12448 // 1.2. Use is a bit convert to an integer type.
12449 // 2. The size of its operands are 32-bits (64-bits are not legal).
12450 EVT VT = N->getValueType(0);
12451 EVT EltVT = VT.getVectorElementType();
12453 // Check 1.1. and 2.
12454 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12455 return SDValue();
12457 // By construction, the input type must be float.
12458 assert(EltVT == MVT::f32 && "Unexpected type!");
12460 // Check 1.2.
12461 SDNode *Use = *N->use_begin();
12462 if (Use->getOpcode() != ISD::BITCAST ||
12463 Use->getValueType(0).isFloatingPoint())
12464 return SDValue();
12466 // Check profitability.
12467 // Model is, if more than half of the relevant operands are bitcast from
12468 // i32, turn the build_vector into a sequence of insert_vector_elt.
12469 // Relevant operands are everything that is not statically
12470 // (i.e., at compile time) bitcasted.
12471 unsigned NumOfBitCastedElts = 0;
12472 unsigned NumElts = VT.getVectorNumElements();
12473 unsigned NumOfRelevantElts = NumElts;
12474 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12475 SDValue Elt = N->getOperand(Idx);
12476 if (Elt->getOpcode() == ISD::BITCAST) {
12477 // Assume only bit cast to i32 will go away.
12478 if (Elt->getOperand(0).getValueType() == MVT::i32)
12479 ++NumOfBitCastedElts;
12480 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12481 // Constants are statically casted, thus do not count them as
12482 // relevant operands.
12483 --NumOfRelevantElts;
12486 // Check if more than half of the elements require a non-free bitcast.
12487 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12488 return SDValue();
12490 SelectionDAG &DAG = DCI.DAG;
12491 // Create the new vector type.
12492 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12493 // Check if the type is legal.
12494 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12495 if (!TLI.isTypeLegal(VecVT))
12496 return SDValue();
12498 // Combine:
12499 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12500 // => BITCAST INSERT_VECTOR_ELT
12501 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12502 // (BITCAST EN), N.
12503 SDValue Vec = DAG.getUNDEF(VecVT);
12504 SDLoc dl(N);
12505 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12506 SDValue V = N->getOperand(Idx);
12507 if (V.isUndef())
12508 continue;
12509 if (V.getOpcode() == ISD::BITCAST &&
12510 V->getOperand(0).getValueType() == MVT::i32)
12511 // Fold obvious case.
12512 V = V.getOperand(0);
12513 else {
12514 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12515 // Make the DAGCombiner fold the bitcasts.
12516 DCI.AddToWorklist(V.getNode());
12518 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12519 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12521 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12522 // Make the DAGCombiner fold the bitcasts.
12523 DCI.AddToWorklist(Vec.getNode());
12524 return Vec;
12527 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12528 /// ISD::INSERT_VECTOR_ELT.
12529 static SDValue PerformInsertEltCombine(SDNode *N,
12530 TargetLowering::DAGCombinerInfo &DCI) {
12531 // Bitcast an i64 load inserted into a vector to f64.
12532 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12533 EVT VT = N->getValueType(0);
12534 SDNode *Elt = N->getOperand(1).getNode();
12535 if (VT.getVectorElementType() != MVT::i64 ||
12536 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12537 return SDValue();
12539 SelectionDAG &DAG = DCI.DAG;
12540 SDLoc dl(N);
12541 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12542 VT.getVectorNumElements());
12543 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12544 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12545 // Make the DAGCombiner fold the bitcasts.
12546 DCI.AddToWorklist(Vec.getNode());
12547 DCI.AddToWorklist(V.getNode());
12548 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12549 Vec, V, N->getOperand(2));
12550 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12553 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12554 /// ISD::VECTOR_SHUFFLE.
12555 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12556 // The LLVM shufflevector instruction does not require the shuffle mask
12557 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12558 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12559 // operands do not match the mask length, they are extended by concatenating
12560 // them with undef vectors. That is probably the right thing for other
12561 // targets, but for NEON it is better to concatenate two double-register
12562 // size vector operands into a single quad-register size vector. Do that
12563 // transformation here:
12564 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12565 // shuffle(concat(v1, v2), undef)
12566 SDValue Op0 = N->getOperand(0);
12567 SDValue Op1 = N->getOperand(1);
12568 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12569 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12570 Op0.getNumOperands() != 2 ||
12571 Op1.getNumOperands() != 2)
12572 return SDValue();
12573 SDValue Concat0Op1 = Op0.getOperand(1);
12574 SDValue Concat1Op1 = Op1.getOperand(1);
12575 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12576 return SDValue();
12577 // Skip the transformation if any of the types are illegal.
12578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12579 EVT VT = N->getValueType(0);
12580 if (!TLI.isTypeLegal(VT) ||
12581 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12582 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12583 return SDValue();
12585 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12586 Op0.getOperand(0), Op1.getOperand(0));
12587 // Translate the shuffle mask.
12588 SmallVector<int, 16> NewMask;
12589 unsigned NumElts = VT.getVectorNumElements();
12590 unsigned HalfElts = NumElts/2;
12591 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12592 for (unsigned n = 0; n < NumElts; ++n) {
12593 int MaskElt = SVN->getMaskElt(n);
12594 int NewElt = -1;
12595 if (MaskElt < (int)HalfElts)
12596 NewElt = MaskElt;
12597 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12598 NewElt = HalfElts + MaskElt - NumElts;
12599 NewMask.push_back(NewElt);
12601 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12602 DAG.getUNDEF(VT), NewMask);
12605 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12606 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12607 /// base address updates.
12608 /// For generic load/stores, the memory type is assumed to be a vector.
12609 /// The caller is assumed to have checked legality.
12610 static SDValue CombineBaseUpdate(SDNode *N,
12611 TargetLowering::DAGCombinerInfo &DCI) {
12612 SelectionDAG &DAG = DCI.DAG;
12613 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12614 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12615 const bool isStore = N->getOpcode() == ISD::STORE;
12616 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12617 SDValue Addr = N->getOperand(AddrOpIdx);
12618 MemSDNode *MemN = cast<MemSDNode>(N);
12619 SDLoc dl(N);
12621 // Search for a use of the address operand that is an increment.
12622 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12623 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12624 SDNode *User = *UI;
12625 if (User->getOpcode() != ISD::ADD ||
12626 UI.getUse().getResNo() != Addr.getResNo())
12627 continue;
12629 // Check that the add is independent of the load/store. Otherwise, folding
12630 // it would create a cycle. We can avoid searching through Addr as it's a
12631 // predecessor to both.
12632 SmallPtrSet<const SDNode *, 32> Visited;
12633 SmallVector<const SDNode *, 16> Worklist;
12634 Visited.insert(Addr.getNode());
12635 Worklist.push_back(N);
12636 Worklist.push_back(User);
12637 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12638 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12639 continue;
12641 // Find the new opcode for the updating load/store.
12642 bool isLoadOp = true;
12643 bool isLaneOp = false;
12644 unsigned NewOpc = 0;
12645 unsigned NumVecs = 0;
12646 if (isIntrinsic) {
12647 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12648 switch (IntNo) {
12649 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12650 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12651 NumVecs = 1; break;
12652 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12653 NumVecs = 2; break;
12654 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12655 NumVecs = 3; break;
12656 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12657 NumVecs = 4; break;
12658 case Intrinsic::arm_neon_vld2dup:
12659 case Intrinsic::arm_neon_vld3dup:
12660 case Intrinsic::arm_neon_vld4dup:
12661 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12662 // combining base updates for such intrinsics.
12663 continue;
12664 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12665 NumVecs = 2; isLaneOp = true; break;
12666 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12667 NumVecs = 3; isLaneOp = true; break;
12668 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12669 NumVecs = 4; isLaneOp = true; break;
12670 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12671 NumVecs = 1; isLoadOp = false; break;
12672 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12673 NumVecs = 2; isLoadOp = false; break;
12674 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12675 NumVecs = 3; isLoadOp = false; break;
12676 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12677 NumVecs = 4; isLoadOp = false; break;
12678 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12679 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12680 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12681 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12682 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12683 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12685 } else {
12686 isLaneOp = true;
12687 switch (N->getOpcode()) {
12688 default: llvm_unreachable("unexpected opcode for Neon base update");
12689 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12690 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12691 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12692 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12693 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12694 NumVecs = 1; isLaneOp = false; break;
12695 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12696 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12700 // Find the size of memory referenced by the load/store.
12701 EVT VecTy;
12702 if (isLoadOp) {
12703 VecTy = N->getValueType(0);
12704 } else if (isIntrinsic) {
12705 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12706 } else {
12707 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12708 VecTy = N->getOperand(1).getValueType();
12711 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12712 if (isLaneOp)
12713 NumBytes /= VecTy.getVectorNumElements();
12715 // If the increment is a constant, it must match the memory ref size.
12716 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12717 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12718 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12719 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12720 // separate instructions that make it harder to use a non-constant update.
12721 continue;
12724 // OK, we found an ADD we can fold into the base update.
12725 // Now, create a _UPD node, taking care of not breaking alignment.
12727 EVT AlignedVecTy = VecTy;
12728 unsigned Alignment = MemN->getAlignment();
12730 // If this is a less-than-standard-aligned load/store, change the type to
12731 // match the standard alignment.
12732 // The alignment is overlooked when selecting _UPD variants; and it's
12733 // easier to introduce bitcasts here than fix that.
12734 // There are 3 ways to get to this base-update combine:
12735 // - intrinsics: they are assumed to be properly aligned (to the standard
12736 // alignment of the memory type), so we don't need to do anything.
12737 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12738 // intrinsics, so, likewise, there's nothing to do.
12739 // - generic load/store instructions: the alignment is specified as an
12740 // explicit operand, rather than implicitly as the standard alignment
12741 // of the memory type (like the intrisics). We need to change the
12742 // memory type to match the explicit alignment. That way, we don't
12743 // generate non-standard-aligned ARMISD::VLDx nodes.
12744 if (isa<LSBaseSDNode>(N)) {
12745 if (Alignment == 0)
12746 Alignment = 1;
12747 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12748 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12749 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12750 assert(!isLaneOp && "Unexpected generic load/store lane.");
12751 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12752 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12754 // Don't set an explicit alignment on regular load/stores that we want
12755 // to transform to VLD/VST 1_UPD nodes.
12756 // This matches the behavior of regular load/stores, which only get an
12757 // explicit alignment if the MMO alignment is larger than the standard
12758 // alignment of the memory type.
12759 // Intrinsics, however, always get an explicit alignment, set to the
12760 // alignment of the MMO.
12761 Alignment = 1;
12764 // Create the new updating load/store node.
12765 // First, create an SDVTList for the new updating node's results.
12766 EVT Tys[6];
12767 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12768 unsigned n;
12769 for (n = 0; n < NumResultVecs; ++n)
12770 Tys[n] = AlignedVecTy;
12771 Tys[n++] = MVT::i32;
12772 Tys[n] = MVT::Other;
12773 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12775 // Then, gather the new node's operands.
12776 SmallVector<SDValue, 8> Ops;
12777 Ops.push_back(N->getOperand(0)); // incoming chain
12778 Ops.push_back(N->getOperand(AddrOpIdx));
12779 Ops.push_back(Inc);
12781 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12782 // Try to match the intrinsic's signature
12783 Ops.push_back(StN->getValue());
12784 } else {
12785 // Loads (and of course intrinsics) match the intrinsics' signature,
12786 // so just add all but the alignment operand.
12787 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12788 Ops.push_back(N->getOperand(i));
12791 // For all node types, the alignment operand is always the last one.
12792 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12794 // If this is a non-standard-aligned STORE, the penultimate operand is the
12795 // stored value. Bitcast it to the aligned type.
12796 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12797 SDValue &StVal = Ops[Ops.size()-2];
12798 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12801 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12802 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12803 MemN->getMemOperand());
12805 // Update the uses.
12806 SmallVector<SDValue, 5> NewResults;
12807 for (unsigned i = 0; i < NumResultVecs; ++i)
12808 NewResults.push_back(SDValue(UpdN.getNode(), i));
12810 // If this is an non-standard-aligned LOAD, the first result is the loaded
12811 // value. Bitcast it to the expected result type.
12812 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12813 SDValue &LdVal = NewResults[0];
12814 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12817 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12818 DCI.CombineTo(N, NewResults);
12819 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12821 break;
12823 return SDValue();
12826 static SDValue PerformVLDCombine(SDNode *N,
12827 TargetLowering::DAGCombinerInfo &DCI) {
12828 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12829 return SDValue();
12831 return CombineBaseUpdate(N, DCI);
12834 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12835 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12836 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12837 /// return true.
12838 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12839 SelectionDAG &DAG = DCI.DAG;
12840 EVT VT = N->getValueType(0);
12841 // vldN-dup instructions only support 64-bit vectors for N > 1.
12842 if (!VT.is64BitVector())
12843 return false;
12845 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12846 SDNode *VLD = N->getOperand(0).getNode();
12847 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12848 return false;
12849 unsigned NumVecs = 0;
12850 unsigned NewOpc = 0;
12851 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12852 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12853 NumVecs = 2;
12854 NewOpc = ARMISD::VLD2DUP;
12855 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12856 NumVecs = 3;
12857 NewOpc = ARMISD::VLD3DUP;
12858 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12859 NumVecs = 4;
12860 NewOpc = ARMISD::VLD4DUP;
12861 } else {
12862 return false;
12865 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12866 // numbers match the load.
12867 unsigned VLDLaneNo =
12868 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12869 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12870 UI != UE; ++UI) {
12871 // Ignore uses of the chain result.
12872 if (UI.getUse().getResNo() == NumVecs)
12873 continue;
12874 SDNode *User = *UI;
12875 if (User->getOpcode() != ARMISD::VDUPLANE ||
12876 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12877 return false;
12880 // Create the vldN-dup node.
12881 EVT Tys[5];
12882 unsigned n;
12883 for (n = 0; n < NumVecs; ++n)
12884 Tys[n] = VT;
12885 Tys[n] = MVT::Other;
12886 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12887 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12888 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12889 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12890 Ops, VLDMemInt->getMemoryVT(),
12891 VLDMemInt->getMemOperand());
12893 // Update the uses.
12894 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12895 UI != UE; ++UI) {
12896 unsigned ResNo = UI.getUse().getResNo();
12897 // Ignore uses of the chain result.
12898 if (ResNo == NumVecs)
12899 continue;
12900 SDNode *User = *UI;
12901 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12904 // Now the vldN-lane intrinsic is dead except for its chain result.
12905 // Update uses of the chain.
12906 std::vector<SDValue> VLDDupResults;
12907 for (unsigned n = 0; n < NumVecs; ++n)
12908 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12909 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12910 DCI.CombineTo(VLD, VLDDupResults);
12912 return true;
12915 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12916 /// ARMISD::VDUPLANE.
12917 static SDValue PerformVDUPLANECombine(SDNode *N,
12918 TargetLowering::DAGCombinerInfo &DCI) {
12919 SDValue Op = N->getOperand(0);
12921 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12922 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12923 if (CombineVLDDUP(N, DCI))
12924 return SDValue(N, 0);
12926 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12927 // redundant. Ignore bit_converts for now; element sizes are checked below.
12928 while (Op.getOpcode() == ISD::BITCAST)
12929 Op = Op.getOperand(0);
12930 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12931 return SDValue();
12933 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12934 unsigned EltSize = Op.getScalarValueSizeInBits();
12935 // The canonical VMOV for a zero vector uses a 32-bit element size.
12936 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12937 unsigned EltBits;
12938 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12939 EltSize = 8;
12940 EVT VT = N->getValueType(0);
12941 if (EltSize > VT.getScalarSizeInBits())
12942 return SDValue();
12944 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12947 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12948 static SDValue PerformVDUPCombine(SDNode *N,
12949 TargetLowering::DAGCombinerInfo &DCI,
12950 const ARMSubtarget *Subtarget) {
12951 SelectionDAG &DAG = DCI.DAG;
12952 SDValue Op = N->getOperand(0);
12954 if (!Subtarget->hasNEON())
12955 return SDValue();
12957 // Match VDUP(LOAD) -> VLD1DUP.
12958 // We match this pattern here rather than waiting for isel because the
12959 // transform is only legal for unindexed loads.
12960 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12961 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12962 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12963 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12964 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12965 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12966 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12967 Ops, LD->getMemoryVT(),
12968 LD->getMemOperand());
12969 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12970 return VLDDup;
12973 return SDValue();
12976 static SDValue PerformLOADCombine(SDNode *N,
12977 TargetLowering::DAGCombinerInfo &DCI) {
12978 EVT VT = N->getValueType(0);
12980 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12981 if (ISD::isNormalLoad(N) && VT.isVector() &&
12982 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12983 return CombineBaseUpdate(N, DCI);
12985 return SDValue();
12988 /// PerformSTORECombine - Target-specific dag combine xforms for
12989 /// ISD::STORE.
12990 static SDValue PerformSTORECombine(SDNode *N,
12991 TargetLowering::DAGCombinerInfo &DCI) {
12992 StoreSDNode *St = cast<StoreSDNode>(N);
12993 if (St->isVolatile())
12994 return SDValue();
12996 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12997 // pack all of the elements in one place. Next, store to memory in fewer
12998 // chunks.
12999 SDValue StVal = St->getValue();
13000 EVT VT = StVal.getValueType();
13001 if (St->isTruncatingStore() && VT.isVector()) {
13002 SelectionDAG &DAG = DCI.DAG;
13003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13004 EVT StVT = St->getMemoryVT();
13005 unsigned NumElems = VT.getVectorNumElements();
13006 assert(StVT != VT && "Cannot truncate to the same type");
13007 unsigned FromEltSz = VT.getScalarSizeInBits();
13008 unsigned ToEltSz = StVT.getScalarSizeInBits();
13010 // From, To sizes and ElemCount must be pow of two
13011 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
13013 // We are going to use the original vector elt for storing.
13014 // Accumulated smaller vector elements must be a multiple of the store size.
13015 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
13017 unsigned SizeRatio = FromEltSz / ToEltSz;
13018 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13020 // Create a type on which we perform the shuffle.
13021 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13022 NumElems*SizeRatio);
13023 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13025 SDLoc DL(St);
13026 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13027 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13028 for (unsigned i = 0; i < NumElems; ++i)
13029 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
13030 ? (i + 1) * SizeRatio - 1
13031 : i * SizeRatio;
13033 // Can't shuffle using an illegal type.
13034 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13036 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
13037 DAG.getUNDEF(WideVec.getValueType()),
13038 ShuffleVec);
13039 // At this point all of the data is stored at the bottom of the
13040 // register. We now need to save it to mem.
13042 // Find the largest store unit
13043 MVT StoreType = MVT::i8;
13044 for (MVT Tp : MVT::integer_valuetypes()) {
13045 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13046 StoreType = Tp;
13048 // Didn't find a legal store type.
13049 if (!TLI.isTypeLegal(StoreType))
13050 return SDValue();
13052 // Bitcast the original vector into a vector of store-size units
13053 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13054 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13055 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13056 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13057 SmallVector<SDValue, 8> Chains;
13058 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13059 TLI.getPointerTy(DAG.getDataLayout()));
13060 SDValue BasePtr = St->getBasePtr();
13062 // Perform one or more big stores into memory.
13063 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
13064 for (unsigned I = 0; I < E; I++) {
13065 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
13066 StoreType, ShuffWide,
13067 DAG.getIntPtrConstant(I, DL));
13068 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
13069 St->getPointerInfo(), St->getAlignment(),
13070 St->getMemOperand()->getFlags());
13071 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
13072 Increment);
13073 Chains.push_back(Ch);
13075 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13078 if (!ISD::isNormalStore(St))
13079 return SDValue();
13081 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13082 // ARM stores of arguments in the same cache line.
13083 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13084 StVal.getNode()->hasOneUse()) {
13085 SelectionDAG &DAG = DCI.DAG;
13086 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13087 SDLoc DL(St);
13088 SDValue BasePtr = St->getBasePtr();
13089 SDValue NewST1 = DAG.getStore(
13090 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13091 BasePtr, St->getPointerInfo(), St->getAlignment(),
13092 St->getMemOperand()->getFlags());
13094 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13095 DAG.getConstant(4, DL, MVT::i32));
13096 return DAG.getStore(NewST1.getValue(0), DL,
13097 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13098 OffsetPtr, St->getPointerInfo(),
13099 std::min(4U, St->getAlignment() / 2),
13100 St->getMemOperand()->getFlags());
13103 if (StVal.getValueType() == MVT::i64 &&
13104 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13106 // Bitcast an i64 store extracted from a vector to f64.
13107 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13108 SelectionDAG &DAG = DCI.DAG;
13109 SDLoc dl(StVal);
13110 SDValue IntVec = StVal.getOperand(0);
13111 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13112 IntVec.getValueType().getVectorNumElements());
13113 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13114 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13115 Vec, StVal.getOperand(1));
13116 dl = SDLoc(N);
13117 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13118 // Make the DAGCombiner fold the bitcasts.
13119 DCI.AddToWorklist(Vec.getNode());
13120 DCI.AddToWorklist(ExtElt.getNode());
13121 DCI.AddToWorklist(V.getNode());
13122 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13123 St->getPointerInfo(), St->getAlignment(),
13124 St->getMemOperand()->getFlags(), St->getAAInfo());
13127 // If this is a legal vector store, try to combine it into a VST1_UPD.
13128 if (ISD::isNormalStore(N) && VT.isVector() &&
13129 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13130 return CombineBaseUpdate(N, DCI);
13132 return SDValue();
13135 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13136 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13137 /// when the VMUL has a constant operand that is a power of 2.
13139 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13140 /// vmul.f32 d16, d17, d16
13141 /// vcvt.s32.f32 d16, d16
13142 /// becomes:
13143 /// vcvt.s32.f32 d16, d16, #3
13144 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13145 const ARMSubtarget *Subtarget) {
13146 if (!Subtarget->hasNEON())
13147 return SDValue();
13149 SDValue Op = N->getOperand(0);
13150 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13151 Op.getOpcode() != ISD::FMUL)
13152 return SDValue();
13154 SDValue ConstVec = Op->getOperand(1);
13155 if (!isa<BuildVectorSDNode>(ConstVec))
13156 return SDValue();
13158 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13159 uint32_t FloatBits = FloatTy.getSizeInBits();
13160 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13161 uint32_t IntBits = IntTy.getSizeInBits();
13162 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13163 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13164 // These instructions only exist converting from f32 to i32. We can handle
13165 // smaller integers by generating an extra truncate, but larger ones would
13166 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13167 // these intructions only support v2i32/v4i32 types.
13168 return SDValue();
13171 BitVector UndefElements;
13172 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13173 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13174 if (C == -1 || C == 0 || C > 32)
13175 return SDValue();
13177 SDLoc dl(N);
13178 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13179 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13180 Intrinsic::arm_neon_vcvtfp2fxu;
13181 SDValue FixConv = DAG.getNode(
13182 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13183 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13184 DAG.getConstant(C, dl, MVT::i32));
13186 if (IntBits < FloatBits)
13187 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13189 return FixConv;
13192 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13193 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13194 /// when the VDIV has a constant operand that is a power of 2.
13196 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13197 /// vcvt.f32.s32 d16, d16
13198 /// vdiv.f32 d16, d17, d16
13199 /// becomes:
13200 /// vcvt.f32.s32 d16, d16, #3
13201 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13202 const ARMSubtarget *Subtarget) {
13203 if (!Subtarget->hasNEON())
13204 return SDValue();
13206 SDValue Op = N->getOperand(0);
13207 unsigned OpOpcode = Op.getNode()->getOpcode();
13208 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13209 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13210 return SDValue();
13212 SDValue ConstVec = N->getOperand(1);
13213 if (!isa<BuildVectorSDNode>(ConstVec))
13214 return SDValue();
13216 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13217 uint32_t FloatBits = FloatTy.getSizeInBits();
13218 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13219 uint32_t IntBits = IntTy.getSizeInBits();
13220 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13221 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13222 // These instructions only exist converting from i32 to f32. We can handle
13223 // smaller integers by generating an extra extend, but larger ones would
13224 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13225 // these intructions only support v2i32/v4i32 types.
13226 return SDValue();
13229 BitVector UndefElements;
13230 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13231 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13232 if (C == -1 || C == 0 || C > 32)
13233 return SDValue();
13235 SDLoc dl(N);
13236 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13237 SDValue ConvInput = Op.getOperand(0);
13238 if (IntBits < FloatBits)
13239 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13240 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13241 ConvInput);
13243 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13244 Intrinsic::arm_neon_vcvtfxu2fp;
13245 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13246 Op.getValueType(),
13247 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13248 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13251 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13252 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13253 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13254 switch (IntNo) {
13255 default:
13256 // Don't do anything for most intrinsics.
13257 break;
13259 // Vector shifts: check for immediate versions and lower them.
13260 // Note: This is done during DAG combining instead of DAG legalizing because
13261 // the build_vectors for 64-bit vector element shift counts are generally
13262 // not legal, and it is hard to see their values after they get legalized to
13263 // loads from a constant pool.
13264 case Intrinsic::arm_neon_vshifts:
13265 case Intrinsic::arm_neon_vshiftu:
13266 case Intrinsic::arm_neon_vrshifts:
13267 case Intrinsic::arm_neon_vrshiftu:
13268 case Intrinsic::arm_neon_vrshiftn:
13269 case Intrinsic::arm_neon_vqshifts:
13270 case Intrinsic::arm_neon_vqshiftu:
13271 case Intrinsic::arm_neon_vqshiftsu:
13272 case Intrinsic::arm_neon_vqshiftns:
13273 case Intrinsic::arm_neon_vqshiftnu:
13274 case Intrinsic::arm_neon_vqshiftnsu:
13275 case Intrinsic::arm_neon_vqrshiftns:
13276 case Intrinsic::arm_neon_vqrshiftnu:
13277 case Intrinsic::arm_neon_vqrshiftnsu: {
13278 EVT VT = N->getOperand(1).getValueType();
13279 int64_t Cnt;
13280 unsigned VShiftOpc = 0;
13282 switch (IntNo) {
13283 case Intrinsic::arm_neon_vshifts:
13284 case Intrinsic::arm_neon_vshiftu:
13285 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13286 VShiftOpc = ARMISD::VSHLIMM;
13287 break;
13289 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13290 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13291 : ARMISD::VSHRuIMM);
13292 break;
13294 return SDValue();
13296 case Intrinsic::arm_neon_vrshifts:
13297 case Intrinsic::arm_neon_vrshiftu:
13298 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13299 break;
13300 return SDValue();
13302 case Intrinsic::arm_neon_vqshifts:
13303 case Intrinsic::arm_neon_vqshiftu:
13304 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13305 break;
13306 return SDValue();
13308 case Intrinsic::arm_neon_vqshiftsu:
13309 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13310 break;
13311 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13313 case Intrinsic::arm_neon_vrshiftn:
13314 case Intrinsic::arm_neon_vqshiftns:
13315 case Intrinsic::arm_neon_vqshiftnu:
13316 case Intrinsic::arm_neon_vqshiftnsu:
13317 case Intrinsic::arm_neon_vqrshiftns:
13318 case Intrinsic::arm_neon_vqrshiftnu:
13319 case Intrinsic::arm_neon_vqrshiftnsu:
13320 // Narrowing shifts require an immediate right shift.
13321 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13322 break;
13323 llvm_unreachable("invalid shift count for narrowing vector shift "
13324 "intrinsic");
13326 default:
13327 llvm_unreachable("unhandled vector shift");
13330 switch (IntNo) {
13331 case Intrinsic::arm_neon_vshifts:
13332 case Intrinsic::arm_neon_vshiftu:
13333 // Opcode already set above.
13334 break;
13335 case Intrinsic::arm_neon_vrshifts:
13336 VShiftOpc = ARMISD::VRSHRsIMM;
13337 break;
13338 case Intrinsic::arm_neon_vrshiftu:
13339 VShiftOpc = ARMISD::VRSHRuIMM;
13340 break;
13341 case Intrinsic::arm_neon_vrshiftn:
13342 VShiftOpc = ARMISD::VRSHRNIMM;
13343 break;
13344 case Intrinsic::arm_neon_vqshifts:
13345 VShiftOpc = ARMISD::VQSHLsIMM;
13346 break;
13347 case Intrinsic::arm_neon_vqshiftu:
13348 VShiftOpc = ARMISD::VQSHLuIMM;
13349 break;
13350 case Intrinsic::arm_neon_vqshiftsu:
13351 VShiftOpc = ARMISD::VQSHLsuIMM;
13352 break;
13353 case Intrinsic::arm_neon_vqshiftns:
13354 VShiftOpc = ARMISD::VQSHRNsIMM;
13355 break;
13356 case Intrinsic::arm_neon_vqshiftnu:
13357 VShiftOpc = ARMISD::VQSHRNuIMM;
13358 break;
13359 case Intrinsic::arm_neon_vqshiftnsu:
13360 VShiftOpc = ARMISD::VQSHRNsuIMM;
13361 break;
13362 case Intrinsic::arm_neon_vqrshiftns:
13363 VShiftOpc = ARMISD::VQRSHRNsIMM;
13364 break;
13365 case Intrinsic::arm_neon_vqrshiftnu:
13366 VShiftOpc = ARMISD::VQRSHRNuIMM;
13367 break;
13368 case Intrinsic::arm_neon_vqrshiftnsu:
13369 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13370 break;
13373 SDLoc dl(N);
13374 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13375 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13378 case Intrinsic::arm_neon_vshiftins: {
13379 EVT VT = N->getOperand(1).getValueType();
13380 int64_t Cnt;
13381 unsigned VShiftOpc = 0;
13383 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13384 VShiftOpc = ARMISD::VSLIIMM;
13385 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13386 VShiftOpc = ARMISD::VSRIIMM;
13387 else {
13388 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13391 SDLoc dl(N);
13392 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13393 N->getOperand(1), N->getOperand(2),
13394 DAG.getConstant(Cnt, dl, MVT::i32));
13397 case Intrinsic::arm_neon_vqrshifts:
13398 case Intrinsic::arm_neon_vqrshiftu:
13399 // No immediate versions of these to check for.
13400 break;
13403 return SDValue();
13406 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13407 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13408 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13409 /// vector element shift counts are generally not legal, and it is hard to see
13410 /// their values after they get legalized to loads from a constant pool.
13411 static SDValue PerformShiftCombine(SDNode *N,
13412 TargetLowering::DAGCombinerInfo &DCI,
13413 const ARMSubtarget *ST) {
13414 SelectionDAG &DAG = DCI.DAG;
13415 EVT VT = N->getValueType(0);
13416 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13417 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13418 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13419 SDValue N1 = N->getOperand(1);
13420 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13421 SDValue N0 = N->getOperand(0);
13422 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13423 DAG.MaskedValueIsZero(N0.getOperand(0),
13424 APInt::getHighBitsSet(32, 16)))
13425 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13429 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13430 N->getOperand(0)->getOpcode() == ISD::AND &&
13431 N->getOperand(0)->hasOneUse()) {
13432 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13433 return SDValue();
13434 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13435 // usually show up because instcombine prefers to canonicalize it to
13436 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13437 // out of GEP lowering in some cases.
13438 SDValue N0 = N->getOperand(0);
13439 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13440 if (!ShiftAmtNode)
13441 return SDValue();
13442 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13443 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13444 if (!AndMaskNode)
13445 return SDValue();
13446 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13447 // Don't transform uxtb/uxth.
13448 if (AndMask == 255 || AndMask == 65535)
13449 return SDValue();
13450 if (isMask_32(AndMask)) {
13451 uint32_t MaskedBits = countLeadingZeros(AndMask);
13452 if (MaskedBits > ShiftAmt) {
13453 SDLoc DL(N);
13454 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13455 DAG.getConstant(MaskedBits, DL, MVT::i32));
13456 return DAG.getNode(
13457 ISD::SRL, DL, MVT::i32, SHL,
13458 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13463 // Nothing to be done for scalar shifts.
13464 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13465 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13466 return SDValue();
13467 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13468 return SDValue();
13470 int64_t Cnt;
13472 switch (N->getOpcode()) {
13473 default: llvm_unreachable("unexpected shift opcode");
13475 case ISD::SHL:
13476 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13477 SDLoc dl(N);
13478 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13479 DAG.getConstant(Cnt, dl, MVT::i32));
13481 break;
13483 case ISD::SRA:
13484 case ISD::SRL:
13485 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13486 unsigned VShiftOpc =
13487 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13488 SDLoc dl(N);
13489 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13490 DAG.getConstant(Cnt, dl, MVT::i32));
13493 return SDValue();
13496 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13497 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13498 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13499 const ARMSubtarget *ST) {
13500 SDValue N0 = N->getOperand(0);
13502 // Check for sign- and zero-extensions of vector extract operations of 8-
13503 // and 16-bit vector elements. NEON supports these directly. They are
13504 // handled during DAG combining because type legalization will promote them
13505 // to 32-bit types and it is messy to recognize the operations after that.
13506 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13507 SDValue Vec = N0.getOperand(0);
13508 SDValue Lane = N0.getOperand(1);
13509 EVT VT = N->getValueType(0);
13510 EVT EltVT = N0.getValueType();
13511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13513 if (VT == MVT::i32 &&
13514 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13515 TLI.isTypeLegal(Vec.getValueType()) &&
13516 isa<ConstantSDNode>(Lane)) {
13518 unsigned Opc = 0;
13519 switch (N->getOpcode()) {
13520 default: llvm_unreachable("unexpected opcode");
13521 case ISD::SIGN_EXTEND:
13522 Opc = ARMISD::VGETLANEs;
13523 break;
13524 case ISD::ZERO_EXTEND:
13525 case ISD::ANY_EXTEND:
13526 Opc = ARMISD::VGETLANEu;
13527 break;
13529 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13533 return SDValue();
13536 static const APInt *isPowerOf2Constant(SDValue V) {
13537 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13538 if (!C)
13539 return nullptr;
13540 const APInt *CV = &C->getAPIntValue();
13541 return CV->isPowerOf2() ? CV : nullptr;
13544 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13545 // If we have a CMOV, OR and AND combination such as:
13546 // if (x & CN)
13547 // y |= CM;
13549 // And:
13550 // * CN is a single bit;
13551 // * All bits covered by CM are known zero in y
13553 // Then we can convert this into a sequence of BFI instructions. This will
13554 // always be a win if CM is a single bit, will always be no worse than the
13555 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13556 // three bits (due to the extra IT instruction).
13558 SDValue Op0 = CMOV->getOperand(0);
13559 SDValue Op1 = CMOV->getOperand(1);
13560 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13561 auto CC = CCNode->getAPIntValue().getLimitedValue();
13562 SDValue CmpZ = CMOV->getOperand(4);
13564 // The compare must be against zero.
13565 if (!isNullConstant(CmpZ->getOperand(1)))
13566 return SDValue();
13568 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13569 SDValue And = CmpZ->getOperand(0);
13570 if (And->getOpcode() != ISD::AND)
13571 return SDValue();
13572 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13573 if (!AndC)
13574 return SDValue();
13575 SDValue X = And->getOperand(0);
13577 if (CC == ARMCC::EQ) {
13578 // We're performing an "equal to zero" compare. Swap the operands so we
13579 // canonicalize on a "not equal to zero" compare.
13580 std::swap(Op0, Op1);
13581 } else {
13582 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13585 if (Op1->getOpcode() != ISD::OR)
13586 return SDValue();
13588 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13589 if (!OrC)
13590 return SDValue();
13591 SDValue Y = Op1->getOperand(0);
13593 if (Op0 != Y)
13594 return SDValue();
13596 // Now, is it profitable to continue?
13597 APInt OrCI = OrC->getAPIntValue();
13598 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13599 if (OrCI.countPopulation() > Heuristic)
13600 return SDValue();
13602 // Lastly, can we determine that the bits defined by OrCI
13603 // are zero in Y?
13604 KnownBits Known = DAG.computeKnownBits(Y);
13605 if ((OrCI & Known.Zero) != OrCI)
13606 return SDValue();
13608 // OK, we can do the combine.
13609 SDValue V = Y;
13610 SDLoc dl(X);
13611 EVT VT = X.getValueType();
13612 unsigned BitInX = AndC->logBase2();
13614 if (BitInX != 0) {
13615 // We must shift X first.
13616 X = DAG.getNode(ISD::SRL, dl, VT, X,
13617 DAG.getConstant(BitInX, dl, VT));
13620 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13621 BitInY < NumActiveBits; ++BitInY) {
13622 if (OrCI[BitInY] == 0)
13623 continue;
13624 APInt Mask(VT.getSizeInBits(), 0);
13625 Mask.setBit(BitInY);
13626 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13627 // Confusingly, the operand is an *inverted* mask.
13628 DAG.getConstant(~Mask, dl, VT));
13631 return V;
13634 // Given N, the value controlling the conditional branch, search for the loop
13635 // intrinsic, returning it, along with how the value is used. We need to handle
13636 // patterns such as the following:
13637 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13638 // (brcond (setcc (loop.decrement), 0, eq), exit)
13639 // (brcond (setcc (loop.decrement), 0, ne), header)
13640 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13641 bool &Negate) {
13642 switch (N->getOpcode()) {
13643 default:
13644 break;
13645 case ISD::XOR: {
13646 if (!isa<ConstantSDNode>(N.getOperand(1)))
13647 return SDValue();
13648 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13649 return SDValue();
13650 Negate = !Negate;
13651 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13653 case ISD::SETCC: {
13654 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13655 if (!Const)
13656 return SDValue();
13657 if (Const->isNullValue())
13658 Imm = 0;
13659 else if (Const->isOne())
13660 Imm = 1;
13661 else
13662 return SDValue();
13663 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13664 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13666 case ISD::INTRINSIC_W_CHAIN: {
13667 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13668 if (IntOp != Intrinsic::test_set_loop_iterations &&
13669 IntOp != Intrinsic::loop_decrement_reg)
13670 return SDValue();
13671 return N;
13674 return SDValue();
13677 static SDValue PerformHWLoopCombine(SDNode *N,
13678 TargetLowering::DAGCombinerInfo &DCI,
13679 const ARMSubtarget *ST) {
13681 // The hwloop intrinsics that we're interested are used for control-flow,
13682 // either for entering or exiting the loop:
13683 // - test.set.loop.iterations will test whether its operand is zero. If it
13684 // is zero, the proceeding branch should not enter the loop.
13685 // - loop.decrement.reg also tests whether its operand is zero. If it is
13686 // zero, the proceeding branch should not branch back to the beginning of
13687 // the loop.
13688 // So here, we need to check that how the brcond is using the result of each
13689 // of the intrinsics to ensure that we're branching to the right place at the
13690 // right time.
13692 ISD::CondCode CC;
13693 SDValue Cond;
13694 int Imm = 1;
13695 bool Negate = false;
13696 SDValue Chain = N->getOperand(0);
13697 SDValue Dest;
13699 if (N->getOpcode() == ISD::BRCOND) {
13700 CC = ISD::SETEQ;
13701 Cond = N->getOperand(1);
13702 Dest = N->getOperand(2);
13703 } else {
13704 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13705 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13706 Cond = N->getOperand(2);
13707 Dest = N->getOperand(4);
13708 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13709 if (!Const->isOne() && !Const->isNullValue())
13710 return SDValue();
13711 Imm = Const->getZExtValue();
13712 } else
13713 return SDValue();
13716 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13717 if (!Int)
13718 return SDValue();
13720 if (Negate)
13721 CC = ISD::getSetCCInverse(CC, true);
13723 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13724 return (CC == ISD::SETEQ && Imm == 0) ||
13725 (CC == ISD::SETNE && Imm == 1) ||
13726 (CC == ISD::SETLT && Imm == 1) ||
13727 (CC == ISD::SETULT && Imm == 1);
13730 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13731 return (CC == ISD::SETEQ && Imm == 1) ||
13732 (CC == ISD::SETNE && Imm == 0) ||
13733 (CC == ISD::SETGT && Imm == 0) ||
13734 (CC == ISD::SETUGT && Imm == 0) ||
13735 (CC == ISD::SETGE && Imm == 1) ||
13736 (CC == ISD::SETUGE && Imm == 1);
13739 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13740 "unsupported condition");
13742 SDLoc dl(Int);
13743 SelectionDAG &DAG = DCI.DAG;
13744 SDValue Elements = Int.getOperand(2);
13745 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13746 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13747 && "expected single br user");
13748 SDNode *Br = *N->use_begin();
13749 SDValue OtherTarget = Br->getOperand(1);
13751 // Update the unconditional branch to branch to the given Dest.
13752 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13753 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13754 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13755 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13758 if (IntOp == Intrinsic::test_set_loop_iterations) {
13759 SDValue Res;
13760 // We expect this 'instruction' to branch when the counter is zero.
13761 if (IsTrueIfZero(CC, Imm)) {
13762 SDValue Ops[] = { Chain, Elements, Dest };
13763 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13764 } else {
13765 // The logic is the reverse of what we need for WLS, so find the other
13766 // basic block target: the target of the proceeding br.
13767 UpdateUncondBr(Br, Dest, DAG);
13769 SDValue Ops[] = { Chain, Elements, OtherTarget };
13770 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13772 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13773 return Res;
13774 } else {
13775 SDValue Size = DAG.getTargetConstant(
13776 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13777 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13778 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13779 DAG.getVTList(MVT::i32, MVT::Other), Args);
13780 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13782 // We expect this instruction to branch when the count is not zero.
13783 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13785 // Update the unconditional branch to target the loop preheader if we've
13786 // found the condition has been reversed.
13787 if (Target == OtherTarget)
13788 UpdateUncondBr(Br, Dest, DAG);
13790 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13791 SDValue(LoopDec.getNode(), 1), Chain);
13793 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13794 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13796 return SDValue();
13799 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13800 SDValue
13801 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13802 SDValue Cmp = N->getOperand(4);
13803 if (Cmp.getOpcode() != ARMISD::CMPZ)
13804 // Only looking at NE cases.
13805 return SDValue();
13807 EVT VT = N->getValueType(0);
13808 SDLoc dl(N);
13809 SDValue LHS = Cmp.getOperand(0);
13810 SDValue RHS = Cmp.getOperand(1);
13811 SDValue Chain = N->getOperand(0);
13812 SDValue BB = N->getOperand(1);
13813 SDValue ARMcc = N->getOperand(2);
13814 ARMCC::CondCodes CC =
13815 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13817 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13818 // -> (brcond Chain BB CC CPSR Cmp)
13819 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13820 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13821 LHS->getOperand(0)->hasOneUse()) {
13822 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13823 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13824 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13825 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13826 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13827 (LHS01C && LHS01C->getZExtValue() == 1) &&
13828 (LHS1C && LHS1C->getZExtValue() == 1) &&
13829 (RHSC && RHSC->getZExtValue() == 0)) {
13830 return DAG.getNode(
13831 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13832 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13836 return SDValue();
13839 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13840 SDValue
13841 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13842 SDValue Cmp = N->getOperand(4);
13843 if (Cmp.getOpcode() != ARMISD::CMPZ)
13844 // Only looking at EQ and NE cases.
13845 return SDValue();
13847 EVT VT = N->getValueType(0);
13848 SDLoc dl(N);
13849 SDValue LHS = Cmp.getOperand(0);
13850 SDValue RHS = Cmp.getOperand(1);
13851 SDValue FalseVal = N->getOperand(0);
13852 SDValue TrueVal = N->getOperand(1);
13853 SDValue ARMcc = N->getOperand(2);
13854 ARMCC::CondCodes CC =
13855 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13857 // BFI is only available on V6T2+.
13858 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13859 SDValue R = PerformCMOVToBFICombine(N, DAG);
13860 if (R)
13861 return R;
13864 // Simplify
13865 // mov r1, r0
13866 // cmp r1, x
13867 // mov r0, y
13868 // moveq r0, x
13869 // to
13870 // cmp r0, x
13871 // movne r0, y
13873 // mov r1, r0
13874 // cmp r1, x
13875 // mov r0, x
13876 // movne r0, y
13877 // to
13878 // cmp r0, x
13879 // movne r0, y
13880 /// FIXME: Turn this into a target neutral optimization?
13881 SDValue Res;
13882 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13883 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13884 N->getOperand(3), Cmp);
13885 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13886 SDValue ARMcc;
13887 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13888 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13889 N->getOperand(3), NewCmp);
13892 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13893 // -> (cmov F T CC CPSR Cmp)
13894 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13895 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13896 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13897 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13898 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13899 (LHS1C && LHS1C->getZExtValue() == 1) &&
13900 (RHSC && RHSC->getZExtValue() == 0)) {
13901 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13902 LHS->getOperand(2), LHS->getOperand(3),
13903 LHS->getOperand(4));
13907 if (!VT.isInteger())
13908 return SDValue();
13910 // Materialize a boolean comparison for integers so we can avoid branching.
13911 if (isNullConstant(FalseVal)) {
13912 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13913 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13914 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13915 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13916 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13917 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13918 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13919 DAG.getConstant(5, dl, MVT::i32));
13920 } else {
13921 // CMOV 0, 1, ==, (CMPZ x, y) ->
13922 // (ADDCARRY (SUB x, y), t:0, t:1)
13923 // where t = (SUBCARRY 0, (SUB x, y), 0)
13925 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13926 // x != y. In other words, a carry C == 1 when x == y, C == 0
13927 // otherwise.
13928 // The final ADDCARRY computes
13929 // x - y + (0 - (x - y)) + C == C
13930 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13931 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13932 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13933 // ISD::SUBCARRY returns a borrow but we want the carry here
13934 // actually.
13935 SDValue Carry =
13936 DAG.getNode(ISD::SUB, dl, MVT::i32,
13937 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13938 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13940 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13941 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13942 // This seems pointless but will allow us to combine it further below.
13943 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13944 SDValue Sub =
13945 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13946 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13947 Sub.getValue(1), SDValue());
13948 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13949 N->getOperand(3), CPSRGlue.getValue(1));
13950 FalseVal = Sub;
13952 } else if (isNullConstant(TrueVal)) {
13953 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13954 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13955 // This seems pointless but will allow us to combine it further below
13956 // Note that we change == for != as this is the dual for the case above.
13957 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13958 SDValue Sub =
13959 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13960 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13961 Sub.getValue(1), SDValue());
13962 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13963 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13964 N->getOperand(3), CPSRGlue.getValue(1));
13965 FalseVal = Sub;
13969 // On Thumb1, the DAG above may be further combined if z is a power of 2
13970 // (z == 2 ^ K).
13971 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13972 // t1 = (USUBO (SUB x, y), 1)
13973 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13974 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13976 // This also handles the special case of comparing against zero; it's
13977 // essentially, the same pattern, except there's no SUBS:
13978 // CMOV x, z, !=, (CMPZ x, 0) ->
13979 // t1 = (USUBO x, 1)
13980 // t2 = (SUBCARRY x, t1:0, t1:1)
13981 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13982 const APInt *TrueConst;
13983 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13984 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13985 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13986 (FalseVal == LHS && isNullConstant(RHS))) &&
13987 (TrueConst = isPowerOf2Constant(TrueVal))) {
13988 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13989 unsigned ShiftAmount = TrueConst->logBase2();
13990 if (ShiftAmount)
13991 TrueVal = DAG.getConstant(1, dl, VT);
13992 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13993 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13995 if (ShiftAmount)
13996 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13997 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14000 if (Res.getNode()) {
14001 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14002 // Capture demanded bits information that would be otherwise lost.
14003 if (Known.Zero == 0xfffffffe)
14004 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14005 DAG.getValueType(MVT::i1));
14006 else if (Known.Zero == 0xffffff00)
14007 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14008 DAG.getValueType(MVT::i8));
14009 else if (Known.Zero == 0xffff0000)
14010 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14011 DAG.getValueType(MVT::i16));
14014 return Res;
14017 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14018 DAGCombinerInfo &DCI) const {
14019 switch (N->getOpcode()) {
14020 default: break;
14021 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14022 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14023 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14024 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14025 case ISD::SUB: return PerformSUBCombine(N, DCI);
14026 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14027 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14028 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14029 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14030 case ISD::BRCOND:
14031 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14032 case ARMISD::ADDC:
14033 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14034 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14035 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14036 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14037 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14038 case ISD::STORE: return PerformSTORECombine(N, DCI);
14039 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14040 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14041 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14042 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14043 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14044 case ISD::FP_TO_SINT:
14045 case ISD::FP_TO_UINT:
14046 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14047 case ISD::FDIV:
14048 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14049 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14050 case ISD::SHL:
14051 case ISD::SRA:
14052 case ISD::SRL:
14053 return PerformShiftCombine(N, DCI, Subtarget);
14054 case ISD::SIGN_EXTEND:
14055 case ISD::ZERO_EXTEND:
14056 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14057 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14058 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14059 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14060 case ARMISD::VLD1DUP:
14061 case ARMISD::VLD2DUP:
14062 case ARMISD::VLD3DUP:
14063 case ARMISD::VLD4DUP:
14064 return PerformVLDCombine(N, DCI);
14065 case ARMISD::BUILD_VECTOR:
14066 return PerformARMBUILD_VECTORCombine(N, DCI);
14067 case ARMISD::SMULWB: {
14068 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14069 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14070 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14071 return SDValue();
14072 break;
14074 case ARMISD::SMULWT: {
14075 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14076 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14077 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14078 return SDValue();
14079 break;
14081 case ARMISD::SMLALBB: {
14082 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14083 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14084 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14085 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14086 return SDValue();
14087 break;
14089 case ARMISD::SMLALBT: {
14090 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14091 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14092 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14093 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14094 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14095 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14096 return SDValue();
14097 break;
14099 case ARMISD::SMLALTB: {
14100 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14101 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14102 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14103 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14104 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14105 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14106 return SDValue();
14107 break;
14109 case ARMISD::SMLALTT: {
14110 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14111 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14112 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14113 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14114 return SDValue();
14115 break;
14117 case ISD::INTRINSIC_VOID:
14118 case ISD::INTRINSIC_W_CHAIN:
14119 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14120 case Intrinsic::arm_neon_vld1:
14121 case Intrinsic::arm_neon_vld1x2:
14122 case Intrinsic::arm_neon_vld1x3:
14123 case Intrinsic::arm_neon_vld1x4:
14124 case Intrinsic::arm_neon_vld2:
14125 case Intrinsic::arm_neon_vld3:
14126 case Intrinsic::arm_neon_vld4:
14127 case Intrinsic::arm_neon_vld2lane:
14128 case Intrinsic::arm_neon_vld3lane:
14129 case Intrinsic::arm_neon_vld4lane:
14130 case Intrinsic::arm_neon_vld2dup:
14131 case Intrinsic::arm_neon_vld3dup:
14132 case Intrinsic::arm_neon_vld4dup:
14133 case Intrinsic::arm_neon_vst1:
14134 case Intrinsic::arm_neon_vst1x2:
14135 case Intrinsic::arm_neon_vst1x3:
14136 case Intrinsic::arm_neon_vst1x4:
14137 case Intrinsic::arm_neon_vst2:
14138 case Intrinsic::arm_neon_vst3:
14139 case Intrinsic::arm_neon_vst4:
14140 case Intrinsic::arm_neon_vst2lane:
14141 case Intrinsic::arm_neon_vst3lane:
14142 case Intrinsic::arm_neon_vst4lane:
14143 return PerformVLDCombine(N, DCI);
14144 default: break;
14146 break;
14148 return SDValue();
14151 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14152 EVT VT) const {
14153 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14156 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14157 unsigned Alignment,
14158 MachineMemOperand::Flags,
14159 bool *Fast) const {
14160 // Depends what it gets converted into if the type is weird.
14161 if (!VT.isSimple())
14162 return false;
14164 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14165 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14166 auto Ty = VT.getSimpleVT().SimpleTy;
14168 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14169 // Unaligned access can use (for example) LRDB, LRDH, LDR
14170 if (AllowsUnaligned) {
14171 if (Fast)
14172 *Fast = Subtarget->hasV7Ops();
14173 return true;
14177 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14178 // For any little-endian targets with neon, we can support unaligned ld/st
14179 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14180 // A big-endian target may also explicitly support unaligned accesses
14181 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14182 if (Fast)
14183 *Fast = true;
14184 return true;
14188 if (!Subtarget->hasMVEIntegerOps())
14189 return false;
14191 // These are for predicates
14192 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14193 if (Fast)
14194 *Fast = true;
14195 return true;
14198 // These are for truncated stores/narrowing loads. They are fine so long as
14199 // the alignment is at least the size of the item being loaded
14200 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14201 Alignment >= VT.getScalarSizeInBits() / 8) {
14202 if (Fast)
14203 *Fast = true;
14204 return true;
14207 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14208 // VSTRW.U32 all store the vector register in exactly the same format, and
14209 // differ only in the range of their immediate offset field and the required
14210 // alignment. So there is always a store that can be used, regardless of
14211 // actual type.
14213 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14214 // VREV64.8) pair and get the same effect. This will likely be better than
14215 // aligning the vector through the stack.
14216 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14217 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14218 Ty == MVT::v2f64) {
14219 if (Fast)
14220 *Fast = true;
14221 return true;
14224 return false;
14227 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14228 unsigned AlignCheck) {
14229 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14230 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14233 EVT ARMTargetLowering::getOptimalMemOpType(
14234 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14235 bool ZeroMemset, bool MemcpyStrSrc,
14236 const AttributeList &FuncAttributes) const {
14237 // See if we can use NEON instructions for this...
14238 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14239 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14240 bool Fast;
14241 if (Size >= 16 &&
14242 (memOpAlign(SrcAlign, DstAlign, 16) ||
14243 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14244 MachineMemOperand::MONone, &Fast) &&
14245 Fast))) {
14246 return MVT::v2f64;
14247 } else if (Size >= 8 &&
14248 (memOpAlign(SrcAlign, DstAlign, 8) ||
14249 (allowsMisalignedMemoryAccesses(
14250 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14251 Fast))) {
14252 return MVT::f64;
14256 // Let the target-independent logic figure it out.
14257 return MVT::Other;
14260 // 64-bit integers are split into their high and low parts and held in two
14261 // different registers, so the trunc is free since the low register can just
14262 // be used.
14263 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14264 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14265 return false;
14266 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14267 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14268 return (SrcBits == 64 && DestBits == 32);
14271 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14272 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14273 !DstVT.isInteger())
14274 return false;
14275 unsigned SrcBits = SrcVT.getSizeInBits();
14276 unsigned DestBits = DstVT.getSizeInBits();
14277 return (SrcBits == 64 && DestBits == 32);
14280 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14281 if (Val.getOpcode() != ISD::LOAD)
14282 return false;
14284 EVT VT1 = Val.getValueType();
14285 if (!VT1.isSimple() || !VT1.isInteger() ||
14286 !VT2.isSimple() || !VT2.isInteger())
14287 return false;
14289 switch (VT1.getSimpleVT().SimpleTy) {
14290 default: break;
14291 case MVT::i1:
14292 case MVT::i8:
14293 case MVT::i16:
14294 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14295 return true;
14298 return false;
14301 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14302 if (!VT.isSimple())
14303 return false;
14305 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14306 // negate values directly (fneg is free). So, we don't want to let the DAG
14307 // combiner rewrite fneg into xors and some other instructions. For f16 and
14308 // FullFP16 argument passing, some bitcast nodes may be introduced,
14309 // triggering this DAG combine rewrite, so we are avoiding that with this.
14310 switch (VT.getSimpleVT().SimpleTy) {
14311 default: break;
14312 case MVT::f16:
14313 return Subtarget->hasFullFP16();
14316 return false;
14319 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14320 /// of the vector elements.
14321 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14322 auto areExtDoubled = [](Instruction *Ext) {
14323 return Ext->getType()->getScalarSizeInBits() ==
14324 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14327 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14328 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14329 !areExtDoubled(cast<Instruction>(Ext1)) ||
14330 !areExtDoubled(cast<Instruction>(Ext2)))
14331 return false;
14333 return true;
14336 /// Check if sinking \p I's operands to I's basic block is profitable, because
14337 /// the operands can be folded into a target instruction, e.g.
14338 /// sext/zext can be folded into vsubl.
14339 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14340 SmallVectorImpl<Use *> &Ops) const {
14341 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14342 return false;
14344 switch (I->getOpcode()) {
14345 case Instruction::Sub:
14346 case Instruction::Add: {
14347 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14348 return false;
14349 Ops.push_back(&I->getOperandUse(0));
14350 Ops.push_back(&I->getOperandUse(1));
14351 return true;
14353 default:
14354 return false;
14356 return false;
14359 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14360 EVT VT = ExtVal.getValueType();
14362 if (!isTypeLegal(VT))
14363 return false;
14365 // Don't create a loadext if we can fold the extension into a wide/long
14366 // instruction.
14367 // If there's more than one user instruction, the loadext is desirable no
14368 // matter what. There can be two uses by the same instruction.
14369 if (ExtVal->use_empty() ||
14370 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14371 return true;
14373 SDNode *U = *ExtVal->use_begin();
14374 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14375 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14376 return false;
14378 return true;
14381 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14382 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14383 return false;
14385 if (!isTypeLegal(EVT::getEVT(Ty1)))
14386 return false;
14388 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14390 // Assuming the caller doesn't have a zeroext or signext return parameter,
14391 // truncation all the way down to i1 is valid.
14392 return true;
14395 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14396 const AddrMode &AM, Type *Ty,
14397 unsigned AS) const {
14398 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14399 if (Subtarget->hasFPAO())
14400 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14401 return 0;
14403 return -1;
14406 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14407 if (V < 0)
14408 return false;
14410 unsigned Scale = 1;
14411 switch (VT.getSimpleVT().SimpleTy) {
14412 case MVT::i1:
14413 case MVT::i8:
14414 // Scale == 1;
14415 break;
14416 case MVT::i16:
14417 // Scale == 2;
14418 Scale = 2;
14419 break;
14420 default:
14421 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14422 // Scale == 4;
14423 Scale = 4;
14424 break;
14427 if ((V & (Scale - 1)) != 0)
14428 return false;
14429 return isUInt<5>(V / Scale);
14432 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14433 const ARMSubtarget *Subtarget) {
14434 if (!VT.isInteger() && !VT.isFloatingPoint())
14435 return false;
14436 if (VT.isVector() && Subtarget->hasNEON())
14437 return false;
14438 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14439 !Subtarget->hasMVEFloatOps())
14440 return false;
14442 bool IsNeg = false;
14443 if (V < 0) {
14444 IsNeg = true;
14445 V = -V;
14448 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14450 // MVE: size * imm7
14451 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14452 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14453 case MVT::i32:
14454 case MVT::f32:
14455 return isShiftedUInt<7,2>(V);
14456 case MVT::i16:
14457 case MVT::f16:
14458 return isShiftedUInt<7,1>(V);
14459 case MVT::i8:
14460 return isUInt<7>(V);
14461 default:
14462 return false;
14466 // half VLDR: 2 * imm8
14467 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14468 return isShiftedUInt<8, 1>(V);
14469 // VLDR and LDRD: 4 * imm8
14470 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14471 return isShiftedUInt<8, 2>(V);
14473 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14474 // + imm12 or - imm8
14475 if (IsNeg)
14476 return isUInt<8>(V);
14477 return isUInt<12>(V);
14480 return false;
14483 /// isLegalAddressImmediate - Return true if the integer value can be used
14484 /// as the offset of the target addressing mode for load / store of the
14485 /// given type.
14486 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14487 const ARMSubtarget *Subtarget) {
14488 if (V == 0)
14489 return true;
14491 if (!VT.isSimple())
14492 return false;
14494 if (Subtarget->isThumb1Only())
14495 return isLegalT1AddressImmediate(V, VT);
14496 else if (Subtarget->isThumb2())
14497 return isLegalT2AddressImmediate(V, VT, Subtarget);
14499 // ARM mode.
14500 if (V < 0)
14501 V = - V;
14502 switch (VT.getSimpleVT().SimpleTy) {
14503 default: return false;
14504 case MVT::i1:
14505 case MVT::i8:
14506 case MVT::i32:
14507 // +- imm12
14508 return isUInt<12>(V);
14509 case MVT::i16:
14510 // +- imm8
14511 return isUInt<8>(V);
14512 case MVT::f32:
14513 case MVT::f64:
14514 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14515 return false;
14516 return isShiftedUInt<8, 2>(V);
14520 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14521 EVT VT) const {
14522 int Scale = AM.Scale;
14523 if (Scale < 0)
14524 return false;
14526 switch (VT.getSimpleVT().SimpleTy) {
14527 default: return false;
14528 case MVT::i1:
14529 case MVT::i8:
14530 case MVT::i16:
14531 case MVT::i32:
14532 if (Scale == 1)
14533 return true;
14534 // r + r << imm
14535 Scale = Scale & ~1;
14536 return Scale == 2 || Scale == 4 || Scale == 8;
14537 case MVT::i64:
14538 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14539 // version in Thumb mode.
14540 // r + r
14541 if (Scale == 1)
14542 return true;
14543 // r * 2 (this can be lowered to r + r).
14544 if (!AM.HasBaseReg && Scale == 2)
14545 return true;
14546 return false;
14547 case MVT::isVoid:
14548 // Note, we allow "void" uses (basically, uses that aren't loads or
14549 // stores), because arm allows folding a scale into many arithmetic
14550 // operations. This should be made more precise and revisited later.
14552 // Allow r << imm, but the imm has to be a multiple of two.
14553 if (Scale & 1) return false;
14554 return isPowerOf2_32(Scale);
14558 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14559 EVT VT) const {
14560 const int Scale = AM.Scale;
14562 // Negative scales are not supported in Thumb1.
14563 if (Scale < 0)
14564 return false;
14566 // Thumb1 addressing modes do not support register scaling excepting the
14567 // following cases:
14568 // 1. Scale == 1 means no scaling.
14569 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14570 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14573 /// isLegalAddressingMode - Return true if the addressing mode represented
14574 /// by AM is legal for this target, for a load/store of the specified type.
14575 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14576 const AddrMode &AM, Type *Ty,
14577 unsigned AS, Instruction *I) const {
14578 EVT VT = getValueType(DL, Ty, true);
14579 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14580 return false;
14582 // Can never fold addr of global into load/store.
14583 if (AM.BaseGV)
14584 return false;
14586 switch (AM.Scale) {
14587 case 0: // no scale reg, must be "r+i" or "r", or "i".
14588 break;
14589 default:
14590 // ARM doesn't support any R+R*scale+imm addr modes.
14591 if (AM.BaseOffs)
14592 return false;
14594 if (!VT.isSimple())
14595 return false;
14597 if (Subtarget->isThumb1Only())
14598 return isLegalT1ScaledAddressingMode(AM, VT);
14600 if (Subtarget->isThumb2())
14601 return isLegalT2ScaledAddressingMode(AM, VT);
14603 int Scale = AM.Scale;
14604 switch (VT.getSimpleVT().SimpleTy) {
14605 default: return false;
14606 case MVT::i1:
14607 case MVT::i8:
14608 case MVT::i32:
14609 if (Scale < 0) Scale = -Scale;
14610 if (Scale == 1)
14611 return true;
14612 // r + r << imm
14613 return isPowerOf2_32(Scale & ~1);
14614 case MVT::i16:
14615 case MVT::i64:
14616 // r +/- r
14617 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14618 return true;
14619 // r * 2 (this can be lowered to r + r).
14620 if (!AM.HasBaseReg && Scale == 2)
14621 return true;
14622 return false;
14624 case MVT::isVoid:
14625 // Note, we allow "void" uses (basically, uses that aren't loads or
14626 // stores), because arm allows folding a scale into many arithmetic
14627 // operations. This should be made more precise and revisited later.
14629 // Allow r << imm, but the imm has to be a multiple of two.
14630 if (Scale & 1) return false;
14631 return isPowerOf2_32(Scale);
14634 return true;
14637 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14638 /// icmp immediate, that is the target has icmp instructions which can compare
14639 /// a register against the immediate without having to materialize the
14640 /// immediate into a register.
14641 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14642 // Thumb2 and ARM modes can use cmn for negative immediates.
14643 if (!Subtarget->isThumb())
14644 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14645 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14646 if (Subtarget->isThumb2())
14647 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14648 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14649 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14650 return Imm >= 0 && Imm <= 255;
14653 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14654 /// *or sub* immediate, that is the target has add or sub instructions which can
14655 /// add a register with the immediate without having to materialize the
14656 /// immediate into a register.
14657 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14658 // Same encoding for add/sub, just flip the sign.
14659 int64_t AbsImm = std::abs(Imm);
14660 if (!Subtarget->isThumb())
14661 return ARM_AM::getSOImmVal(AbsImm) != -1;
14662 if (Subtarget->isThumb2())
14663 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14664 // Thumb1 only has 8-bit unsigned immediate.
14665 return AbsImm >= 0 && AbsImm <= 255;
14668 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14669 bool isSEXTLoad, SDValue &Base,
14670 SDValue &Offset, bool &isInc,
14671 SelectionDAG &DAG) {
14672 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14673 return false;
14675 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14676 // AddressingMode 3
14677 Base = Ptr->getOperand(0);
14678 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14679 int RHSC = (int)RHS->getZExtValue();
14680 if (RHSC < 0 && RHSC > -256) {
14681 assert(Ptr->getOpcode() == ISD::ADD);
14682 isInc = false;
14683 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14684 return true;
14687 isInc = (Ptr->getOpcode() == ISD::ADD);
14688 Offset = Ptr->getOperand(1);
14689 return true;
14690 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14691 // AddressingMode 2
14692 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14693 int RHSC = (int)RHS->getZExtValue();
14694 if (RHSC < 0 && RHSC > -0x1000) {
14695 assert(Ptr->getOpcode() == ISD::ADD);
14696 isInc = false;
14697 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14698 Base = Ptr->getOperand(0);
14699 return true;
14703 if (Ptr->getOpcode() == ISD::ADD) {
14704 isInc = true;
14705 ARM_AM::ShiftOpc ShOpcVal=
14706 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14707 if (ShOpcVal != ARM_AM::no_shift) {
14708 Base = Ptr->getOperand(1);
14709 Offset = Ptr->getOperand(0);
14710 } else {
14711 Base = Ptr->getOperand(0);
14712 Offset = Ptr->getOperand(1);
14714 return true;
14717 isInc = (Ptr->getOpcode() == ISD::ADD);
14718 Base = Ptr->getOperand(0);
14719 Offset = Ptr->getOperand(1);
14720 return true;
14723 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14724 return false;
14727 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14728 bool isSEXTLoad, SDValue &Base,
14729 SDValue &Offset, bool &isInc,
14730 SelectionDAG &DAG) {
14731 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14732 return false;
14734 Base = Ptr->getOperand(0);
14735 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14736 int RHSC = (int)RHS->getZExtValue();
14737 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14738 assert(Ptr->getOpcode() == ISD::ADD);
14739 isInc = false;
14740 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14741 return true;
14742 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14743 isInc = Ptr->getOpcode() == ISD::ADD;
14744 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14745 return true;
14749 return false;
14752 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
14753 bool isSEXTLoad, bool isLE, SDValue &Base,
14754 SDValue &Offset, bool &isInc,
14755 SelectionDAG &DAG) {
14756 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14757 return false;
14758 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
14759 return false;
14761 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
14762 int RHSC = (int)RHS->getZExtValue();
14764 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
14765 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
14766 assert(Ptr->getOpcode() == ISD::ADD);
14767 isInc = false;
14768 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14769 return true;
14770 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
14771 isInc = Ptr->getOpcode() == ISD::ADD;
14772 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14773 return true;
14775 return false;
14778 // Try to find a matching instruction based on s/zext, Alignment, Offset and
14779 // (in BE) type.
14780 Base = Ptr->getOperand(0);
14781 if (VT == MVT::v4i16) {
14782 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
14783 return true;
14784 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
14785 if (IsInRange(RHSC, 0x80, 1))
14786 return true;
14787 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
14788 IsInRange(RHSC, 0x80, 4))
14789 return true;
14790 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
14791 IsInRange(RHSC, 0x80, 2))
14792 return true;
14793 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
14794 return true;
14795 return false;
14798 /// getPreIndexedAddressParts - returns true by value, base pointer and
14799 /// offset pointer and addressing mode by reference if the node's address
14800 /// can be legally represented as pre-indexed load / store address.
14801 bool
14802 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14803 SDValue &Offset,
14804 ISD::MemIndexedMode &AM,
14805 SelectionDAG &DAG) const {
14806 if (Subtarget->isThumb1Only())
14807 return false;
14809 EVT VT;
14810 SDValue Ptr;
14811 unsigned Align;
14812 bool isSEXTLoad = false;
14813 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14814 Ptr = LD->getBasePtr();
14815 VT = LD->getMemoryVT();
14816 Align = LD->getAlignment();
14817 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14818 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14819 Ptr = ST->getBasePtr();
14820 VT = ST->getMemoryVT();
14821 Align = ST->getAlignment();
14822 } else
14823 return false;
14825 bool isInc;
14826 bool isLegal = false;
14827 if (VT.isVector())
14828 isLegal = Subtarget->hasMVEIntegerOps() &&
14829 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
14830 Subtarget->isLittle(), Base, Offset,
14831 isInc, DAG);
14832 else {
14833 if (Subtarget->isThumb2())
14834 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14835 Offset, isInc, DAG);
14836 else
14837 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14838 Offset, isInc, DAG);
14840 if (!isLegal)
14841 return false;
14843 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14844 return true;
14847 /// getPostIndexedAddressParts - returns true by value, base pointer and
14848 /// offset pointer and addressing mode by reference if this node can be
14849 /// combined with a load / store to form a post-indexed load / store.
14850 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14851 SDValue &Base,
14852 SDValue &Offset,
14853 ISD::MemIndexedMode &AM,
14854 SelectionDAG &DAG) const {
14855 EVT VT;
14856 SDValue Ptr;
14857 unsigned Align;
14858 bool isSEXTLoad = false, isNonExt;
14859 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14860 VT = LD->getMemoryVT();
14861 Ptr = LD->getBasePtr();
14862 Align = LD->getAlignment();
14863 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14864 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14865 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14866 VT = ST->getMemoryVT();
14867 Ptr = ST->getBasePtr();
14868 Align = ST->getAlignment();
14869 isNonExt = !ST->isTruncatingStore();
14870 } else
14871 return false;
14873 if (Subtarget->isThumb1Only()) {
14874 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14875 // must be non-extending/truncating, i32, with an offset of 4.
14876 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14877 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14878 return false;
14879 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14880 if (!RHS || RHS->getZExtValue() != 4)
14881 return false;
14883 Offset = Op->getOperand(1);
14884 Base = Op->getOperand(0);
14885 AM = ISD::POST_INC;
14886 return true;
14889 bool isInc;
14890 bool isLegal = false;
14891 if (VT.isVector())
14892 isLegal = Subtarget->hasMVEIntegerOps() &&
14893 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
14894 Subtarget->isLittle(), Base, Offset,
14895 isInc, DAG);
14896 else {
14897 if (Subtarget->isThumb2())
14898 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14899 isInc, DAG);
14900 else
14901 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14902 isInc, DAG);
14904 if (!isLegal)
14905 return false;
14907 if (Ptr != Base) {
14908 // Swap base ptr and offset to catch more post-index load / store when
14909 // it's legal. In Thumb2 mode, offset must be an immediate.
14910 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14911 !Subtarget->isThumb2())
14912 std::swap(Base, Offset);
14914 // Post-indexed load / store update the base pointer.
14915 if (Ptr != Base)
14916 return false;
14919 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14920 return true;
14923 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14924 KnownBits &Known,
14925 const APInt &DemandedElts,
14926 const SelectionDAG &DAG,
14927 unsigned Depth) const {
14928 unsigned BitWidth = Known.getBitWidth();
14929 Known.resetAll();
14930 switch (Op.getOpcode()) {
14931 default: break;
14932 case ARMISD::ADDC:
14933 case ARMISD::ADDE:
14934 case ARMISD::SUBC:
14935 case ARMISD::SUBE:
14936 // Special cases when we convert a carry to a boolean.
14937 if (Op.getResNo() == 0) {
14938 SDValue LHS = Op.getOperand(0);
14939 SDValue RHS = Op.getOperand(1);
14940 // (ADDE 0, 0, C) will give us a single bit.
14941 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14942 isNullConstant(RHS)) {
14943 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14944 return;
14947 break;
14948 case ARMISD::CMOV: {
14949 // Bits are known zero/one if known on the LHS and RHS.
14950 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14951 if (Known.isUnknown())
14952 return;
14954 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14955 Known.Zero &= KnownRHS.Zero;
14956 Known.One &= KnownRHS.One;
14957 return;
14959 case ISD::INTRINSIC_W_CHAIN: {
14960 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14961 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14962 switch (IntID) {
14963 default: return;
14964 case Intrinsic::arm_ldaex:
14965 case Intrinsic::arm_ldrex: {
14966 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14967 unsigned MemBits = VT.getScalarSizeInBits();
14968 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14969 return;
14973 case ARMISD::BFI: {
14974 // Conservatively, we can recurse down the first operand
14975 // and just mask out all affected bits.
14976 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14978 // The operand to BFI is already a mask suitable for removing the bits it
14979 // sets.
14980 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14981 const APInt &Mask = CI->getAPIntValue();
14982 Known.Zero &= Mask;
14983 Known.One &= Mask;
14984 return;
14986 case ARMISD::VGETLANEs:
14987 case ARMISD::VGETLANEu: {
14988 const SDValue &SrcSV = Op.getOperand(0);
14989 EVT VecVT = SrcSV.getValueType();
14990 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14991 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14992 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14993 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14994 "VGETLANE index out of bounds");
14995 unsigned Idx = Pos->getZExtValue();
14996 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14997 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
14999 EVT VT = Op.getValueType();
15000 const unsigned DstSz = VT.getScalarSizeInBits();
15001 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15002 (void)SrcSz;
15003 assert(SrcSz == Known.getBitWidth());
15004 assert(DstSz > SrcSz);
15005 if (Op.getOpcode() == ARMISD::VGETLANEs)
15006 Known = Known.sext(DstSz);
15007 else {
15008 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15010 assert(DstSz == Known.getBitWidth());
15011 break;
15016 bool
15017 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15018 const APInt &DemandedAPInt,
15019 TargetLoweringOpt &TLO) const {
15020 // Delay optimization, so we don't have to deal with illegal types, or block
15021 // optimizations.
15022 if (!TLO.LegalOps)
15023 return false;
15025 // Only optimize AND for now.
15026 if (Op.getOpcode() != ISD::AND)
15027 return false;
15029 EVT VT = Op.getValueType();
15031 // Ignore vectors.
15032 if (VT.isVector())
15033 return false;
15035 assert(VT == MVT::i32 && "Unexpected integer type");
15037 // Make sure the RHS really is a constant.
15038 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15039 if (!C)
15040 return false;
15042 unsigned Mask = C->getZExtValue();
15044 unsigned Demanded = DemandedAPInt.getZExtValue();
15045 unsigned ShrunkMask = Mask & Demanded;
15046 unsigned ExpandedMask = Mask | ~Demanded;
15048 // If the mask is all zeros, let the target-independent code replace the
15049 // result with zero.
15050 if (ShrunkMask == 0)
15051 return false;
15053 // If the mask is all ones, erase the AND. (Currently, the target-independent
15054 // code won't do this, so we have to do it explicitly to avoid an infinite
15055 // loop in obscure cases.)
15056 if (ExpandedMask == ~0U)
15057 return TLO.CombineTo(Op, Op.getOperand(0));
15059 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15060 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15062 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15063 if (NewMask == Mask)
15064 return true;
15065 SDLoc DL(Op);
15066 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15067 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15068 return TLO.CombineTo(Op, NewOp);
15071 // Prefer uxtb mask.
15072 if (IsLegalMask(0xFF))
15073 return UseMask(0xFF);
15075 // Prefer uxth mask.
15076 if (IsLegalMask(0xFFFF))
15077 return UseMask(0xFFFF);
15079 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15080 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15081 if (ShrunkMask < 256)
15082 return UseMask(ShrunkMask);
15084 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15085 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15086 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15087 return UseMask(ExpandedMask);
15089 // Potential improvements:
15091 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15092 // We could try to prefer Thumb1 immediates which can be lowered to a
15093 // two-instruction sequence.
15094 // We could try to recognize more legal ARM/Thumb2 immediates here.
15096 return false;
15100 //===----------------------------------------------------------------------===//
15101 // ARM Inline Assembly Support
15102 //===----------------------------------------------------------------------===//
15104 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15105 // Looking for "rev" which is V6+.
15106 if (!Subtarget->hasV6Ops())
15107 return false;
15109 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15110 std::string AsmStr = IA->getAsmString();
15111 SmallVector<StringRef, 4> AsmPieces;
15112 SplitString(AsmStr, AsmPieces, ";\n");
15114 switch (AsmPieces.size()) {
15115 default: return false;
15116 case 1:
15117 AsmStr = AsmPieces[0];
15118 AsmPieces.clear();
15119 SplitString(AsmStr, AsmPieces, " \t,");
15121 // rev $0, $1
15122 if (AsmPieces.size() == 3 &&
15123 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15124 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15125 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15126 if (Ty && Ty->getBitWidth() == 32)
15127 return IntrinsicLowering::LowerToByteSwap(CI);
15129 break;
15132 return false;
15135 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15136 // At this point, we have to lower this constraint to something else, so we
15137 // lower it to an "r" or "w". However, by doing this we will force the result
15138 // to be in register, while the X constraint is much more permissive.
15140 // Although we are correct (we are free to emit anything, without
15141 // constraints), we might break use cases that would expect us to be more
15142 // efficient and emit something else.
15143 if (!Subtarget->hasVFP2Base())
15144 return "r";
15145 if (ConstraintVT.isFloatingPoint())
15146 return "w";
15147 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15148 (ConstraintVT.getSizeInBits() == 64 ||
15149 ConstraintVT.getSizeInBits() == 128))
15150 return "w";
15152 return "r";
15155 /// getConstraintType - Given a constraint letter, return the type of
15156 /// constraint it is for this target.
15157 ARMTargetLowering::ConstraintType
15158 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15159 unsigned S = Constraint.size();
15160 if (S == 1) {
15161 switch (Constraint[0]) {
15162 default: break;
15163 case 'l': return C_RegisterClass;
15164 case 'w': return C_RegisterClass;
15165 case 'h': return C_RegisterClass;
15166 case 'x': return C_RegisterClass;
15167 case 't': return C_RegisterClass;
15168 case 'j': return C_Immediate; // Constant for movw.
15169 // An address with a single base register. Due to the way we
15170 // currently handle addresses it is the same as an 'r' memory constraint.
15171 case 'Q': return C_Memory;
15173 } else if (S == 2) {
15174 switch (Constraint[0]) {
15175 default: break;
15176 case 'T': return C_RegisterClass;
15177 // All 'U+' constraints are addresses.
15178 case 'U': return C_Memory;
15181 return TargetLowering::getConstraintType(Constraint);
15184 /// Examine constraint type and operand type and determine a weight value.
15185 /// This object must already have been set up with the operand type
15186 /// and the current alternative constraint selected.
15187 TargetLowering::ConstraintWeight
15188 ARMTargetLowering::getSingleConstraintMatchWeight(
15189 AsmOperandInfo &info, const char *constraint) const {
15190 ConstraintWeight weight = CW_Invalid;
15191 Value *CallOperandVal = info.CallOperandVal;
15192 // If we don't have a value, we can't do a match,
15193 // but allow it at the lowest weight.
15194 if (!CallOperandVal)
15195 return CW_Default;
15196 Type *type = CallOperandVal->getType();
15197 // Look at the constraint type.
15198 switch (*constraint) {
15199 default:
15200 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15201 break;
15202 case 'l':
15203 if (type->isIntegerTy()) {
15204 if (Subtarget->isThumb())
15205 weight = CW_SpecificReg;
15206 else
15207 weight = CW_Register;
15209 break;
15210 case 'w':
15211 if (type->isFloatingPointTy())
15212 weight = CW_Register;
15213 break;
15215 return weight;
15218 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15220 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15221 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15222 switch (Constraint.size()) {
15223 case 1:
15224 // GCC ARM Constraint Letters
15225 switch (Constraint[0]) {
15226 case 'l': // Low regs or general regs.
15227 if (Subtarget->isThumb())
15228 return RCPair(0U, &ARM::tGPRRegClass);
15229 return RCPair(0U, &ARM::GPRRegClass);
15230 case 'h': // High regs or no regs.
15231 if (Subtarget->isThumb())
15232 return RCPair(0U, &ARM::hGPRRegClass);
15233 break;
15234 case 'r':
15235 if (Subtarget->isThumb1Only())
15236 return RCPair(0U, &ARM::tGPRRegClass);
15237 return RCPair(0U, &ARM::GPRRegClass);
15238 case 'w':
15239 if (VT == MVT::Other)
15240 break;
15241 if (VT == MVT::f32)
15242 return RCPair(0U, &ARM::SPRRegClass);
15243 if (VT.getSizeInBits() == 64)
15244 return RCPair(0U, &ARM::DPRRegClass);
15245 if (VT.getSizeInBits() == 128)
15246 return RCPair(0U, &ARM::QPRRegClass);
15247 break;
15248 case 'x':
15249 if (VT == MVT::Other)
15250 break;
15251 if (VT == MVT::f32)
15252 return RCPair(0U, &ARM::SPR_8RegClass);
15253 if (VT.getSizeInBits() == 64)
15254 return RCPair(0U, &ARM::DPR_8RegClass);
15255 if (VT.getSizeInBits() == 128)
15256 return RCPair(0U, &ARM::QPR_8RegClass);
15257 break;
15258 case 't':
15259 if (VT == MVT::Other)
15260 break;
15261 if (VT == MVT::f32 || VT == MVT::i32)
15262 return RCPair(0U, &ARM::SPRRegClass);
15263 if (VT.getSizeInBits() == 64)
15264 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15265 if (VT.getSizeInBits() == 128)
15266 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15267 break;
15269 break;
15271 case 2:
15272 if (Constraint[0] == 'T') {
15273 switch (Constraint[1]) {
15274 default:
15275 break;
15276 case 'e':
15277 return RCPair(0U, &ARM::tGPREvenRegClass);
15278 case 'o':
15279 return RCPair(0U, &ARM::tGPROddRegClass);
15282 break;
15284 default:
15285 break;
15288 if (StringRef("{cc}").equals_lower(Constraint))
15289 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15291 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15294 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15295 /// vector. If it is invalid, don't add anything to Ops.
15296 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15297 std::string &Constraint,
15298 std::vector<SDValue>&Ops,
15299 SelectionDAG &DAG) const {
15300 SDValue Result;
15302 // Currently only support length 1 constraints.
15303 if (Constraint.length() != 1) return;
15305 char ConstraintLetter = Constraint[0];
15306 switch (ConstraintLetter) {
15307 default: break;
15308 case 'j':
15309 case 'I': case 'J': case 'K': case 'L':
15310 case 'M': case 'N': case 'O':
15311 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15312 if (!C)
15313 return;
15315 int64_t CVal64 = C->getSExtValue();
15316 int CVal = (int) CVal64;
15317 // None of these constraints allow values larger than 32 bits. Check
15318 // that the value fits in an int.
15319 if (CVal != CVal64)
15320 return;
15322 switch (ConstraintLetter) {
15323 case 'j':
15324 // Constant suitable for movw, must be between 0 and
15325 // 65535.
15326 if (Subtarget->hasV6T2Ops())
15327 if (CVal >= 0 && CVal <= 65535)
15328 break;
15329 return;
15330 case 'I':
15331 if (Subtarget->isThumb1Only()) {
15332 // This must be a constant between 0 and 255, for ADD
15333 // immediates.
15334 if (CVal >= 0 && CVal <= 255)
15335 break;
15336 } else if (Subtarget->isThumb2()) {
15337 // A constant that can be used as an immediate value in a
15338 // data-processing instruction.
15339 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15340 break;
15341 } else {
15342 // A constant that can be used as an immediate value in a
15343 // data-processing instruction.
15344 if (ARM_AM::getSOImmVal(CVal) != -1)
15345 break;
15347 return;
15349 case 'J':
15350 if (Subtarget->isThumb1Only()) {
15351 // This must be a constant between -255 and -1, for negated ADD
15352 // immediates. This can be used in GCC with an "n" modifier that
15353 // prints the negated value, for use with SUB instructions. It is
15354 // not useful otherwise but is implemented for compatibility.
15355 if (CVal >= -255 && CVal <= -1)
15356 break;
15357 } else {
15358 // This must be a constant between -4095 and 4095. It is not clear
15359 // what this constraint is intended for. Implemented for
15360 // compatibility with GCC.
15361 if (CVal >= -4095 && CVal <= 4095)
15362 break;
15364 return;
15366 case 'K':
15367 if (Subtarget->isThumb1Only()) {
15368 // A 32-bit value where only one byte has a nonzero value. Exclude
15369 // zero to match GCC. This constraint is used by GCC internally for
15370 // constants that can be loaded with a move/shift combination.
15371 // It is not useful otherwise but is implemented for compatibility.
15372 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15373 break;
15374 } else if (Subtarget->isThumb2()) {
15375 // A constant whose bitwise inverse can be used as an immediate
15376 // value in a data-processing instruction. This can be used in GCC
15377 // with a "B" modifier that prints the inverted value, for use with
15378 // BIC and MVN instructions. It is not useful otherwise but is
15379 // implemented for compatibility.
15380 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15381 break;
15382 } else {
15383 // A constant whose bitwise inverse can be used as an immediate
15384 // value in a data-processing instruction. This can be used in GCC
15385 // with a "B" modifier that prints the inverted value, for use with
15386 // BIC and MVN instructions. It is not useful otherwise but is
15387 // implemented for compatibility.
15388 if (ARM_AM::getSOImmVal(~CVal) != -1)
15389 break;
15391 return;
15393 case 'L':
15394 if (Subtarget->isThumb1Only()) {
15395 // This must be a constant between -7 and 7,
15396 // for 3-operand ADD/SUB immediate instructions.
15397 if (CVal >= -7 && CVal < 7)
15398 break;
15399 } else if (Subtarget->isThumb2()) {
15400 // A constant whose negation can be used as an immediate value in a
15401 // data-processing instruction. This can be used in GCC with an "n"
15402 // modifier that prints the negated value, for use with SUB
15403 // instructions. It is not useful otherwise but is implemented for
15404 // compatibility.
15405 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15406 break;
15407 } else {
15408 // A constant whose negation can be used as an immediate value in a
15409 // data-processing instruction. This can be used in GCC with an "n"
15410 // modifier that prints the negated value, for use with SUB
15411 // instructions. It is not useful otherwise but is implemented for
15412 // compatibility.
15413 if (ARM_AM::getSOImmVal(-CVal) != -1)
15414 break;
15416 return;
15418 case 'M':
15419 if (Subtarget->isThumb1Only()) {
15420 // This must be a multiple of 4 between 0 and 1020, for
15421 // ADD sp + immediate.
15422 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15423 break;
15424 } else {
15425 // A power of two or a constant between 0 and 32. This is used in
15426 // GCC for the shift amount on shifted register operands, but it is
15427 // useful in general for any shift amounts.
15428 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15429 break;
15431 return;
15433 case 'N':
15434 if (Subtarget->isThumb()) { // FIXME thumb2
15435 // This must be a constant between 0 and 31, for shift amounts.
15436 if (CVal >= 0 && CVal <= 31)
15437 break;
15439 return;
15441 case 'O':
15442 if (Subtarget->isThumb()) { // FIXME thumb2
15443 // This must be a multiple of 4 between -508 and 508, for
15444 // ADD/SUB sp = sp + immediate.
15445 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15446 break;
15448 return;
15450 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15451 break;
15454 if (Result.getNode()) {
15455 Ops.push_back(Result);
15456 return;
15458 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15461 static RTLIB::Libcall getDivRemLibcall(
15462 const SDNode *N, MVT::SimpleValueType SVT) {
15463 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15464 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15465 "Unhandled Opcode in getDivRemLibcall");
15466 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15467 N->getOpcode() == ISD::SREM;
15468 RTLIB::Libcall LC;
15469 switch (SVT) {
15470 default: llvm_unreachable("Unexpected request for libcall!");
15471 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15472 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15473 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15474 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15476 return LC;
15479 static TargetLowering::ArgListTy getDivRemArgList(
15480 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15481 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15482 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15483 "Unhandled Opcode in getDivRemArgList");
15484 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15485 N->getOpcode() == ISD::SREM;
15486 TargetLowering::ArgListTy Args;
15487 TargetLowering::ArgListEntry Entry;
15488 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15489 EVT ArgVT = N->getOperand(i).getValueType();
15490 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15491 Entry.Node = N->getOperand(i);
15492 Entry.Ty = ArgTy;
15493 Entry.IsSExt = isSigned;
15494 Entry.IsZExt = !isSigned;
15495 Args.push_back(Entry);
15497 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15498 std::swap(Args[0], Args[1]);
15499 return Args;
15502 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15503 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15504 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15505 Subtarget->isTargetWindows()) &&
15506 "Register-based DivRem lowering only");
15507 unsigned Opcode = Op->getOpcode();
15508 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15509 "Invalid opcode for Div/Rem lowering");
15510 bool isSigned = (Opcode == ISD::SDIVREM);
15511 EVT VT = Op->getValueType(0);
15512 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15513 SDLoc dl(Op);
15515 // If the target has hardware divide, use divide + multiply + subtract:
15516 // div = a / b
15517 // rem = a - b * div
15518 // return {div, rem}
15519 // This should be lowered into UDIV/SDIV + MLS later on.
15520 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15521 : Subtarget->hasDivideInARMMode();
15522 if (hasDivide && Op->getValueType(0).isSimple() &&
15523 Op->getSimpleValueType(0) == MVT::i32) {
15524 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15525 const SDValue Dividend = Op->getOperand(0);
15526 const SDValue Divisor = Op->getOperand(1);
15527 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15528 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15529 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15531 SDValue Values[2] = {Div, Rem};
15532 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15535 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15536 VT.getSimpleVT().SimpleTy);
15537 SDValue InChain = DAG.getEntryNode();
15539 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15540 DAG.getContext(),
15541 Subtarget);
15543 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15544 getPointerTy(DAG.getDataLayout()));
15546 Type *RetTy = StructType::get(Ty, Ty);
15548 if (Subtarget->isTargetWindows())
15549 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15551 TargetLowering::CallLoweringInfo CLI(DAG);
15552 CLI.setDebugLoc(dl).setChain(InChain)
15553 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15554 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15556 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15557 return CallInfo.first;
15560 // Lowers REM using divmod helpers
15561 // see RTABI section 4.2/4.3
15562 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15563 // Build return types (div and rem)
15564 std::vector<Type*> RetTyParams;
15565 Type *RetTyElement;
15567 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15568 default: llvm_unreachable("Unexpected request for libcall!");
15569 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15570 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15571 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15572 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15575 RetTyParams.push_back(RetTyElement);
15576 RetTyParams.push_back(RetTyElement);
15577 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15578 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15580 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15581 SimpleTy);
15582 SDValue InChain = DAG.getEntryNode();
15583 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15584 Subtarget);
15585 bool isSigned = N->getOpcode() == ISD::SREM;
15586 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15587 getPointerTy(DAG.getDataLayout()));
15589 if (Subtarget->isTargetWindows())
15590 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15592 // Lower call
15593 CallLoweringInfo CLI(DAG);
15594 CLI.setChain(InChain)
15595 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15596 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15597 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15599 // Return second (rem) result operand (first contains div)
15600 SDNode *ResNode = CallResult.first.getNode();
15601 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15602 return ResNode->getOperand(1);
15605 SDValue
15606 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15607 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15608 SDLoc DL(Op);
15610 // Get the inputs.
15611 SDValue Chain = Op.getOperand(0);
15612 SDValue Size = Op.getOperand(1);
15614 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15615 "no-stack-arg-probe")) {
15616 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15617 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15618 Chain = SP.getValue(1);
15619 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15620 if (Align)
15621 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15622 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15623 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15624 SDValue Ops[2] = { SP, Chain };
15625 return DAG.getMergeValues(Ops, DL);
15628 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15629 DAG.getConstant(2, DL, MVT::i32));
15631 SDValue Flag;
15632 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15633 Flag = Chain.getValue(1);
15635 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15636 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15638 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15639 Chain = NewSP.getValue(1);
15641 SDValue Ops[2] = { NewSP, Chain };
15642 return DAG.getMergeValues(Ops, DL);
15645 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15646 SDValue SrcVal = Op.getOperand(0);
15647 const unsigned DstSz = Op.getValueType().getSizeInBits();
15648 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15649 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15650 "Unexpected type for custom-lowering FP_EXTEND");
15652 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15653 "With both FP DP and 16, any FP conversion is legal!");
15655 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15656 "With FP16, 16 to 32 conversion is legal!");
15658 // Either we are converting from 16 -> 64, without FP16 and/or
15659 // FP.double-precision or without Armv8-fp. So we must do it in two
15660 // steps.
15661 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15662 // without FP16. So we must do a function call.
15663 SDLoc Loc(Op);
15664 RTLIB::Libcall LC;
15665 MakeLibCallOptions CallOptions;
15666 if (SrcSz == 16) {
15667 // Instruction from 16 -> 32
15668 if (Subtarget->hasFP16())
15669 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15670 // Lib call from 16 -> 32
15671 else {
15672 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15673 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15674 "Unexpected type for custom-lowering FP_EXTEND");
15675 SrcVal =
15676 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15680 if (DstSz != 64)
15681 return SrcVal;
15682 // For sure now SrcVal is 32 bits
15683 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15684 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15686 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15687 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15688 "Unexpected type for custom-lowering FP_EXTEND");
15689 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
15692 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15693 SDValue SrcVal = Op.getOperand(0);
15694 EVT SrcVT = SrcVal.getValueType();
15695 EVT DstVT = Op.getValueType();
15696 const unsigned DstSz = Op.getValueType().getSizeInBits();
15697 const unsigned SrcSz = SrcVT.getSizeInBits();
15698 (void)DstSz;
15699 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15700 "Unexpected type for custom-lowering FP_ROUND");
15702 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15703 "With both FP DP and 16, any FP conversion is legal!");
15705 SDLoc Loc(Op);
15707 // Instruction from 32 -> 16 if hasFP16 is valid
15708 if (SrcSz == 32 && Subtarget->hasFP16())
15709 return Op;
15711 // Lib call from 32 -> 16 / 64 -> [32, 16]
15712 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15713 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15714 "Unexpected type for custom-lowering FP_ROUND");
15715 MakeLibCallOptions CallOptions;
15716 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
15719 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15720 SelectionDAG &DAG) const {
15721 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15722 MVT HalfT = MVT::i32;
15723 SDLoc dl(N);
15724 SDValue Hi, Lo, Tmp;
15726 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15727 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15728 return ;
15730 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15731 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15733 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15734 DAG.getConstant(0, dl, HalfT));
15735 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15736 DAG.getConstant(1, dl, HalfT));
15738 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15739 DAG.getConstant(OpTypeBits - 1, dl,
15740 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15741 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15742 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15743 SDValue(Lo.getNode(), 1));
15744 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15745 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15747 Results.push_back(Lo);
15748 Results.push_back(Hi);
15751 bool
15752 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15753 // The ARM target isn't yet aware of offsets.
15754 return false;
15757 bool ARM::isBitFieldInvertedMask(unsigned v) {
15758 if (v == 0xffffffff)
15759 return false;
15761 // there can be 1's on either or both "outsides", all the "inside"
15762 // bits must be 0's
15763 return isShiftedMask_32(~v);
15766 /// isFPImmLegal - Returns true if the target can instruction select the
15767 /// specified FP immediate natively. If false, the legalizer will
15768 /// materialize the FP immediate as a load from a constant pool.
15769 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15770 bool ForCodeSize) const {
15771 if (!Subtarget->hasVFP3Base())
15772 return false;
15773 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15774 return ARM_AM::getFP16Imm(Imm) != -1;
15775 if (VT == MVT::f32)
15776 return ARM_AM::getFP32Imm(Imm) != -1;
15777 if (VT == MVT::f64 && Subtarget->hasFP64())
15778 return ARM_AM::getFP64Imm(Imm) != -1;
15779 return false;
15782 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15783 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15784 /// specified in the intrinsic calls.
15785 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15786 const CallInst &I,
15787 MachineFunction &MF,
15788 unsigned Intrinsic) const {
15789 switch (Intrinsic) {
15790 case Intrinsic::arm_neon_vld1:
15791 case Intrinsic::arm_neon_vld2:
15792 case Intrinsic::arm_neon_vld3:
15793 case Intrinsic::arm_neon_vld4:
15794 case Intrinsic::arm_neon_vld2lane:
15795 case Intrinsic::arm_neon_vld3lane:
15796 case Intrinsic::arm_neon_vld4lane:
15797 case Intrinsic::arm_neon_vld2dup:
15798 case Intrinsic::arm_neon_vld3dup:
15799 case Intrinsic::arm_neon_vld4dup: {
15800 Info.opc = ISD::INTRINSIC_W_CHAIN;
15801 // Conservatively set memVT to the entire set of vectors loaded.
15802 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15803 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15804 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15805 Info.ptrVal = I.getArgOperand(0);
15806 Info.offset = 0;
15807 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15808 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15809 // volatile loads with NEON intrinsics not supported
15810 Info.flags = MachineMemOperand::MOLoad;
15811 return true;
15813 case Intrinsic::arm_neon_vld1x2:
15814 case Intrinsic::arm_neon_vld1x3:
15815 case Intrinsic::arm_neon_vld1x4: {
15816 Info.opc = ISD::INTRINSIC_W_CHAIN;
15817 // Conservatively set memVT to the entire set of vectors loaded.
15818 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15819 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15820 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15821 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15822 Info.offset = 0;
15823 Info.align.reset();
15824 // volatile loads with NEON intrinsics not supported
15825 Info.flags = MachineMemOperand::MOLoad;
15826 return true;
15828 case Intrinsic::arm_neon_vst1:
15829 case Intrinsic::arm_neon_vst2:
15830 case Intrinsic::arm_neon_vst3:
15831 case Intrinsic::arm_neon_vst4:
15832 case Intrinsic::arm_neon_vst2lane:
15833 case Intrinsic::arm_neon_vst3lane:
15834 case Intrinsic::arm_neon_vst4lane: {
15835 Info.opc = ISD::INTRINSIC_VOID;
15836 // Conservatively set memVT to the entire set of vectors stored.
15837 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15838 unsigned NumElts = 0;
15839 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15840 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15841 if (!ArgTy->isVectorTy())
15842 break;
15843 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15845 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15846 Info.ptrVal = I.getArgOperand(0);
15847 Info.offset = 0;
15848 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15849 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15850 // volatile stores with NEON intrinsics not supported
15851 Info.flags = MachineMemOperand::MOStore;
15852 return true;
15854 case Intrinsic::arm_neon_vst1x2:
15855 case Intrinsic::arm_neon_vst1x3:
15856 case Intrinsic::arm_neon_vst1x4: {
15857 Info.opc = ISD::INTRINSIC_VOID;
15858 // Conservatively set memVT to the entire set of vectors stored.
15859 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15860 unsigned NumElts = 0;
15861 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15862 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15863 if (!ArgTy->isVectorTy())
15864 break;
15865 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15867 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15868 Info.ptrVal = I.getArgOperand(0);
15869 Info.offset = 0;
15870 Info.align.reset();
15871 // volatile stores with NEON intrinsics not supported
15872 Info.flags = MachineMemOperand::MOStore;
15873 return true;
15875 case Intrinsic::arm_ldaex:
15876 case Intrinsic::arm_ldrex: {
15877 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15878 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15879 Info.opc = ISD::INTRINSIC_W_CHAIN;
15880 Info.memVT = MVT::getVT(PtrTy->getElementType());
15881 Info.ptrVal = I.getArgOperand(0);
15882 Info.offset = 0;
15883 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15884 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15885 return true;
15887 case Intrinsic::arm_stlex:
15888 case Intrinsic::arm_strex: {
15889 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15890 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15891 Info.opc = ISD::INTRINSIC_W_CHAIN;
15892 Info.memVT = MVT::getVT(PtrTy->getElementType());
15893 Info.ptrVal = I.getArgOperand(1);
15894 Info.offset = 0;
15895 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15896 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15897 return true;
15899 case Intrinsic::arm_stlexd:
15900 case Intrinsic::arm_strexd:
15901 Info.opc = ISD::INTRINSIC_W_CHAIN;
15902 Info.memVT = MVT::i64;
15903 Info.ptrVal = I.getArgOperand(2);
15904 Info.offset = 0;
15905 Info.align = Align(8);
15906 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15907 return true;
15909 case Intrinsic::arm_ldaexd:
15910 case Intrinsic::arm_ldrexd:
15911 Info.opc = ISD::INTRINSIC_W_CHAIN;
15912 Info.memVT = MVT::i64;
15913 Info.ptrVal = I.getArgOperand(0);
15914 Info.offset = 0;
15915 Info.align = Align(8);
15916 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15917 return true;
15919 default:
15920 break;
15923 return false;
15926 /// Returns true if it is beneficial to convert a load of a constant
15927 /// to just the constant itself.
15928 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15929 Type *Ty) const {
15930 assert(Ty->isIntegerTy());
15932 unsigned Bits = Ty->getPrimitiveSizeInBits();
15933 if (Bits == 0 || Bits > 32)
15934 return false;
15935 return true;
15938 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15939 unsigned Index) const {
15940 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15941 return false;
15943 return (Index == 0 || Index == ResVT.getVectorNumElements());
15946 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15947 ARM_MB::MemBOpt Domain) const {
15948 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15950 // First, if the target has no DMB, see what fallback we can use.
15951 if (!Subtarget->hasDataBarrier()) {
15952 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15953 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15954 // here.
15955 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15956 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15957 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15958 Builder.getInt32(0), Builder.getInt32(7),
15959 Builder.getInt32(10), Builder.getInt32(5)};
15960 return Builder.CreateCall(MCR, args);
15961 } else {
15962 // Instead of using barriers, atomic accesses on these subtargets use
15963 // libcalls.
15964 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15966 } else {
15967 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15968 // Only a full system barrier exists in the M-class architectures.
15969 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15970 Constant *CDomain = Builder.getInt32(Domain);
15971 return Builder.CreateCall(DMB, CDomain);
15975 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15976 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15977 Instruction *Inst,
15978 AtomicOrdering Ord) const {
15979 switch (Ord) {
15980 case AtomicOrdering::NotAtomic:
15981 case AtomicOrdering::Unordered:
15982 llvm_unreachable("Invalid fence: unordered/non-atomic");
15983 case AtomicOrdering::Monotonic:
15984 case AtomicOrdering::Acquire:
15985 return nullptr; // Nothing to do
15986 case AtomicOrdering::SequentiallyConsistent:
15987 if (!Inst->hasAtomicStore())
15988 return nullptr; // Nothing to do
15989 LLVM_FALLTHROUGH;
15990 case AtomicOrdering::Release:
15991 case AtomicOrdering::AcquireRelease:
15992 if (Subtarget->preferISHSTBarriers())
15993 return makeDMB(Builder, ARM_MB::ISHST);
15994 // FIXME: add a comment with a link to documentation justifying this.
15995 else
15996 return makeDMB(Builder, ARM_MB::ISH);
15998 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16001 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16002 Instruction *Inst,
16003 AtomicOrdering Ord) const {
16004 switch (Ord) {
16005 case AtomicOrdering::NotAtomic:
16006 case AtomicOrdering::Unordered:
16007 llvm_unreachable("Invalid fence: unordered/not-atomic");
16008 case AtomicOrdering::Monotonic:
16009 case AtomicOrdering::Release:
16010 return nullptr; // Nothing to do
16011 case AtomicOrdering::Acquire:
16012 case AtomicOrdering::AcquireRelease:
16013 case AtomicOrdering::SequentiallyConsistent:
16014 return makeDMB(Builder, ARM_MB::ISH);
16016 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16019 // Loads and stores less than 64-bits are already atomic; ones above that
16020 // are doomed anyway, so defer to the default libcall and blame the OS when
16021 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16022 // anything for those.
16023 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16024 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16025 return (Size == 64) && !Subtarget->isMClass();
16028 // Loads and stores less than 64-bits are already atomic; ones above that
16029 // are doomed anyway, so defer to the default libcall and blame the OS when
16030 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16031 // anything for those.
16032 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16033 // guarantee, see DDI0406C ARM architecture reference manual,
16034 // sections A8.8.72-74 LDRD)
16035 TargetLowering::AtomicExpansionKind
16036 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16037 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16038 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16039 : AtomicExpansionKind::None;
16042 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16043 // and up to 64 bits on the non-M profiles
16044 TargetLowering::AtomicExpansionKind
16045 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16046 if (AI->isFloatingPointOperation())
16047 return AtomicExpansionKind::CmpXChg;
16049 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16050 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16051 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16052 ? AtomicExpansionKind::LLSC
16053 : AtomicExpansionKind::None;
16056 TargetLowering::AtomicExpansionKind
16057 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16058 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16059 // implement cmpxchg without spilling. If the address being exchanged is also
16060 // on the stack and close enough to the spill slot, this can lead to a
16061 // situation where the monitor always gets cleared and the atomic operation
16062 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16063 bool HasAtomicCmpXchg =
16064 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16065 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16066 return AtomicExpansionKind::LLSC;
16067 return AtomicExpansionKind::None;
16070 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16071 const Instruction *I) const {
16072 return InsertFencesForAtomic;
16075 // This has so far only been implemented for MachO.
16076 bool ARMTargetLowering::useLoadStackGuardNode() const {
16077 return Subtarget->isTargetMachO();
16080 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16081 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16082 return TargetLowering::insertSSPDeclarations(M);
16084 // MSVC CRT has a global variable holding security cookie.
16085 M.getOrInsertGlobal("__security_cookie",
16086 Type::getInt8PtrTy(M.getContext()));
16088 // MSVC CRT has a function to validate security cookie.
16089 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16090 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16091 Type::getInt8PtrTy(M.getContext()));
16092 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16093 F->addAttribute(1, Attribute::AttrKind::InReg);
16096 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16097 // MSVC CRT has a global variable holding security cookie.
16098 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16099 return M.getGlobalVariable("__security_cookie");
16100 return TargetLowering::getSDagStackGuard(M);
16103 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16104 // MSVC CRT has a function to validate security cookie.
16105 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16106 return M.getFunction("__security_check_cookie");
16107 return TargetLowering::getSSPStackGuardCheck(M);
16110 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16111 unsigned &Cost) const {
16112 // If we do not have NEON, vector types are not natively supported.
16113 if (!Subtarget->hasNEON())
16114 return false;
16116 // Floating point values and vector values map to the same register file.
16117 // Therefore, although we could do a store extract of a vector type, this is
16118 // better to leave at float as we have more freedom in the addressing mode for
16119 // those.
16120 if (VectorTy->isFPOrFPVectorTy())
16121 return false;
16123 // If the index is unknown at compile time, this is very expensive to lower
16124 // and it is not possible to combine the store with the extract.
16125 if (!isa<ConstantInt>(Idx))
16126 return false;
16128 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16129 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16130 // We can do a store + vector extract on any vector that fits perfectly in a D
16131 // or Q register.
16132 if (BitWidth == 64 || BitWidth == 128) {
16133 Cost = 0;
16134 return true;
16136 return false;
16139 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16140 return Subtarget->hasV6T2Ops();
16143 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16144 return Subtarget->hasV6T2Ops();
16147 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16148 return !Subtarget->hasMinSize();
16151 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16152 AtomicOrdering Ord) const {
16153 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16154 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16155 bool IsAcquire = isAcquireOrStronger(Ord);
16157 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16158 // intrinsic must return {i32, i32} and we have to recombine them into a
16159 // single i64 here.
16160 if (ValTy->getPrimitiveSizeInBits() == 64) {
16161 Intrinsic::ID Int =
16162 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16163 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16165 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16166 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16168 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16169 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16170 if (!Subtarget->isLittle())
16171 std::swap (Lo, Hi);
16172 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16173 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16174 return Builder.CreateOr(
16175 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16178 Type *Tys[] = { Addr->getType() };
16179 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16180 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16182 return Builder.CreateTruncOrBitCast(
16183 Builder.CreateCall(Ldrex, Addr),
16184 cast<PointerType>(Addr->getType())->getElementType());
16187 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16188 IRBuilder<> &Builder) const {
16189 if (!Subtarget->hasV7Ops())
16190 return;
16191 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16192 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16195 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16196 Value *Addr,
16197 AtomicOrdering Ord) const {
16198 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16199 bool IsRelease = isReleaseOrStronger(Ord);
16201 // Since the intrinsics must have legal type, the i64 intrinsics take two
16202 // parameters: "i32, i32". We must marshal Val into the appropriate form
16203 // before the call.
16204 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16205 Intrinsic::ID Int =
16206 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16207 Function *Strex = Intrinsic::getDeclaration(M, Int);
16208 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16210 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16211 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16212 if (!Subtarget->isLittle())
16213 std::swap(Lo, Hi);
16214 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16215 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16218 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16219 Type *Tys[] = { Addr->getType() };
16220 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16222 return Builder.CreateCall(
16223 Strex, {Builder.CreateZExtOrBitCast(
16224 Val, Strex->getFunctionType()->getParamType(0)),
16225 Addr});
16229 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16230 return Subtarget->isMClass();
16233 /// A helper function for determining the number of interleaved accesses we
16234 /// will generate when lowering accesses of the given type.
16235 unsigned
16236 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16237 const DataLayout &DL) const {
16238 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16241 bool ARMTargetLowering::isLegalInterleavedAccessType(
16242 VectorType *VecTy, const DataLayout &DL) const {
16244 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16245 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16247 // Ensure the vector doesn't have f16 elements. Even though we could do an
16248 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16249 // f32.
16250 if (VecTy->getElementType()->isHalfTy())
16251 return false;
16253 // Ensure the number of vector elements is greater than 1.
16254 if (VecTy->getNumElements() < 2)
16255 return false;
16257 // Ensure the element type is legal.
16258 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16259 return false;
16261 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16262 // 128 will be split into multiple interleaved accesses.
16263 return VecSize == 64 || VecSize % 128 == 0;
16266 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16267 if (Subtarget->hasNEON())
16268 return 4;
16269 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16272 /// Lower an interleaved load into a vldN intrinsic.
16274 /// E.g. Lower an interleaved load (Factor = 2):
16275 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16276 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16277 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16279 /// Into:
16280 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16281 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16282 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16283 bool ARMTargetLowering::lowerInterleavedLoad(
16284 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16285 ArrayRef<unsigned> Indices, unsigned Factor) const {
16286 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16287 "Invalid interleave factor");
16288 assert(!Shuffles.empty() && "Empty shufflevector input");
16289 assert(Shuffles.size() == Indices.size() &&
16290 "Unmatched number of shufflevectors and indices");
16292 VectorType *VecTy = Shuffles[0]->getType();
16293 Type *EltTy = VecTy->getVectorElementType();
16295 const DataLayout &DL = LI->getModule()->getDataLayout();
16297 // Skip if we do not have NEON and skip illegal vector types. We can
16298 // "legalize" wide vector types into multiple interleaved accesses as long as
16299 // the vector types are divisible by 128.
16300 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16301 return false;
16303 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16305 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16306 // load integer vectors first and then convert to pointer vectors.
16307 if (EltTy->isPointerTy())
16308 VecTy =
16309 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16311 IRBuilder<> Builder(LI);
16313 // The base address of the load.
16314 Value *BaseAddr = LI->getPointerOperand();
16316 if (NumLoads > 1) {
16317 // If we're going to generate more than one load, reset the sub-vector type
16318 // to something legal.
16319 VecTy = VectorType::get(VecTy->getVectorElementType(),
16320 VecTy->getVectorNumElements() / NumLoads);
16322 // We will compute the pointer operand of each load from the original base
16323 // address using GEPs. Cast the base address to a pointer to the scalar
16324 // element type.
16325 BaseAddr = Builder.CreateBitCast(
16326 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16327 LI->getPointerAddressSpace()));
16330 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16332 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16333 Type *Tys[] = {VecTy, Int8Ptr};
16334 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16335 Intrinsic::arm_neon_vld3,
16336 Intrinsic::arm_neon_vld4};
16337 Function *VldnFunc =
16338 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16340 // Holds sub-vectors extracted from the load intrinsic return values. The
16341 // sub-vectors are associated with the shufflevector instructions they will
16342 // replace.
16343 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16345 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16346 // If we're generating more than one load, compute the base address of
16347 // subsequent loads as an offset from the previous.
16348 if (LoadCount > 0)
16349 BaseAddr =
16350 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16351 VecTy->getVectorNumElements() * Factor);
16353 SmallVector<Value *, 2> Ops;
16354 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16355 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16357 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16359 // Replace uses of each shufflevector with the corresponding vector loaded
16360 // by ldN.
16361 for (unsigned i = 0; i < Shuffles.size(); i++) {
16362 ShuffleVectorInst *SV = Shuffles[i];
16363 unsigned Index = Indices[i];
16365 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16367 // Convert the integer vector to pointer vector if the element is pointer.
16368 if (EltTy->isPointerTy())
16369 SubVec = Builder.CreateIntToPtr(
16370 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16371 VecTy->getVectorNumElements()));
16373 SubVecs[SV].push_back(SubVec);
16377 // Replace uses of the shufflevector instructions with the sub-vectors
16378 // returned by the load intrinsic. If a shufflevector instruction is
16379 // associated with more than one sub-vector, those sub-vectors will be
16380 // concatenated into a single wide vector.
16381 for (ShuffleVectorInst *SVI : Shuffles) {
16382 auto &SubVec = SubVecs[SVI];
16383 auto *WideVec =
16384 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16385 SVI->replaceAllUsesWith(WideVec);
16388 return true;
16391 /// Lower an interleaved store into a vstN intrinsic.
16393 /// E.g. Lower an interleaved store (Factor = 3):
16394 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16395 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16396 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16398 /// Into:
16399 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16400 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16401 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16402 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16404 /// Note that the new shufflevectors will be removed and we'll only generate one
16405 /// vst3 instruction in CodeGen.
16407 /// Example for a more general valid mask (Factor 3). Lower:
16408 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16409 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16410 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16412 /// Into:
16413 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16414 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16415 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16416 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16417 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16418 ShuffleVectorInst *SVI,
16419 unsigned Factor) const {
16420 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16421 "Invalid interleave factor");
16423 VectorType *VecTy = SVI->getType();
16424 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16425 "Invalid interleaved store");
16427 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16428 Type *EltTy = VecTy->getVectorElementType();
16429 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16431 const DataLayout &DL = SI->getModule()->getDataLayout();
16433 // Skip if we do not have NEON and skip illegal vector types. We can
16434 // "legalize" wide vector types into multiple interleaved accesses as long as
16435 // the vector types are divisible by 128.
16436 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16437 return false;
16439 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16441 Value *Op0 = SVI->getOperand(0);
16442 Value *Op1 = SVI->getOperand(1);
16443 IRBuilder<> Builder(SI);
16445 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16446 // vectors to integer vectors.
16447 if (EltTy->isPointerTy()) {
16448 Type *IntTy = DL.getIntPtrType(EltTy);
16450 // Convert to the corresponding integer vector.
16451 Type *IntVecTy =
16452 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16453 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16454 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16456 SubVecTy = VectorType::get(IntTy, LaneLen);
16459 // The base address of the store.
16460 Value *BaseAddr = SI->getPointerOperand();
16462 if (NumStores > 1) {
16463 // If we're going to generate more than one store, reset the lane length
16464 // and sub-vector type to something legal.
16465 LaneLen /= NumStores;
16466 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16468 // We will compute the pointer operand of each store from the original base
16469 // address using GEPs. Cast the base address to a pointer to the scalar
16470 // element type.
16471 BaseAddr = Builder.CreateBitCast(
16472 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16473 SI->getPointerAddressSpace()));
16476 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16478 auto Mask = SVI->getShuffleMask();
16480 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16481 Type *Tys[] = {Int8Ptr, SubVecTy};
16482 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16483 Intrinsic::arm_neon_vst3,
16484 Intrinsic::arm_neon_vst4};
16486 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16487 // If we generating more than one store, we compute the base address of
16488 // subsequent stores as an offset from the previous.
16489 if (StoreCount > 0)
16490 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16491 BaseAddr, LaneLen * Factor);
16493 SmallVector<Value *, 6> Ops;
16494 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16496 Function *VstNFunc =
16497 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16499 // Split the shufflevector operands into sub vectors for the new vstN call.
16500 for (unsigned i = 0; i < Factor; i++) {
16501 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16502 if (Mask[IdxI] >= 0) {
16503 Ops.push_back(Builder.CreateShuffleVector(
16504 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16505 } else {
16506 unsigned StartMask = 0;
16507 for (unsigned j = 1; j < LaneLen; j++) {
16508 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16509 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16510 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16511 break;
16514 // Note: If all elements in a chunk are undefs, StartMask=0!
16515 // Note: Filling undef gaps with random elements is ok, since
16516 // those elements were being written anyway (with undefs).
16517 // In the case of all undefs we're defaulting to using elems from 0
16518 // Note: StartMask cannot be negative, it's checked in
16519 // isReInterleaveMask
16520 Ops.push_back(Builder.CreateShuffleVector(
16521 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16525 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16526 Builder.CreateCall(VstNFunc, Ops);
16528 return true;
16531 enum HABaseType {
16532 HA_UNKNOWN = 0,
16533 HA_FLOAT,
16534 HA_DOUBLE,
16535 HA_VECT64,
16536 HA_VECT128
16539 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16540 uint64_t &Members) {
16541 if (auto *ST = dyn_cast<StructType>(Ty)) {
16542 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16543 uint64_t SubMembers = 0;
16544 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16545 return false;
16546 Members += SubMembers;
16548 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16549 uint64_t SubMembers = 0;
16550 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16551 return false;
16552 Members += SubMembers * AT->getNumElements();
16553 } else if (Ty->isFloatTy()) {
16554 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16555 return false;
16556 Members = 1;
16557 Base = HA_FLOAT;
16558 } else if (Ty->isDoubleTy()) {
16559 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16560 return false;
16561 Members = 1;
16562 Base = HA_DOUBLE;
16563 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16564 Members = 1;
16565 switch (Base) {
16566 case HA_FLOAT:
16567 case HA_DOUBLE:
16568 return false;
16569 case HA_VECT64:
16570 return VT->getBitWidth() == 64;
16571 case HA_VECT128:
16572 return VT->getBitWidth() == 128;
16573 case HA_UNKNOWN:
16574 switch (VT->getBitWidth()) {
16575 case 64:
16576 Base = HA_VECT64;
16577 return true;
16578 case 128:
16579 Base = HA_VECT128;
16580 return true;
16581 default:
16582 return false;
16587 return (Members > 0 && Members <= 4);
16590 /// Return the correct alignment for the current calling convention.
16591 unsigned
16592 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16593 DataLayout DL) const {
16594 if (!ArgTy->isVectorTy())
16595 return DL.getABITypeAlignment(ArgTy);
16597 // Avoid over-aligning vector parameters. It would require realigning the
16598 // stack and waste space for no real benefit.
16599 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16602 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16603 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16604 /// passing according to AAPCS rules.
16605 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16606 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16607 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16608 CallingConv::ARM_AAPCS_VFP)
16609 return false;
16611 HABaseType Base = HA_UNKNOWN;
16612 uint64_t Members = 0;
16613 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16614 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16616 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16617 return IsHA || IsIntArray;
16620 unsigned ARMTargetLowering::getExceptionPointerRegister(
16621 const Constant *PersonalityFn) const {
16622 // Platforms which do not use SjLj EH may return values in these registers
16623 // via the personality function.
16624 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16627 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16628 const Constant *PersonalityFn) const {
16629 // Platforms which do not use SjLj EH may return values in these registers
16630 // via the personality function.
16631 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16634 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16635 // Update IsSplitCSR in ARMFunctionInfo.
16636 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16637 AFI->setIsSplitCSR(true);
16640 void ARMTargetLowering::insertCopiesSplitCSR(
16641 MachineBasicBlock *Entry,
16642 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16643 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16644 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16645 if (!IStart)
16646 return;
16648 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16649 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16650 MachineBasicBlock::iterator MBBI = Entry->begin();
16651 for (const MCPhysReg *I = IStart; *I; ++I) {
16652 const TargetRegisterClass *RC = nullptr;
16653 if (ARM::GPRRegClass.contains(*I))
16654 RC = &ARM::GPRRegClass;
16655 else if (ARM::DPRRegClass.contains(*I))
16656 RC = &ARM::DPRRegClass;
16657 else
16658 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16660 Register NewVR = MRI->createVirtualRegister(RC);
16661 // Create copy from CSR to a virtual register.
16662 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16663 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16664 // nounwind. If we want to generalize this later, we may need to emit
16665 // CFI pseudo-instructions.
16666 assert(Entry->getParent()->getFunction().hasFnAttribute(
16667 Attribute::NoUnwind) &&
16668 "Function should be nounwind in insertCopiesSplitCSR!");
16669 Entry->addLiveIn(*I);
16670 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16671 .addReg(*I);
16673 // Insert the copy-back instructions right before the terminator.
16674 for (auto *Exit : Exits)
16675 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16676 TII->get(TargetOpcode::COPY), *I)
16677 .addReg(NewVR);
16681 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16682 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16683 TargetLoweringBase::finalizeLowering(MF);