1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 // This option should go away when tail calls fully work.
58 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
59 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63 EnableARMLongCalls("arm-long-calls", cl::Hidden,
64 cl::desc("Generate calls via indirect call instructions"),
68 ARMInterworking("arm-interworking", cl::Hidden,
69 cl::desc("Enable / disable ARM interworking (for debugging only)"),
73 class ARMCCState : public CCState {
75 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
76 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
77 LLVMContext &C, ParmContext PC)
78 : CCState(CC, isVarArg, MF, TM, locs, C) {
79 assert(((PC == Call) || (PC == Prologue)) &&
80 "ARMCCState users must specify whether their context is call"
81 "or prologue generation.");
87 // The APCS parameter registers.
88 static const uint16_t GPRArgRegs[] = {
89 ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
93 EVT PromotedBitwiseVT) {
94 if (VT != PromotedLdStVT) {
95 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
96 AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
97 PromotedLdStVT.getSimpleVT());
99 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
100 AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
101 PromotedLdStVT.getSimpleVT());
104 EVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
115 setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
120 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
124 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
125 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
129 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
130 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
136 AddPromotedToType (ISD::AND, VT.getSimpleVT(),
137 PromotedBitwiseVT.getSimpleVT());
138 setOperationAction(ISD::OR, VT.getSimpleVT(), Promote);
139 AddPromotedToType (ISD::OR, VT.getSimpleVT(),
140 PromotedBitwiseVT.getSimpleVT());
141 setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
142 AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
143 PromotedBitwiseVT.getSimpleVT());
146 // Neon does not support vector divide/remainder operations.
147 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
148 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
149 setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
150 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
151 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
152 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
156 addRegisterClass(VT, &ARM::DPRRegClass);
157 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
161 addRegisterClass(VT, &ARM::QPRRegClass);
162 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
166 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
167 return new TargetLoweringObjectFileMachO();
169 return new ARMElfTargetObjectFile();
172 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
173 : TargetLowering(TM, createTLOF(TM)) {
174 Subtarget = &TM.getSubtarget<ARMSubtarget>();
175 RegInfo = TM.getRegisterInfo();
176 Itins = TM.getInstrItineraryData();
178 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
180 if (Subtarget->isTargetDarwin()) {
181 // Uses VFP for Thumb libfuncs if available.
182 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
183 // Single-precision floating-point arithmetic.
184 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
185 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
186 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
187 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189 // Double-precision floating-point arithmetic.
190 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
191 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
192 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
193 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195 // Single-precision comparisons.
196 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
197 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
198 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
199 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
200 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
201 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
202 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
203 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
205 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
212 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
214 // Double-precision comparisons.
215 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
216 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
217 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
218 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
219 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
220 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
221 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
222 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
224 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
231 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
233 // Floating-point to integer conversions.
234 // i64 conversions are done via library routines even when generating VFP
235 // instructions, so use the same ones.
236 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
237 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
238 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
239 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241 // Conversions between floating types.
242 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
243 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
245 // Integer to floating-point conversions.
246 // i64 conversions are done via library routines even when generating VFP
247 // instructions, so use the same ones.
248 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
249 // e.g., __floatunsidf vs. __floatunssidfvfp.
250 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
251 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
252 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
253 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
257 // These libcalls are not available in 32-bit.
258 setLibcallName(RTLIB::SHL_I128, 0);
259 setLibcallName(RTLIB::SRL_I128, 0);
260 setLibcallName(RTLIB::SRA_I128, 0);
262 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
263 // Double-precision floating-point arithmetic helper functions
264 // RTABI chapter 4.1.2, Table 2
265 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
266 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
267 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
268 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
269 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
272 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274 // Double-precision floating-point comparison helper functions
275 // RTABI chapter 4.1.2, Table 3
276 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
277 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
278 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
279 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
280 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
281 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
283 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
284 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
285 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
286 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
287 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
288 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
289 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
290 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
291 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
292 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
299 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301 // Single-precision floating-point arithmetic helper functions
302 // RTABI chapter 4.1.2, Table 4
303 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
304 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
305 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
306 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
307 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
310 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312 // Single-precision floating-point comparison helper functions
313 // RTABI chapter 4.1.2, Table 5
314 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
315 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
316 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
317 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
318 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
319 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
321 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
322 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
323 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
324 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
325 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
326 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
327 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
328 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
329 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
330 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
337 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339 // Floating-point to integer conversions.
340 // RTABI chapter 4.1.2, Table 6
341 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
342 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
344 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
345 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
346 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
347 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
348 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
349 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
356 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358 // Conversions between floating types.
359 // RTABI chapter 4.1.2, Table 7
360 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
361 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
362 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
363 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365 // Integer to floating-point conversions.
366 // RTABI chapter 4.1.2, Table 8
367 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
368 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
369 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
370 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
371 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
372 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
373 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
374 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384 // Long long helper functions
385 // RTABI chapter 4.2, Table 9
386 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
387 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
388 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
389 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
390 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
397 // Integer division functions
398 // RTABI chapter 4.3.1
399 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
402 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
403 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
406 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
407 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417 // RTABI chapter 4.3.4
418 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
419 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
420 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
421 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
423 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426 // Use divmod compiler-rt calls for iOS 5.0 and later.
427 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
428 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
429 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
430 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433 if (Subtarget->isThumb1Only())
434 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
437 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
438 !Subtarget->isThumb1Only()) {
439 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
440 if (!Subtarget->isFPOnlySP())
441 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
443 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
450 setTruncStoreAction((MVT::SimpleValueType)VT,
451 (MVT::SimpleValueType)InnerVT, Expand);
452 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setTargetDAGCombine(ISD::INTRINSIC_VOID);
545 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547 setTargetDAGCombine(ISD::SHL);
548 setTargetDAGCombine(ISD::SRL);
549 setTargetDAGCombine(ISD::SRA);
550 setTargetDAGCombine(ISD::SIGN_EXTEND);
551 setTargetDAGCombine(ISD::ZERO_EXTEND);
552 setTargetDAGCombine(ISD::ANY_EXTEND);
553 setTargetDAGCombine(ISD::SELECT_CC);
554 setTargetDAGCombine(ISD::BUILD_VECTOR);
555 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557 setTargetDAGCombine(ISD::STORE);
558 setTargetDAGCombine(ISD::FP_TO_SINT);
559 setTargetDAGCombine(ISD::FP_TO_UINT);
560 setTargetDAGCombine(ISD::FDIV);
562 // It is legal to extload from v4i8 to v4i16 or v4i32.
563 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564 MVT::v4i16, MVT::v2i16,
566 for (unsigned i = 0; i < 6; ++i) {
567 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
573 computeRegisterProperties();
575 // ARM does not have f32 extending load.
576 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
578 // ARM does not have i1 sign extending load.
579 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
581 // ARM supports all 4 flavors of integer indexed load / store.
582 if (!Subtarget->isThumb1Only()) {
583 for (unsigned im = (unsigned)ISD::PRE_INC;
584 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585 setIndexedLoadAction(im, MVT::i1, Legal);
586 setIndexedLoadAction(im, MVT::i8, Legal);
587 setIndexedLoadAction(im, MVT::i16, Legal);
588 setIndexedLoadAction(im, MVT::i32, Legal);
589 setIndexedStoreAction(im, MVT::i1, Legal);
590 setIndexedStoreAction(im, MVT::i8, Legal);
591 setIndexedStoreAction(im, MVT::i16, Legal);
592 setIndexedStoreAction(im, MVT::i32, Legal);
596 // i64 operation support.
597 setOperationAction(ISD::MUL, MVT::i64, Expand);
598 setOperationAction(ISD::MULHU, MVT::i32, Expand);
599 if (Subtarget->isThumb1Only()) {
600 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
603 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605 setOperationAction(ISD::MULHS, MVT::i32, Expand);
607 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL, MVT::i64, Custom);
611 setOperationAction(ISD::SRA, MVT::i64, Custom);
613 if (!Subtarget->isThumb1Only()) {
614 // FIXME: We should do this for Thumb1 as well.
615 setOperationAction(ISD::ADDC, MVT::i32, Custom);
616 setOperationAction(ISD::ADDE, MVT::i32, Custom);
617 setOperationAction(ISD::SUBC, MVT::i32, Custom);
618 setOperationAction(ISD::SUBE, MVT::i32, Custom);
621 // ARM does not have ROTL.
622 setOperationAction(ISD::ROTL, MVT::i32, Expand);
623 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
624 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
628 // These just redirect to CTTZ and CTLZ on ARM.
629 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
630 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
632 // Only ARMv6 has BSWAP.
633 if (!Subtarget->hasV6Ops())
634 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
636 // These are expanded into libcalls.
637 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638 // v7M has a hardware divider
639 setOperationAction(ISD::SDIV, MVT::i32, Expand);
640 setOperationAction(ISD::UDIV, MVT::i32, Expand);
642 setOperationAction(ISD::SREM, MVT::i32, Expand);
643 setOperationAction(ISD::UREM, MVT::i32, Expand);
644 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
647 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
648 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
649 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
653 setOperationAction(ISD::TRAP, MVT::Other, Legal);
655 // Use the default implementation.
656 setOperationAction(ISD::VASTART, MVT::Other, Custom);
657 setOperationAction(ISD::VAARG, MVT::Other, Expand);
658 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
659 setOperationAction(ISD::VAEND, MVT::Other, Expand);
660 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
661 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
663 if (!Subtarget->isTargetDarwin()) {
664 // Non-Darwin platforms may return values in these registers via the
665 // personality function.
666 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
667 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
668 setExceptionPointerRegister(ARM::R0);
669 setExceptionSelectorRegister(ARM::R1);
672 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674 // the default expansion.
675 // FIXME: This should be checking for v6k, not just v6.
676 if (Subtarget->hasDataBarrier() ||
677 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678 // membarrier needs custom lowering; the rest are legal and handled
680 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682 // Custom lowering for 64-bit ops
683 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
684 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
690 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691 setInsertFencesForAtomic(true);
693 // Set them all for expansion, which will force libcalls.
694 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
697 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709 // Unordered/Monotonic case.
710 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712 // Since the libcalls include locking, fold in the fences
713 setShouldFoldAtomicFences(true);
716 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
718 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719 if (!Subtarget->hasV6Ops()) {
720 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
723 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
725 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726 !Subtarget->isThumb1Only()) {
727 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728 // iff target supports vfp2.
729 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
733 // We want to custom lower some of our intrinsics.
734 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735 if (Subtarget->isTargetDarwin()) {
736 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
741 setOperationAction(ISD::SETCC, MVT::i32, Expand);
742 setOperationAction(ISD::SETCC, MVT::f32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f64, Expand);
744 setOperationAction(ISD::SELECT, MVT::i32, Custom);
745 setOperationAction(ISD::SELECT, MVT::f32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f64, Custom);
747 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
751 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
752 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
753 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
755 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
757 // We don't support sin/cos/fmod/copysign/pow
758 setOperationAction(ISD::FSIN, MVT::f64, Expand);
759 setOperationAction(ISD::FSIN, MVT::f32, Expand);
760 setOperationAction(ISD::FCOS, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f64, Expand);
762 setOperationAction(ISD::FREM, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f32, Expand);
764 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765 !Subtarget->isThumb1Only()) {
766 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
769 setOperationAction(ISD::FPOW, MVT::f64, Expand);
770 setOperationAction(ISD::FPOW, MVT::f32, Expand);
772 if (!Subtarget->hasVFP4()) {
773 setOperationAction(ISD::FMA, MVT::f64, Expand);
774 setOperationAction(ISD::FMA, MVT::f32, Expand);
777 // Various VFP goodness
778 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
779 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
780 if (Subtarget->hasVFP2()) {
781 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
782 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
783 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
784 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
786 // Special handling for half-precision FP.
787 if (!Subtarget->hasFP16()) {
788 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
789 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
793 // We have target-specific dag combine patterns for the following nodes:
794 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
795 setTargetDAGCombine(ISD::ADD);
796 setTargetDAGCombine(ISD::SUB);
797 setTargetDAGCombine(ISD::MUL);
799 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
800 setTargetDAGCombine(ISD::AND);
801 setTargetDAGCombine(ISD::OR);
802 setTargetDAGCombine(ISD::XOR);
805 if (Subtarget->hasV6Ops())
806 setTargetDAGCombine(ISD::SRL);
808 setStackPointerRegisterToSaveRestore(ARM::SP);
810 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
811 !Subtarget->hasVFP2())
812 setSchedulingPreference(Sched::RegPressure);
814 setSchedulingPreference(Sched::Hybrid);
816 //// temporary - rewrite interface to use type
817 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
818 maxStoresPerMemset = 16;
819 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
821 // On ARM arguments smaller than 4 bytes are extended, so all arguments
822 // are at least 4 bytes aligned.
823 setMinStackArgumentAlignment(4);
825 benefitFromCodePlacementOpt = true;
827 // Prefer likely predicted branches to selects on out-of-order cores.
828 predictableSelectIsExpensive = Subtarget->isCortexA9();
830 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
833 // FIXME: It might make sense to define the representative register class as the
834 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
835 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
836 // SPR's representative would be DPR_VFP2. This should work well if register
837 // pressure tracking were modified such that a register use would increment the
838 // pressure of the register class's representative and all of it's super
839 // classes' representatives transitively. We have not implemented this because
840 // of the difficulty prior to coalescing of modeling operand register classes
841 // due to the common occurrence of cross class copies and subregister insertions
843 std::pair<const TargetRegisterClass*, uint8_t>
844 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
845 const TargetRegisterClass *RRC = 0;
847 switch (VT.getSimpleVT().SimpleTy) {
849 return TargetLowering::findRepresentativeClass(VT);
850 // Use DPR as representative register class for all floating point
851 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
852 // the cost is 1 for both f32 and f64.
853 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
854 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
855 RRC = &ARM::DPRRegClass;
856 // When NEON is used for SP, only half of the register file is available
857 // because operations that define both SP and DP results will be constrained
858 // to the VFP2 class (D0-D15). We currently model this constraint prior to
859 // coalescing by double-counting the SP regs. See the FIXME above.
860 if (Subtarget->useNEONForSinglePrecisionFP())
863 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
864 case MVT::v4f32: case MVT::v2f64:
865 RRC = &ARM::DPRRegClass;
869 RRC = &ARM::DPRRegClass;
873 RRC = &ARM::DPRRegClass;
877 return std::make_pair(RRC, Cost);
880 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
883 case ARMISD::Wrapper: return "ARMISD::Wrapper";
884 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
885 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
886 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
887 case ARMISD::CALL: return "ARMISD::CALL";
888 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
889 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
890 case ARMISD::tCALL: return "ARMISD::tCALL";
891 case ARMISD::BRCOND: return "ARMISD::BRCOND";
892 case ARMISD::BR_JT: return "ARMISD::BR_JT";
893 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
894 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
895 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
896 case ARMISD::CMP: return "ARMISD::CMP";
897 case ARMISD::CMPZ: return "ARMISD::CMPZ";
898 case ARMISD::CMPFP: return "ARMISD::CMPFP";
899 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
900 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
901 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
903 case ARMISD::CMOV: return "ARMISD::CMOV";
904 case ARMISD::CAND: return "ARMISD::CAND";
905 case ARMISD::COR: return "ARMISD::COR";
906 case ARMISD::CXOR: return "ARMISD::CXOR";
908 case ARMISD::RBIT: return "ARMISD::RBIT";
910 case ARMISD::FTOSI: return "ARMISD::FTOSI";
911 case ARMISD::FTOUI: return "ARMISD::FTOUI";
912 case ARMISD::SITOF: return "ARMISD::SITOF";
913 case ARMISD::UITOF: return "ARMISD::UITOF";
915 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
916 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
917 case ARMISD::RRX: return "ARMISD::RRX";
919 case ARMISD::ADDC: return "ARMISD::ADDC";
920 case ARMISD::ADDE: return "ARMISD::ADDE";
921 case ARMISD::SUBC: return "ARMISD::SUBC";
922 case ARMISD::SUBE: return "ARMISD::SUBE";
924 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
925 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
927 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
928 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
930 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
932 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
934 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
936 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
937 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
939 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
941 case ARMISD::VCEQ: return "ARMISD::VCEQ";
942 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
943 case ARMISD::VCGE: return "ARMISD::VCGE";
944 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
945 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
946 case ARMISD::VCGEU: return "ARMISD::VCGEU";
947 case ARMISD::VCGT: return "ARMISD::VCGT";
948 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
949 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
950 case ARMISD::VCGTU: return "ARMISD::VCGTU";
951 case ARMISD::VTST: return "ARMISD::VTST";
953 case ARMISD::VSHL: return "ARMISD::VSHL";
954 case ARMISD::VSHRs: return "ARMISD::VSHRs";
955 case ARMISD::VSHRu: return "ARMISD::VSHRu";
956 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
957 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
958 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
959 case ARMISD::VSHRN: return "ARMISD::VSHRN";
960 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
961 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
962 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
963 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
964 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
965 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
966 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
967 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
968 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
969 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
970 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
971 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
972 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
973 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
974 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
975 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
976 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
977 case ARMISD::VDUP: return "ARMISD::VDUP";
978 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
979 case ARMISD::VEXT: return "ARMISD::VEXT";
980 case ARMISD::VREV64: return "ARMISD::VREV64";
981 case ARMISD::VREV32: return "ARMISD::VREV32";
982 case ARMISD::VREV16: return "ARMISD::VREV16";
983 case ARMISD::VZIP: return "ARMISD::VZIP";
984 case ARMISD::VUZP: return "ARMISD::VUZP";
985 case ARMISD::VTRN: return "ARMISD::VTRN";
986 case ARMISD::VTBL1: return "ARMISD::VTBL1";
987 case ARMISD::VTBL2: return "ARMISD::VTBL2";
988 case ARMISD::VMULLs: return "ARMISD::VMULLs";
989 case ARMISD::VMULLu: return "ARMISD::VMULLu";
990 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
991 case ARMISD::FMAX: return "ARMISD::FMAX";
992 case ARMISD::FMIN: return "ARMISD::FMIN";
993 case ARMISD::BFI: return "ARMISD::BFI";
994 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
995 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
996 case ARMISD::VBSL: return "ARMISD::VBSL";
997 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
998 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
999 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1000 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1001 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1002 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1003 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1004 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1005 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1006 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1007 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1008 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1009 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1010 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1011 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1012 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1013 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1014 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1015 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1016 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1020 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1021 if (!VT.isVector()) return getPointerTy();
1022 return VT.changeVectorElementTypeToInteger();
1025 /// getRegClassFor - Return the register class that should be used for the
1026 /// specified value type.
1027 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1028 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1029 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1030 // load / store 4 to 8 consecutive D registers.
1031 if (Subtarget->hasNEON()) {
1032 if (VT == MVT::v4i64)
1033 return &ARM::QQPRRegClass;
1034 if (VT == MVT::v8i64)
1035 return &ARM::QQQQPRRegClass;
1037 return TargetLowering::getRegClassFor(VT);
1040 // Create a fast isel object.
1042 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1043 return ARM::createFastISel(funcInfo);
1046 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1047 /// be used for loads / stores from the global.
1048 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1049 return (Subtarget->isThumb1Only() ? 127 : 4095);
1052 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1053 unsigned NumVals = N->getNumValues();
1055 return Sched::RegPressure;
1057 for (unsigned i = 0; i != NumVals; ++i) {
1058 EVT VT = N->getValueType(i);
1059 if (VT == MVT::Glue || VT == MVT::Other)
1061 if (VT.isFloatingPoint() || VT.isVector())
1065 if (!N->isMachineOpcode())
1066 return Sched::RegPressure;
1068 // Load are scheduled for latency even if there instruction itinerary
1069 // is not available.
1070 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1071 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1073 if (MCID.getNumDefs() == 0)
1074 return Sched::RegPressure;
1075 if (!Itins->isEmpty() &&
1076 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1079 return Sched::RegPressure;
1082 //===----------------------------------------------------------------------===//
1084 //===----------------------------------------------------------------------===//
1086 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1087 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1089 default: llvm_unreachable("Unknown condition code!");
1090 case ISD::SETNE: return ARMCC::NE;
1091 case ISD::SETEQ: return ARMCC::EQ;
1092 case ISD::SETGT: return ARMCC::GT;
1093 case ISD::SETGE: return ARMCC::GE;
1094 case ISD::SETLT: return ARMCC::LT;
1095 case ISD::SETLE: return ARMCC::LE;
1096 case ISD::SETUGT: return ARMCC::HI;
1097 case ISD::SETUGE: return ARMCC::HS;
1098 case ISD::SETULT: return ARMCC::LO;
1099 case ISD::SETULE: return ARMCC::LS;
1103 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1104 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1105 ARMCC::CondCodes &CondCode2) {
1106 CondCode2 = ARMCC::AL;
1108 default: llvm_unreachable("Unknown FP condition!");
1110 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1112 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1114 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1115 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1116 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1117 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1118 case ISD::SETO: CondCode = ARMCC::VC; break;
1119 case ISD::SETUO: CondCode = ARMCC::VS; break;
1120 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1121 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1122 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1124 case ISD::SETULT: CondCode = ARMCC::LT; break;
1126 case ISD::SETULE: CondCode = ARMCC::LE; break;
1128 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1132 //===----------------------------------------------------------------------===//
1133 // Calling Convention Implementation
1134 //===----------------------------------------------------------------------===//
1136 #include "ARMGenCallingConv.inc"
1138 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1139 /// given CallingConvention value.
1140 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1142 bool isVarArg) const {
1145 llvm_unreachable("Unsupported calling convention");
1146 case CallingConv::Fast:
1147 if (Subtarget->hasVFP2() && !isVarArg) {
1148 if (!Subtarget->isAAPCS_ABI())
1149 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1150 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1151 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1154 case CallingConv::C: {
1155 // Use target triple & subtarget features to do actual dispatch.
1156 if (!Subtarget->isAAPCS_ABI())
1157 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1158 else if (Subtarget->hasVFP2() &&
1159 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1161 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1164 case CallingConv::ARM_AAPCS_VFP:
1166 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1168 case CallingConv::ARM_AAPCS:
1169 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1170 case CallingConv::ARM_APCS:
1171 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1175 /// LowerCallResult - Lower the result values of a call into the
1176 /// appropriate copies out of appropriate physical registers.
1178 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1179 CallingConv::ID CallConv, bool isVarArg,
1180 const SmallVectorImpl<ISD::InputArg> &Ins,
1181 DebugLoc dl, SelectionDAG &DAG,
1182 SmallVectorImpl<SDValue> &InVals) const {
1184 // Assign locations to each value returned by this call.
1185 SmallVector<CCValAssign, 16> RVLocs;
1186 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1187 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1188 CCInfo.AnalyzeCallResult(Ins,
1189 CCAssignFnForNode(CallConv, /* Return*/ true,
1192 // Copy all of the result registers out of their specified physreg.
1193 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1194 CCValAssign VA = RVLocs[i];
1197 if (VA.needsCustom()) {
1198 // Handle f64 or half of a v2f64.
1199 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1201 Chain = Lo.getValue(1);
1202 InFlag = Lo.getValue(2);
1203 VA = RVLocs[++i]; // skip ahead to next loc
1204 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1206 Chain = Hi.getValue(1);
1207 InFlag = Hi.getValue(2);
1208 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1210 if (VA.getLocVT() == MVT::v2f64) {
1211 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1212 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1213 DAG.getConstant(0, MVT::i32));
1215 VA = RVLocs[++i]; // skip ahead to next loc
1216 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1217 Chain = Lo.getValue(1);
1218 InFlag = Lo.getValue(2);
1219 VA = RVLocs[++i]; // skip ahead to next loc
1220 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221 Chain = Hi.getValue(1);
1222 InFlag = Hi.getValue(2);
1223 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1224 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1225 DAG.getConstant(1, MVT::i32));
1228 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1230 Chain = Val.getValue(1);
1231 InFlag = Val.getValue(2);
1234 switch (VA.getLocInfo()) {
1235 default: llvm_unreachable("Unknown loc info!");
1236 case CCValAssign::Full: break;
1237 case CCValAssign::BCvt:
1238 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1242 InVals.push_back(Val);
1248 /// LowerMemOpCallTo - Store the argument to the stack.
1250 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1251 SDValue StackPtr, SDValue Arg,
1252 DebugLoc dl, SelectionDAG &DAG,
1253 const CCValAssign &VA,
1254 ISD::ArgFlagsTy Flags) const {
1255 unsigned LocMemOffset = VA.getLocMemOffset();
1256 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1257 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1258 return DAG.getStore(Chain, dl, Arg, PtrOff,
1259 MachinePointerInfo::getStack(LocMemOffset),
1263 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1264 SDValue Chain, SDValue &Arg,
1265 RegsToPassVector &RegsToPass,
1266 CCValAssign &VA, CCValAssign &NextVA,
1268 SmallVector<SDValue, 8> &MemOpChains,
1269 ISD::ArgFlagsTy Flags) const {
1271 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1272 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1273 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1275 if (NextVA.isRegLoc())
1276 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1278 assert(NextVA.isMemLoc());
1279 if (StackPtr.getNode() == 0)
1280 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1282 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1288 /// LowerCall - Lowering a call into a callseq_start <-
1289 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1292 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1293 CallingConv::ID CallConv, bool isVarArg,
1294 bool doesNotRet, bool &isTailCall,
1295 const SmallVectorImpl<ISD::OutputArg> &Outs,
1296 const SmallVectorImpl<SDValue> &OutVals,
1297 const SmallVectorImpl<ISD::InputArg> &Ins,
1298 DebugLoc dl, SelectionDAG &DAG,
1299 SmallVectorImpl<SDValue> &InVals) const {
1300 MachineFunction &MF = DAG.getMachineFunction();
1301 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1302 bool IsSibCall = false;
1303 // Disable tail calls if they're not supported.
1304 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1307 // Check if it's really possible to do a tail call.
1308 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1309 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1310 Outs, OutVals, Ins, DAG);
1311 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1312 // detected sibcalls.
1319 // Analyze operands of the call, assigning locations to each operand.
1320 SmallVector<CCValAssign, 16> ArgLocs;
1321 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1322 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1323 CCInfo.AnalyzeCallOperands(Outs,
1324 CCAssignFnForNode(CallConv, /* Return*/ false,
1327 // Get a count of how many bytes are to be pushed on the stack.
1328 unsigned NumBytes = CCInfo.getNextStackOffset();
1330 // For tail calls, memory operands are available in our caller's stack.
1334 // Adjust the stack pointer for the new arguments...
1335 // These operations are automatically eliminated by the prolog/epilog pass
1337 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1339 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1341 RegsToPassVector RegsToPass;
1342 SmallVector<SDValue, 8> MemOpChains;
1344 // Walk the register/memloc assignments, inserting copies/loads. In the case
1345 // of tail call optimization, arguments are handled later.
1346 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1348 ++i, ++realArgIdx) {
1349 CCValAssign &VA = ArgLocs[i];
1350 SDValue Arg = OutVals[realArgIdx];
1351 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1352 bool isByVal = Flags.isByVal();
1354 // Promote the value if needed.
1355 switch (VA.getLocInfo()) {
1356 default: llvm_unreachable("Unknown loc info!");
1357 case CCValAssign::Full: break;
1358 case CCValAssign::SExt:
1359 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1361 case CCValAssign::ZExt:
1362 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1364 case CCValAssign::AExt:
1365 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1367 case CCValAssign::BCvt:
1368 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1372 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1373 if (VA.needsCustom()) {
1374 if (VA.getLocVT() == MVT::v2f64) {
1375 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1376 DAG.getConstant(0, MVT::i32));
1377 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1378 DAG.getConstant(1, MVT::i32));
1380 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1381 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1383 VA = ArgLocs[++i]; // skip ahead to next loc
1384 if (VA.isRegLoc()) {
1385 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1386 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1388 assert(VA.isMemLoc());
1390 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1391 dl, DAG, VA, Flags));
1394 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1395 StackPtr, MemOpChains, Flags);
1397 } else if (VA.isRegLoc()) {
1398 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1399 } else if (isByVal) {
1400 assert(VA.isMemLoc());
1401 unsigned offset = 0;
1403 // True if this byval aggregate will be split between registers
1405 if (CCInfo.isFirstByValRegValid()) {
1406 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1408 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1409 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1410 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1411 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1412 MachinePointerInfo(),
1413 false, false, false, 0);
1414 MemOpChains.push_back(Load.getValue(1));
1415 RegsToPass.push_back(std::make_pair(j, Load));
1417 offset = ARM::R4 - CCInfo.getFirstByValReg();
1418 CCInfo.clearFirstByValReg();
1421 unsigned LocMemOffset = VA.getLocMemOffset();
1422 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1423 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1425 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1426 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1427 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1429 MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1430 Flags.getByValAlign(),
1431 /*isVolatile=*/false,
1432 /*AlwaysInline=*/false,
1433 MachinePointerInfo(0),
1434 MachinePointerInfo(0)));
1436 } else if (!IsSibCall) {
1437 assert(VA.isMemLoc());
1439 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1440 dl, DAG, VA, Flags));
1444 if (!MemOpChains.empty())
1445 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1446 &MemOpChains[0], MemOpChains.size());
1448 // Build a sequence of copy-to-reg nodes chained together with token chain
1449 // and flag operands which copy the outgoing args into the appropriate regs.
1451 // Tail call byval lowering might overwrite argument registers so in case of
1452 // tail call optimization the copies to registers are lowered later.
1454 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1455 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1456 RegsToPass[i].second, InFlag);
1457 InFlag = Chain.getValue(1);
1460 // For tail calls lower the arguments to the 'real' stack slot.
1462 // Force all the incoming stack arguments to be loaded from the stack
1463 // before any new outgoing arguments are stored to the stack, because the
1464 // outgoing stack slots may alias the incoming argument stack slots, and
1465 // the alias isn't otherwise explicit. This is slightly more conservative
1466 // than necessary, because it means that each store effectively depends
1467 // on every argument instead of just those arguments it would clobber.
1469 // Do not flag preceding copytoreg stuff together with the following stuff.
1471 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1472 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1473 RegsToPass[i].second, InFlag);
1474 InFlag = Chain.getValue(1);
1479 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1480 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1481 // node so that legalize doesn't hack it.
1482 bool isDirect = false;
1483 bool isARMFunc = false;
1484 bool isLocalARMFunc = false;
1485 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1487 if (EnableARMLongCalls) {
1488 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1489 && "long-calls with non-static relocation model!");
1490 // Handle a global address or an external symbol. If it's not one of
1491 // those, the target's already in a register, so we don't need to do
1493 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1494 const GlobalValue *GV = G->getGlobal();
1495 // Create a constant pool entry for the callee address
1496 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1497 ARMConstantPoolValue *CPV =
1498 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1500 // Get the address of the callee into a register
1501 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1502 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1503 Callee = DAG.getLoad(getPointerTy(), dl,
1504 DAG.getEntryNode(), CPAddr,
1505 MachinePointerInfo::getConstantPool(),
1506 false, false, false, 0);
1507 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1508 const char *Sym = S->getSymbol();
1510 // Create a constant pool entry for the callee address
1511 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1512 ARMConstantPoolValue *CPV =
1513 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1514 ARMPCLabelIndex, 0);
1515 // Get the address of the callee into a register
1516 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1517 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1518 Callee = DAG.getLoad(getPointerTy(), dl,
1519 DAG.getEntryNode(), CPAddr,
1520 MachinePointerInfo::getConstantPool(),
1521 false, false, false, 0);
1523 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1524 const GlobalValue *GV = G->getGlobal();
1526 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1527 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1528 getTargetMachine().getRelocationModel() != Reloc::Static;
1529 isARMFunc = !Subtarget->isThumb() || isStub;
1530 // ARM call to a local ARM function is predicable.
1531 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1532 // tBX takes a register source operand.
1533 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1534 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1535 ARMConstantPoolValue *CPV =
1536 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1537 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1538 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1539 Callee = DAG.getLoad(getPointerTy(), dl,
1540 DAG.getEntryNode(), CPAddr,
1541 MachinePointerInfo::getConstantPool(),
1542 false, false, false, 0);
1543 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1544 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1545 getPointerTy(), Callee, PICLabel);
1547 // On ELF targets for PIC code, direct calls should go through the PLT
1548 unsigned OpFlags = 0;
1549 if (Subtarget->isTargetELF() &&
1550 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1551 OpFlags = ARMII::MO_PLT;
1552 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1554 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1556 bool isStub = Subtarget->isTargetDarwin() &&
1557 getTargetMachine().getRelocationModel() != Reloc::Static;
1558 isARMFunc = !Subtarget->isThumb() || isStub;
1559 // tBX takes a register source operand.
1560 const char *Sym = S->getSymbol();
1561 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1562 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1563 ARMConstantPoolValue *CPV =
1564 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1565 ARMPCLabelIndex, 4);
1566 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1567 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1568 Callee = DAG.getLoad(getPointerTy(), dl,
1569 DAG.getEntryNode(), CPAddr,
1570 MachinePointerInfo::getConstantPool(),
1571 false, false, false, 0);
1572 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1573 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1574 getPointerTy(), Callee, PICLabel);
1576 unsigned OpFlags = 0;
1577 // On ELF targets for PIC code, direct calls should go through the PLT
1578 if (Subtarget->isTargetELF() &&
1579 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1580 OpFlags = ARMII::MO_PLT;
1581 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1585 // FIXME: handle tail calls differently.
1587 if (Subtarget->isThumb()) {
1588 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1589 CallOpc = ARMISD::CALL_NOLINK;
1590 else if (doesNotRet && isDirect && !isARMFunc &&
1591 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1592 // "mov lr, pc; b _foo" to avoid confusing the RSP
1593 CallOpc = ARMISD::CALL_NOLINK;
1595 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1597 if (!isDirect && !Subtarget->hasV5TOps()) {
1598 CallOpc = ARMISD::CALL_NOLINK;
1599 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1600 // "mov lr, pc; b _foo" to avoid confusing the RSP
1601 CallOpc = ARMISD::CALL_NOLINK;
1603 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1606 std::vector<SDValue> Ops;
1607 Ops.push_back(Chain);
1608 Ops.push_back(Callee);
1610 // Add argument registers to the end of the list so that they are known live
1612 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1613 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1614 RegsToPass[i].second.getValueType()));
1616 // Add a register mask operand representing the call-preserved registers.
1617 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1618 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1619 assert(Mask && "Missing call preserved mask for calling convention");
1620 Ops.push_back(DAG.getRegisterMask(Mask));
1622 if (InFlag.getNode())
1623 Ops.push_back(InFlag);
1625 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1627 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1629 // Returns a chain and a flag for retval copy to use.
1630 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1631 InFlag = Chain.getValue(1);
1633 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1634 DAG.getIntPtrConstant(0, true), InFlag);
1636 InFlag = Chain.getValue(1);
1638 // Handle result values, copying them out of physregs into vregs that we
1640 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1644 /// HandleByVal - Every parameter *after* a byval parameter is passed
1645 /// on the stack. Remember the next parameter register to allocate,
1646 /// and then confiscate the rest of the parameter registers to insure
1649 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1650 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1651 assert((State->getCallOrPrologue() == Prologue ||
1652 State->getCallOrPrologue() == Call) &&
1653 "unhandled ParmContext");
1654 if ((!State->isFirstByValRegValid()) &&
1655 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1656 State->setFirstByValReg(reg);
1657 // At a call site, a byval parameter that is split between
1658 // registers and memory needs its size truncated here. In a
1659 // function prologue, such byval parameters are reassembled in
1660 // memory, and are not truncated.
1661 if (State->getCallOrPrologue() == Call) {
1662 unsigned excess = 4 * (ARM::R4 - reg);
1663 assert(size >= excess && "expected larger existing stack allocation");
1667 // Confiscate any remaining parameter registers to preclude their
1668 // assignment to subsequent parameters.
1669 while (State->AllocateReg(GPRArgRegs, 4))
1673 /// MatchingStackOffset - Return true if the given stack call argument is
1674 /// already available in the same position (relatively) of the caller's
1675 /// incoming argument stack.
1677 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1678 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1679 const TargetInstrInfo *TII) {
1680 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1682 if (Arg.getOpcode() == ISD::CopyFromReg) {
1683 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1684 if (!TargetRegisterInfo::isVirtualRegister(VR))
1686 MachineInstr *Def = MRI->getVRegDef(VR);
1689 if (!Flags.isByVal()) {
1690 if (!TII->isLoadFromStackSlot(Def, FI))
1695 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1696 if (Flags.isByVal())
1697 // ByVal argument is passed in as a pointer but it's now being
1698 // dereferenced. e.g.
1699 // define @foo(%struct.X* %A) {
1700 // tail call @bar(%struct.X* byval %A)
1703 SDValue Ptr = Ld->getBasePtr();
1704 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1707 FI = FINode->getIndex();
1711 assert(FI != INT_MAX);
1712 if (!MFI->isFixedObjectIndex(FI))
1714 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1717 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1718 /// for tail call optimization. Targets which want to do tail call
1719 /// optimization should implement this function.
1721 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1722 CallingConv::ID CalleeCC,
1724 bool isCalleeStructRet,
1725 bool isCallerStructRet,
1726 const SmallVectorImpl<ISD::OutputArg> &Outs,
1727 const SmallVectorImpl<SDValue> &OutVals,
1728 const SmallVectorImpl<ISD::InputArg> &Ins,
1729 SelectionDAG& DAG) const {
1730 const Function *CallerF = DAG.getMachineFunction().getFunction();
1731 CallingConv::ID CallerCC = CallerF->getCallingConv();
1732 bool CCMatch = CallerCC == CalleeCC;
1734 // Look for obvious safe cases to perform tail call optimization that do not
1735 // require ABI changes. This is what gcc calls sibcall.
1737 // Do not sibcall optimize vararg calls unless the call site is not passing
1739 if (isVarArg && !Outs.empty())
1742 // Also avoid sibcall optimization if either caller or callee uses struct
1743 // return semantics.
1744 if (isCalleeStructRet || isCallerStructRet)
1747 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1748 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1749 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1750 // support in the assembler and linker to be used. This would need to be
1751 // fixed to fully support tail calls in Thumb1.
1753 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1754 // LR. This means if we need to reload LR, it takes an extra instructions,
1755 // which outweighs the value of the tail call; but here we don't know yet
1756 // whether LR is going to be used. Probably the right approach is to
1757 // generate the tail call here and turn it back into CALL/RET in
1758 // emitEpilogue if LR is used.
1760 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1761 // but we need to make sure there are enough registers; the only valid
1762 // registers are the 4 used for parameters. We don't currently do this
1764 if (Subtarget->isThumb1Only())
1767 // If the calling conventions do not match, then we'd better make sure the
1768 // results are returned in the same way as what the caller expects.
1770 SmallVector<CCValAssign, 16> RVLocs1;
1771 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1772 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1773 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1775 SmallVector<CCValAssign, 16> RVLocs2;
1776 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1777 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1778 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1780 if (RVLocs1.size() != RVLocs2.size())
1782 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1783 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1785 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1787 if (RVLocs1[i].isRegLoc()) {
1788 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1791 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1797 // If the callee takes no arguments then go on to check the results of the
1799 if (!Outs.empty()) {
1800 // Check if stack adjustment is needed. For now, do not do this if any
1801 // argument is passed on the stack.
1802 SmallVector<CCValAssign, 16> ArgLocs;
1803 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1804 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1805 CCInfo.AnalyzeCallOperands(Outs,
1806 CCAssignFnForNode(CalleeCC, false, isVarArg));
1807 if (CCInfo.getNextStackOffset()) {
1808 MachineFunction &MF = DAG.getMachineFunction();
1810 // Check if the arguments are already laid out in the right way as
1811 // the caller's fixed stack objects.
1812 MachineFrameInfo *MFI = MF.getFrameInfo();
1813 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1814 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1815 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1817 ++i, ++realArgIdx) {
1818 CCValAssign &VA = ArgLocs[i];
1819 EVT RegVT = VA.getLocVT();
1820 SDValue Arg = OutVals[realArgIdx];
1821 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1822 if (VA.getLocInfo() == CCValAssign::Indirect)
1824 if (VA.needsCustom()) {
1825 // f64 and vector types are split into multiple registers or
1826 // register/stack-slot combinations. The types will not match
1827 // the registers; give up on memory f64 refs until we figure
1828 // out what to do about this.
1831 if (!ArgLocs[++i].isRegLoc())
1833 if (RegVT == MVT::v2f64) {
1834 if (!ArgLocs[++i].isRegLoc())
1836 if (!ArgLocs[++i].isRegLoc())
1839 } else if (!VA.isRegLoc()) {
1840 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1852 ARMTargetLowering::LowerReturn(SDValue Chain,
1853 CallingConv::ID CallConv, bool isVarArg,
1854 const SmallVectorImpl<ISD::OutputArg> &Outs,
1855 const SmallVectorImpl<SDValue> &OutVals,
1856 DebugLoc dl, SelectionDAG &DAG) const {
1858 // CCValAssign - represent the assignment of the return value to a location.
1859 SmallVector<CCValAssign, 16> RVLocs;
1861 // CCState - Info about the registers and stack slots.
1862 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1863 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1865 // Analyze outgoing return values.
1866 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1869 // If this is the first return lowered for this function, add
1870 // the regs to the liveout set for the function.
1871 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1872 for (unsigned i = 0; i != RVLocs.size(); ++i)
1873 if (RVLocs[i].isRegLoc())
1874 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1879 // Copy the result values into the output registers.
1880 for (unsigned i = 0, realRVLocIdx = 0;
1882 ++i, ++realRVLocIdx) {
1883 CCValAssign &VA = RVLocs[i];
1884 assert(VA.isRegLoc() && "Can only return in registers!");
1886 SDValue Arg = OutVals[realRVLocIdx];
1888 switch (VA.getLocInfo()) {
1889 default: llvm_unreachable("Unknown loc info!");
1890 case CCValAssign::Full: break;
1891 case CCValAssign::BCvt:
1892 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1896 if (VA.needsCustom()) {
1897 if (VA.getLocVT() == MVT::v2f64) {
1898 // Extract the first half and return it in two registers.
1899 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1900 DAG.getConstant(0, MVT::i32));
1901 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1902 DAG.getVTList(MVT::i32, MVT::i32), Half);
1904 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1905 Flag = Chain.getValue(1);
1906 VA = RVLocs[++i]; // skip ahead to next loc
1907 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1908 HalfGPRs.getValue(1), Flag);
1909 Flag = Chain.getValue(1);
1910 VA = RVLocs[++i]; // skip ahead to next loc
1912 // Extract the 2nd half and fall through to handle it as an f64 value.
1913 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1914 DAG.getConstant(1, MVT::i32));
1916 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1918 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1919 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1920 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1921 Flag = Chain.getValue(1);
1922 VA = RVLocs[++i]; // skip ahead to next loc
1923 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1926 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1928 // Guarantee that all emitted copies are
1929 // stuck together, avoiding something bad.
1930 Flag = Chain.getValue(1);
1935 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1937 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1942 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1943 if (N->getNumValues() != 1)
1945 if (!N->hasNUsesOfValue(1, 0))
1948 SDValue TCChain = Chain;
1949 SDNode *Copy = *N->use_begin();
1950 if (Copy->getOpcode() == ISD::CopyToReg) {
1951 // If the copy has a glue operand, we conservatively assume it isn't safe to
1952 // perform a tail call.
1953 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1955 TCChain = Copy->getOperand(0);
1956 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1957 SDNode *VMov = Copy;
1958 // f64 returned in a pair of GPRs.
1959 SmallPtrSet<SDNode*, 2> Copies;
1960 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1962 if (UI->getOpcode() != ISD::CopyToReg)
1966 if (Copies.size() > 2)
1969 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1971 SDValue UseChain = UI->getOperand(0);
1972 if (Copies.count(UseChain.getNode()))
1979 } else if (Copy->getOpcode() == ISD::BITCAST) {
1980 // f32 returned in a single GPR.
1981 if (!Copy->hasOneUse())
1983 Copy = *Copy->use_begin();
1984 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1986 Chain = Copy->getOperand(0);
1991 bool HasRet = false;
1992 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1994 if (UI->getOpcode() != ARMISD::RET_FLAG)
2006 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2007 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2010 if (!CI->isTailCall())
2013 return !Subtarget->isThumb1Only();
2016 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2017 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2018 // one of the above mentioned nodes. It has to be wrapped because otherwise
2019 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2020 // be used to form addressing mode. These wrapped nodes will be selected
2022 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2023 EVT PtrVT = Op.getValueType();
2024 // FIXME there is no actual debug info here
2025 DebugLoc dl = Op.getDebugLoc();
2026 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2028 if (CP->isMachineConstantPoolEntry())
2029 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2030 CP->getAlignment());
2032 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2033 CP->getAlignment());
2034 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2037 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2038 return MachineJumpTableInfo::EK_Inline;
2041 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2042 SelectionDAG &DAG) const {
2043 MachineFunction &MF = DAG.getMachineFunction();
2044 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2045 unsigned ARMPCLabelIndex = 0;
2046 DebugLoc DL = Op.getDebugLoc();
2047 EVT PtrVT = getPointerTy();
2048 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2049 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2051 if (RelocM == Reloc::Static) {
2052 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2054 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2055 ARMPCLabelIndex = AFI->createPICLabelUId();
2056 ARMConstantPoolValue *CPV =
2057 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2058 ARMCP::CPBlockAddress, PCAdj);
2059 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2061 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2062 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2063 MachinePointerInfo::getConstantPool(),
2064 false, false, false, 0);
2065 if (RelocM == Reloc::Static)
2067 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2068 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2073 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2074 SelectionDAG &DAG) const {
2075 DebugLoc dl = GA->getDebugLoc();
2076 EVT PtrVT = getPointerTy();
2077 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2078 MachineFunction &MF = DAG.getMachineFunction();
2079 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2080 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2081 ARMConstantPoolValue *CPV =
2082 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2083 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2084 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2085 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2086 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2087 MachinePointerInfo::getConstantPool(),
2088 false, false, false, 0);
2089 SDValue Chain = Argument.getValue(1);
2091 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2092 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2094 // call __tls_get_addr.
2097 Entry.Node = Argument;
2098 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2099 Args.push_back(Entry);
2100 // FIXME: is there useful debug info available here?
2101 std::pair<SDValue, SDValue> CallResult =
2102 LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2103 false, false, false, false,
2104 0, CallingConv::C, /*isTailCall=*/false,
2105 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2106 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2107 return CallResult.first;
2110 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2111 // "local exec" model.
2113 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2115 TLSModel::Model model) const {
2116 const GlobalValue *GV = GA->getGlobal();
2117 DebugLoc dl = GA->getDebugLoc();
2119 SDValue Chain = DAG.getEntryNode();
2120 EVT PtrVT = getPointerTy();
2121 // Get the Thread Pointer
2122 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2124 if (model == TLSModel::InitialExec) {
2125 MachineFunction &MF = DAG.getMachineFunction();
2126 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2127 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2128 // Initial exec model.
2129 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2130 ARMConstantPoolValue *CPV =
2131 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2132 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2134 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2135 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2136 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2137 MachinePointerInfo::getConstantPool(),
2138 false, false, false, 0);
2139 Chain = Offset.getValue(1);
2141 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2142 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2144 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2145 MachinePointerInfo::getConstantPool(),
2146 false, false, false, 0);
2149 assert(model == TLSModel::LocalExec);
2150 ARMConstantPoolValue *CPV =
2151 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2152 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2153 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2154 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2155 MachinePointerInfo::getConstantPool(),
2156 false, false, false, 0);
2159 // The address of the thread local variable is the add of the thread
2160 // pointer with the offset of the variable.
2161 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2165 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2166 // TODO: implement the "local dynamic" model
2167 assert(Subtarget->isTargetELF() &&
2168 "TLS not implemented for non-ELF targets");
2169 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2171 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2174 case TLSModel::GeneralDynamic:
2175 case TLSModel::LocalDynamic:
2176 return LowerToTLSGeneralDynamicModel(GA, DAG);
2177 case TLSModel::InitialExec:
2178 case TLSModel::LocalExec:
2179 return LowerToTLSExecModels(GA, DAG, model);
2181 llvm_unreachable("bogus TLS model");
2184 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2185 SelectionDAG &DAG) const {
2186 EVT PtrVT = getPointerTy();
2187 DebugLoc dl = Op.getDebugLoc();
2188 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2189 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2190 if (RelocM == Reloc::PIC_) {
2191 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2192 ARMConstantPoolValue *CPV =
2193 ARMConstantPoolConstant::Create(GV,
2194 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2195 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2196 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2197 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2199 MachinePointerInfo::getConstantPool(),
2200 false, false, false, 0);
2201 SDValue Chain = Result.getValue(1);
2202 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2203 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2205 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2206 MachinePointerInfo::getGOT(),
2207 false, false, false, 0);
2211 // If we have T2 ops, we can materialize the address directly via movt/movw
2212 // pair. This is always cheaper.
2213 if (Subtarget->useMovt()) {
2215 // FIXME: Once remat is capable of dealing with instructions with register
2216 // operands, expand this into two nodes.
2217 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2218 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2220 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2221 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2222 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2223 MachinePointerInfo::getConstantPool(),
2224 false, false, false, 0);
2228 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2229 SelectionDAG &DAG) const {
2230 EVT PtrVT = getPointerTy();
2231 DebugLoc dl = Op.getDebugLoc();
2232 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2233 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2234 MachineFunction &MF = DAG.getMachineFunction();
2235 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2237 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2238 // update ARMFastISel::ARMMaterializeGV.
2239 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2241 // FIXME: Once remat is capable of dealing with instructions with register
2242 // operands, expand this into two nodes.
2243 if (RelocM == Reloc::Static)
2244 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2245 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2247 unsigned Wrapper = (RelocM == Reloc::PIC_)
2248 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2249 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2250 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2251 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2252 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2253 MachinePointerInfo::getGOT(),
2254 false, false, false, 0);
2258 unsigned ARMPCLabelIndex = 0;
2260 if (RelocM == Reloc::Static) {
2261 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2263 ARMPCLabelIndex = AFI->createPICLabelUId();
2264 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2265 ARMConstantPoolValue *CPV =
2266 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2268 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2270 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2272 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2273 MachinePointerInfo::getConstantPool(),
2274 false, false, false, 0);
2275 SDValue Chain = Result.getValue(1);
2277 if (RelocM == Reloc::PIC_) {
2278 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2279 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2282 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2283 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2284 false, false, false, 0);
2289 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2290 SelectionDAG &DAG) const {
2291 assert(Subtarget->isTargetELF() &&
2292 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2293 MachineFunction &MF = DAG.getMachineFunction();
2294 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2295 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2296 EVT PtrVT = getPointerTy();
2297 DebugLoc dl = Op.getDebugLoc();
2298 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2299 ARMConstantPoolValue *CPV =
2300 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2301 ARMPCLabelIndex, PCAdj);
2302 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2304 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2305 MachinePointerInfo::getConstantPool(),
2306 false, false, false, 0);
2307 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2308 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2312 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2313 DebugLoc dl = Op.getDebugLoc();
2314 SDValue Val = DAG.getConstant(0, MVT::i32);
2315 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2316 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2317 Op.getOperand(1), Val);
2321 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2322 DebugLoc dl = Op.getDebugLoc();
2323 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2324 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2328 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2329 const ARMSubtarget *Subtarget) const {
2330 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2331 DebugLoc dl = Op.getDebugLoc();
2333 default: return SDValue(); // Don't custom lower most intrinsics.
2334 case Intrinsic::arm_thread_pointer: {
2335 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2336 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2338 case Intrinsic::eh_sjlj_lsda: {
2339 MachineFunction &MF = DAG.getMachineFunction();
2340 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2342 EVT PtrVT = getPointerTy();
2343 DebugLoc dl = Op.getDebugLoc();
2344 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2346 unsigned PCAdj = (RelocM != Reloc::PIC_)
2347 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2348 ARMConstantPoolValue *CPV =
2349 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2350 ARMCP::CPLSDA, PCAdj);
2351 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2352 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2354 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2355 MachinePointerInfo::getConstantPool(),
2356 false, false, false, 0);
2358 if (RelocM == Reloc::PIC_) {
2359 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2360 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2364 case Intrinsic::arm_neon_vmulls:
2365 case Intrinsic::arm_neon_vmullu: {
2366 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2367 ? ARMISD::VMULLs : ARMISD::VMULLu;
2368 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2369 Op.getOperand(1), Op.getOperand(2));
2374 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2375 const ARMSubtarget *Subtarget) {
2376 DebugLoc dl = Op.getDebugLoc();
2377 if (!Subtarget->hasDataBarrier()) {
2378 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2379 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2381 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2382 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2383 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2384 DAG.getConstant(0, MVT::i32));
2387 SDValue Op5 = Op.getOperand(5);
2388 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2389 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2390 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2391 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2393 ARM_MB::MemBOpt DMBOpt;
2394 if (isDeviceBarrier)
2395 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2397 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2398 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2399 DAG.getConstant(DMBOpt, MVT::i32));
2403 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2404 const ARMSubtarget *Subtarget) {
2405 // FIXME: handle "fence singlethread" more efficiently.
2406 DebugLoc dl = Op.getDebugLoc();
2407 if (!Subtarget->hasDataBarrier()) {
2408 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2409 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2411 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2412 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2413 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2414 DAG.getConstant(0, MVT::i32));
2417 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2418 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2421 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2422 const ARMSubtarget *Subtarget) {
2423 // ARM pre v5TE and Thumb1 does not have preload instructions.
2424 if (!(Subtarget->isThumb2() ||
2425 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2426 // Just preserve the chain.
2427 return Op.getOperand(0);
2429 DebugLoc dl = Op.getDebugLoc();
2430 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2432 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2433 // ARMv7 with MP extension has PLDW.
2434 return Op.getOperand(0);
2436 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2437 if (Subtarget->isThumb()) {
2439 isRead = ~isRead & 1;
2440 isData = ~isData & 1;
2443 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2444 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2445 DAG.getConstant(isData, MVT::i32));
2448 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2449 MachineFunction &MF = DAG.getMachineFunction();
2450 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2452 // vastart just stores the address of the VarArgsFrameIndex slot into the
2453 // memory location argument.
2454 DebugLoc dl = Op.getDebugLoc();
2455 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2456 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2457 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2458 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2459 MachinePointerInfo(SV), false, false, 0);
2463 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2464 SDValue &Root, SelectionDAG &DAG,
2465 DebugLoc dl) const {
2466 MachineFunction &MF = DAG.getMachineFunction();
2467 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2469 const TargetRegisterClass *RC;
2470 if (AFI->isThumb1OnlyFunction())
2471 RC = &ARM::tGPRRegClass;
2473 RC = &ARM::GPRRegClass;
2475 // Transform the arguments stored in physical registers into virtual ones.
2476 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2477 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2480 if (NextVA.isMemLoc()) {
2481 MachineFrameInfo *MFI = MF.getFrameInfo();
2482 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2484 // Create load node to retrieve arguments from the stack.
2485 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2486 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2487 MachinePointerInfo::getFixedStack(FI),
2488 false, false, false, 0);
2490 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2491 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2494 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2498 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2499 unsigned &VARegSize, unsigned &VARegSaveSize)
2502 if (CCInfo.isFirstByValRegValid())
2503 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2505 unsigned int firstUnalloced;
2506 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2507 sizeof(GPRArgRegs) /
2508 sizeof(GPRArgRegs[0]));
2509 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2512 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2513 VARegSize = NumGPRs * 4;
2514 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2517 // The remaining GPRs hold either the beginning of variable-argument
2518 // data, or the beginning of an aggregate passed by value (usuall
2519 // byval). Either way, we allocate stack slots adjacent to the data
2520 // provided by our caller, and store the unallocated registers there.
2521 // If this is a variadic function, the va_list pointer will begin with
2522 // these values; otherwise, this reassembles a (byval) structure that
2523 // was split between registers and memory.
2525 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2526 DebugLoc dl, SDValue &Chain,
2527 unsigned ArgOffset) const {
2528 MachineFunction &MF = DAG.getMachineFunction();
2529 MachineFrameInfo *MFI = MF.getFrameInfo();
2530 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531 unsigned firstRegToSaveIndex;
2532 if (CCInfo.isFirstByValRegValid())
2533 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2535 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2536 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2539 unsigned VARegSize, VARegSaveSize;
2540 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2541 if (VARegSaveSize) {
2542 // If this function is vararg, store any remaining integer argument regs
2543 // to their spots on the stack so that they may be loaded by deferencing
2544 // the result of va_next.
2545 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2546 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2547 ArgOffset + VARegSaveSize
2550 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2553 SmallVector<SDValue, 4> MemOps;
2554 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2555 const TargetRegisterClass *RC;
2556 if (AFI->isThumb1OnlyFunction())
2557 RC = &ARM::tGPRRegClass;
2559 RC = &ARM::GPRRegClass;
2561 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2562 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2564 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2565 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2567 MemOps.push_back(Store);
2568 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2569 DAG.getConstant(4, getPointerTy()));
2571 if (!MemOps.empty())
2572 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2573 &MemOps[0], MemOps.size());
2575 // This will point to the next argument passed via stack.
2576 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2580 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2581 CallingConv::ID CallConv, bool isVarArg,
2582 const SmallVectorImpl<ISD::InputArg>
2584 DebugLoc dl, SelectionDAG &DAG,
2585 SmallVectorImpl<SDValue> &InVals)
2587 MachineFunction &MF = DAG.getMachineFunction();
2588 MachineFrameInfo *MFI = MF.getFrameInfo();
2590 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2592 // Assign locations to all of the incoming arguments.
2593 SmallVector<CCValAssign, 16> ArgLocs;
2594 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2595 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2596 CCInfo.AnalyzeFormalArguments(Ins,
2597 CCAssignFnForNode(CallConv, /* Return*/ false,
2600 SmallVector<SDValue, 16> ArgValues;
2601 int lastInsIndex = -1;
2604 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2605 CCValAssign &VA = ArgLocs[i];
2607 // Arguments stored in registers.
2608 if (VA.isRegLoc()) {
2609 EVT RegVT = VA.getLocVT();
2611 if (VA.needsCustom()) {
2612 // f64 and vector types are split up into multiple registers or
2613 // combinations of registers and stack slots.
2614 if (VA.getLocVT() == MVT::v2f64) {
2615 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2617 VA = ArgLocs[++i]; // skip ahead to next loc
2619 if (VA.isMemLoc()) {
2620 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2621 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2622 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2623 MachinePointerInfo::getFixedStack(FI),
2624 false, false, false, 0);
2626 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2629 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2630 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2631 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2632 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2633 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2635 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2638 const TargetRegisterClass *RC;
2640 if (RegVT == MVT::f32)
2641 RC = &ARM::SPRRegClass;
2642 else if (RegVT == MVT::f64)
2643 RC = &ARM::DPRRegClass;
2644 else if (RegVT == MVT::v2f64)
2645 RC = &ARM::QPRRegClass;
2646 else if (RegVT == MVT::i32)
2647 RC = AFI->isThumb1OnlyFunction() ?
2648 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2649 (const TargetRegisterClass*)&ARM::GPRRegClass;
2651 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2653 // Transform the arguments in physical registers into virtual ones.
2654 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2655 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2658 // If this is an 8 or 16-bit value, it is really passed promoted
2659 // to 32 bits. Insert an assert[sz]ext to capture this, then
2660 // truncate to the right size.
2661 switch (VA.getLocInfo()) {
2662 default: llvm_unreachable("Unknown loc info!");
2663 case CCValAssign::Full: break;
2664 case CCValAssign::BCvt:
2665 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2667 case CCValAssign::SExt:
2668 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2669 DAG.getValueType(VA.getValVT()));
2670 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2672 case CCValAssign::ZExt:
2673 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2674 DAG.getValueType(VA.getValVT()));
2675 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2679 InVals.push_back(ArgValue);
2681 } else { // VA.isRegLoc()
2684 assert(VA.isMemLoc());
2685 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2687 int index = ArgLocs[i].getValNo();
2689 // Some Ins[] entries become multiple ArgLoc[] entries.
2690 // Process them only once.
2691 if (index != lastInsIndex)
2693 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2694 // FIXME: For now, all byval parameter objects are marked mutable.
2695 // This can be changed with more analysis.
2696 // In case of tail call optimization mark all arguments mutable.
2697 // Since they could be overwritten by lowering of arguments in case of
2699 if (Flags.isByVal()) {
2700 unsigned VARegSize, VARegSaveSize;
2701 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2702 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2703 unsigned Bytes = Flags.getByValSize() - VARegSize;
2704 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2705 int FI = MFI->CreateFixedObject(Bytes,
2706 VA.getLocMemOffset(), false);
2707 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2709 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2710 VA.getLocMemOffset(), true);
2712 // Create load nodes to retrieve arguments from the stack.
2713 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2714 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2715 MachinePointerInfo::getFixedStack(FI),
2716 false, false, false, 0));
2718 lastInsIndex = index;
2725 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2730 /// isFloatingPointZero - Return true if this is +0.0.
2731 static bool isFloatingPointZero(SDValue Op) {
2732 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2733 return CFP->getValueAPF().isPosZero();
2734 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2735 // Maybe this has already been legalized into the constant pool?
2736 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2737 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2738 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2739 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2740 return CFP->getValueAPF().isPosZero();
2746 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2747 /// the given operands.
2749 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2750 SDValue &ARMcc, SelectionDAG &DAG,
2751 DebugLoc dl) const {
2752 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2753 unsigned C = RHSC->getZExtValue();
2754 if (!isLegalICmpImmediate(C)) {
2755 // Constant does not fit, try adjusting it by one?
2760 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2761 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2762 RHS = DAG.getConstant(C-1, MVT::i32);
2767 if (C != 0 && isLegalICmpImmediate(C-1)) {
2768 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2769 RHS = DAG.getConstant(C-1, MVT::i32);
2774 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2775 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2776 RHS = DAG.getConstant(C+1, MVT::i32);
2781 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2782 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2783 RHS = DAG.getConstant(C+1, MVT::i32);
2790 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2791 ARMISD::NodeType CompareType;
2794 CompareType = ARMISD::CMP;
2799 CompareType = ARMISD::CMPZ;
2802 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2803 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2806 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2808 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2809 DebugLoc dl) const {
2811 if (!isFloatingPointZero(RHS))
2812 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2814 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2815 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2818 /// duplicateCmp - Glue values can have only one use, so this function
2819 /// duplicates a comparison node.
2821 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2822 unsigned Opc = Cmp.getOpcode();
2823 DebugLoc DL = Cmp.getDebugLoc();
2824 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2825 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2827 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2828 Cmp = Cmp.getOperand(0);
2829 Opc = Cmp.getOpcode();
2830 if (Opc == ARMISD::CMPFP)
2831 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2833 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2834 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2836 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2839 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2840 SDValue Cond = Op.getOperand(0);
2841 SDValue SelectTrue = Op.getOperand(1);
2842 SDValue SelectFalse = Op.getOperand(2);
2843 DebugLoc dl = Op.getDebugLoc();
2847 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2848 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2850 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2851 const ConstantSDNode *CMOVTrue =
2852 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2853 const ConstantSDNode *CMOVFalse =
2854 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2856 if (CMOVTrue && CMOVFalse) {
2857 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2858 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2862 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2864 False = SelectFalse;
2865 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2870 if (True.getNode() && False.getNode()) {
2871 EVT VT = Op.getValueType();
2872 SDValue ARMcc = Cond.getOperand(2);
2873 SDValue CCR = Cond.getOperand(3);
2874 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2875 assert(True.getValueType() == VT);
2876 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2881 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2882 // undefined bits before doing a full-word comparison with zero.
2883 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2884 DAG.getConstant(1, Cond.getValueType()));
2886 return DAG.getSelectCC(dl, Cond,
2887 DAG.getConstant(0, Cond.getValueType()),
2888 SelectTrue, SelectFalse, ISD::SETNE);
2891 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2892 EVT VT = Op.getValueType();
2893 SDValue LHS = Op.getOperand(0);
2894 SDValue RHS = Op.getOperand(1);
2895 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2896 SDValue TrueVal = Op.getOperand(2);
2897 SDValue FalseVal = Op.getOperand(3);
2898 DebugLoc dl = Op.getDebugLoc();
2900 if (LHS.getValueType() == MVT::i32) {
2902 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2903 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2904 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2907 ARMCC::CondCodes CondCode, CondCode2;
2908 FPCCToARMCC(CC, CondCode, CondCode2);
2910 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2911 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2912 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2913 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2915 if (CondCode2 != ARMCC::AL) {
2916 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2917 // FIXME: Needs another CMP because flag can have but one use.
2918 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2919 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2920 Result, TrueVal, ARMcc2, CCR, Cmp2);
2925 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2926 /// to morph to an integer compare sequence.
2927 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2928 const ARMSubtarget *Subtarget) {
2929 SDNode *N = Op.getNode();
2930 if (!N->hasOneUse())
2931 // Otherwise it requires moving the value from fp to integer registers.
2933 if (!N->getNumValues())
2935 EVT VT = Op.getValueType();
2936 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2937 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2938 // vmrs are very slow, e.g. cortex-a8.
2941 if (isFloatingPointZero(Op)) {
2945 return ISD::isNormalLoad(N);
2948 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2949 if (isFloatingPointZero(Op))
2950 return DAG.getConstant(0, MVT::i32);
2952 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2953 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2954 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2955 Ld->isVolatile(), Ld->isNonTemporal(),
2956 Ld->isInvariant(), Ld->getAlignment());
2958 llvm_unreachable("Unknown VFP cmp argument!");
2961 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2962 SDValue &RetVal1, SDValue &RetVal2) {
2963 if (isFloatingPointZero(Op)) {
2964 RetVal1 = DAG.getConstant(0, MVT::i32);
2965 RetVal2 = DAG.getConstant(0, MVT::i32);
2969 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2970 SDValue Ptr = Ld->getBasePtr();
2971 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2972 Ld->getChain(), Ptr,
2973 Ld->getPointerInfo(),
2974 Ld->isVolatile(), Ld->isNonTemporal(),
2975 Ld->isInvariant(), Ld->getAlignment());
2977 EVT PtrType = Ptr.getValueType();
2978 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2979 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2980 PtrType, Ptr, DAG.getConstant(4, PtrType));
2981 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2982 Ld->getChain(), NewPtr,
2983 Ld->getPointerInfo().getWithOffset(4),
2984 Ld->isVolatile(), Ld->isNonTemporal(),
2985 Ld->isInvariant(), NewAlign);
2989 llvm_unreachable("Unknown VFP cmp argument!");
2992 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2993 /// f32 and even f64 comparisons to integer ones.
2995 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2996 SDValue Chain = Op.getOperand(0);
2997 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2998 SDValue LHS = Op.getOperand(2);
2999 SDValue RHS = Op.getOperand(3);
3000 SDValue Dest = Op.getOperand(4);
3001 DebugLoc dl = Op.getDebugLoc();
3003 bool LHSSeenZero = false;
3004 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3005 bool RHSSeenZero = false;
3006 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3007 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3008 // If unsafe fp math optimization is enabled and there are no other uses of
3009 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3010 // to an integer comparison.
3011 if (CC == ISD::SETOEQ)
3013 else if (CC == ISD::SETUNE)
3016 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3018 if (LHS.getValueType() == MVT::f32) {
3019 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3020 bitcastf32Toi32(LHS, DAG), Mask);
3021 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3022 bitcastf32Toi32(RHS, DAG), Mask);
3023 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3024 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3025 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3026 Chain, Dest, ARMcc, CCR, Cmp);
3031 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3032 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3033 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3034 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3035 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3036 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3037 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3038 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3039 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3045 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3046 SDValue Chain = Op.getOperand(0);
3047 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3048 SDValue LHS = Op.getOperand(2);
3049 SDValue RHS = Op.getOperand(3);
3050 SDValue Dest = Op.getOperand(4);
3051 DebugLoc dl = Op.getDebugLoc();
3053 if (LHS.getValueType() == MVT::i32) {
3055 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3056 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3057 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3058 Chain, Dest, ARMcc, CCR, Cmp);
3061 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3063 if (getTargetMachine().Options.UnsafeFPMath &&
3064 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3065 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3066 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3067 if (Result.getNode())
3071 ARMCC::CondCodes CondCode, CondCode2;
3072 FPCCToARMCC(CC, CondCode, CondCode2);
3074 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3075 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3076 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3077 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3078 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3079 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3080 if (CondCode2 != ARMCC::AL) {
3081 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3082 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3083 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3088 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3089 SDValue Chain = Op.getOperand(0);
3090 SDValue Table = Op.getOperand(1);
3091 SDValue Index = Op.getOperand(2);
3092 DebugLoc dl = Op.getDebugLoc();
3094 EVT PTy = getPointerTy();
3095 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3096 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3097 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3098 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3099 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3100 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3101 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3102 if (Subtarget->isThumb2()) {
3103 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3104 // which does another jump to the destination. This also makes it easier
3105 // to translate it to TBB / TBH later.
3106 // FIXME: This might not work if the function is extremely large.
3107 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3108 Addr, Op.getOperand(2), JTI, UId);
3110 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3111 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3112 MachinePointerInfo::getJumpTable(),
3113 false, false, false, 0);
3114 Chain = Addr.getValue(1);
3115 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3116 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3118 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3119 MachinePointerInfo::getJumpTable(),
3120 false, false, false, 0);
3121 Chain = Addr.getValue(1);
3122 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3126 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3127 EVT VT = Op.getValueType();
3128 DebugLoc dl = Op.getDebugLoc();
3130 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3131 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3133 return DAG.UnrollVectorOp(Op.getNode());
3136 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3137 "Invalid type for custom lowering!");
3138 if (VT != MVT::v4i16)
3139 return DAG.UnrollVectorOp(Op.getNode());
3141 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3142 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3145 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3146 EVT VT = Op.getValueType();
3148 return LowerVectorFP_TO_INT(Op, DAG);
3150 DebugLoc dl = Op.getDebugLoc();
3153 switch (Op.getOpcode()) {
3154 default: llvm_unreachable("Invalid opcode!");
3155 case ISD::FP_TO_SINT:
3156 Opc = ARMISD::FTOSI;
3158 case ISD::FP_TO_UINT:
3159 Opc = ARMISD::FTOUI;
3162 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3163 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3166 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3167 EVT VT = Op.getValueType();
3168 DebugLoc dl = Op.getDebugLoc();
3170 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3171 if (VT.getVectorElementType() == MVT::f32)
3173 return DAG.UnrollVectorOp(Op.getNode());
3176 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3177 "Invalid type for custom lowering!");
3178 if (VT != MVT::v4f32)
3179 return DAG.UnrollVectorOp(Op.getNode());
3183 switch (Op.getOpcode()) {
3184 default: llvm_unreachable("Invalid opcode!");
3185 case ISD::SINT_TO_FP:
3186 CastOpc = ISD::SIGN_EXTEND;
3187 Opc = ISD::SINT_TO_FP;
3189 case ISD::UINT_TO_FP:
3190 CastOpc = ISD::ZERO_EXTEND;
3191 Opc = ISD::UINT_TO_FP;
3195 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3196 return DAG.getNode(Opc, dl, VT, Op);
3199 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3200 EVT VT = Op.getValueType();
3202 return LowerVectorINT_TO_FP(Op, DAG);
3204 DebugLoc dl = Op.getDebugLoc();
3207 switch (Op.getOpcode()) {
3208 default: llvm_unreachable("Invalid opcode!");
3209 case ISD::SINT_TO_FP:
3210 Opc = ARMISD::SITOF;
3212 case ISD::UINT_TO_FP:
3213 Opc = ARMISD::UITOF;
3217 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3218 return DAG.getNode(Opc, dl, VT, Op);
3221 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3222 // Implement fcopysign with a fabs and a conditional fneg.
3223 SDValue Tmp0 = Op.getOperand(0);
3224 SDValue Tmp1 = Op.getOperand(1);
3225 DebugLoc dl = Op.getDebugLoc();
3226 EVT VT = Op.getValueType();
3227 EVT SrcVT = Tmp1.getValueType();
3228 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3229 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3230 bool UseNEON = !InGPR && Subtarget->hasNEON();
3233 // Use VBSL to copy the sign bit.
3234 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3235 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3236 DAG.getTargetConstant(EncodedVal, MVT::i32));
3237 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3239 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3240 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3241 DAG.getConstant(32, MVT::i32));
3242 else /*if (VT == MVT::f32)*/
3243 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3244 if (SrcVT == MVT::f32) {
3245 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3247 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3248 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3249 DAG.getConstant(32, MVT::i32));
3250 } else if (VT == MVT::f32)
3251 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3252 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3253 DAG.getConstant(32, MVT::i32));
3254 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3255 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3257 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3259 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3260 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3261 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3263 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3264 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3265 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3266 if (VT == MVT::f32) {
3267 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3268 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3269 DAG.getConstant(0, MVT::i32));
3271 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3277 // Bitcast operand 1 to i32.
3278 if (SrcVT == MVT::f64)
3279 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3280 &Tmp1, 1).getValue(1);
3281 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3283 // Or in the signbit with integer operations.
3284 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3285 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3286 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3287 if (VT == MVT::f32) {
3288 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3289 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3290 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3291 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3294 // f64: Or the high part with signbit and then combine two parts.
3295 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3297 SDValue Lo = Tmp0.getValue(0);
3298 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3299 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3300 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3303 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3304 MachineFunction &MF = DAG.getMachineFunction();
3305 MachineFrameInfo *MFI = MF.getFrameInfo();
3306 MFI->setReturnAddressIsTaken(true);
3308 EVT VT = Op.getValueType();
3309 DebugLoc dl = Op.getDebugLoc();
3310 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3312 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3313 SDValue Offset = DAG.getConstant(4, MVT::i32);
3314 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3315 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3316 MachinePointerInfo(), false, false, false, 0);
3319 // Return LR, which contains the return address. Mark it an implicit live-in.
3320 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3321 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3324 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3325 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3326 MFI->setFrameAddressIsTaken(true);
3328 EVT VT = Op.getValueType();
3329 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3330 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3331 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3332 ? ARM::R7 : ARM::R11;
3333 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3335 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3336 MachinePointerInfo(),
3337 false, false, false, 0);
3341 /// ExpandBITCAST - If the target supports VFP, this function is called to
3342 /// expand a bit convert where either the source or destination type is i64 to
3343 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3344 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3345 /// vectors), since the legalizer won't know what to do with that.
3346 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348 DebugLoc dl = N->getDebugLoc();
3349 SDValue Op = N->getOperand(0);
3351 // This function is only supposed to be called for i64 types, either as the
3352 // source or destination of the bit convert.
3353 EVT SrcVT = Op.getValueType();
3354 EVT DstVT = N->getValueType(0);
3355 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3356 "ExpandBITCAST called for non-i64 type");
3358 // Turn i64->f64 into VMOVDRR.
3359 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3360 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3361 DAG.getConstant(0, MVT::i32));
3362 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3363 DAG.getConstant(1, MVT::i32));
3364 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3365 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3368 // Turn f64->i64 into VMOVRRD.
3369 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3370 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3371 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3372 // Merge the pieces into a single i64 value.
3373 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3379 /// getZeroVector - Returns a vector of specified type with all zero elements.
3380 /// Zero vectors are used to represent vector negation and in those cases
3381 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3382 /// not support i64 elements, so sometimes the zero vectors will need to be
3383 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3385 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3386 assert(VT.isVector() && "Expected a vector type");
3387 // The canonical modified immediate encoding of a zero vector is....0!
3388 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3389 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3390 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3391 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3394 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3395 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3396 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3397 SelectionDAG &DAG) const {
3398 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3399 EVT VT = Op.getValueType();
3400 unsigned VTBits = VT.getSizeInBits();
3401 DebugLoc dl = Op.getDebugLoc();
3402 SDValue ShOpLo = Op.getOperand(0);
3403 SDValue ShOpHi = Op.getOperand(1);
3404 SDValue ShAmt = Op.getOperand(2);
3406 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3408 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3410 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3411 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3412 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3413 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3414 DAG.getConstant(VTBits, MVT::i32));
3415 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3416 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3417 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3419 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3420 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3422 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3423 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3426 SDValue Ops[2] = { Lo, Hi };
3427 return DAG.getMergeValues(Ops, 2, dl);
3430 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3431 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3432 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3433 SelectionDAG &DAG) const {
3434 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3435 EVT VT = Op.getValueType();
3436 unsigned VTBits = VT.getSizeInBits();
3437 DebugLoc dl = Op.getDebugLoc();
3438 SDValue ShOpLo = Op.getOperand(0);
3439 SDValue ShOpHi = Op.getOperand(1);
3440 SDValue ShAmt = Op.getOperand(2);
3443 assert(Op.getOpcode() == ISD::SHL_PARTS);
3444 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3445 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3446 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3447 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3448 DAG.getConstant(VTBits, MVT::i32));
3449 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3450 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3452 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3453 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3454 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3456 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3457 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3460 SDValue Ops[2] = { Lo, Hi };
3461 return DAG.getMergeValues(Ops, 2, dl);
3464 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3465 SelectionDAG &DAG) const {
3466 // The rounding mode is in bits 23:22 of the FPSCR.
3467 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3468 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3469 // so that the shift + and get folded into a bitfield extract.
3470 DebugLoc dl = Op.getDebugLoc();
3471 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3472 DAG.getConstant(Intrinsic::arm_get_fpscr,
3474 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3475 DAG.getConstant(1U << 22, MVT::i32));
3476 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3477 DAG.getConstant(22, MVT::i32));
3478 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3479 DAG.getConstant(3, MVT::i32));
3482 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3483 const ARMSubtarget *ST) {
3484 EVT VT = N->getValueType(0);
3485 DebugLoc dl = N->getDebugLoc();
3487 if (!ST->hasV6T2Ops())
3490 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3491 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3494 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3495 const ARMSubtarget *ST) {
3496 EVT VT = N->getValueType(0);
3497 DebugLoc dl = N->getDebugLoc();
3502 // Lower vector shifts on NEON to use VSHL.
3503 assert(ST->hasNEON() && "unexpected vector shift");
3505 // Left shifts translate directly to the vshiftu intrinsic.
3506 if (N->getOpcode() == ISD::SHL)
3507 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3508 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3509 N->getOperand(0), N->getOperand(1));
3511 assert((N->getOpcode() == ISD::SRA ||
3512 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3514 // NEON uses the same intrinsics for both left and right shifts. For
3515 // right shifts, the shift amounts are negative, so negate the vector of
3517 EVT ShiftVT = N->getOperand(1).getValueType();
3518 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3519 getZeroVector(ShiftVT, DAG, dl),
3521 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3522 Intrinsic::arm_neon_vshifts :
3523 Intrinsic::arm_neon_vshiftu);
3524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3525 DAG.getConstant(vshiftInt, MVT::i32),
3526 N->getOperand(0), NegatedCount);
3529 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3530 const ARMSubtarget *ST) {
3531 EVT VT = N->getValueType(0);
3532 DebugLoc dl = N->getDebugLoc();
3534 // We can get here for a node like i32 = ISD::SHL i32, i64
3538 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3539 "Unknown shift to lower!");
3541 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3542 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3543 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3546 // If we are in thumb mode, we don't have RRX.
3547 if (ST->isThumb1Only()) return SDValue();
3549 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3550 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3551 DAG.getConstant(0, MVT::i32));
3552 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3553 DAG.getConstant(1, MVT::i32));
3555 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3556 // captures the result into a carry flag.
3557 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3558 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3560 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3561 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3563 // Merge the pieces into a single i64 value.
3564 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3567 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3568 SDValue TmpOp0, TmpOp1;
3569 bool Invert = false;
3573 SDValue Op0 = Op.getOperand(0);
3574 SDValue Op1 = Op.getOperand(1);
3575 SDValue CC = Op.getOperand(2);
3576 EVT VT = Op.getValueType();
3577 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3578 DebugLoc dl = Op.getDebugLoc();
3580 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3581 switch (SetCCOpcode) {
3582 default: llvm_unreachable("Illegal FP comparison");
3584 case ISD::SETNE: Invert = true; // Fallthrough
3586 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3588 case ISD::SETLT: Swap = true; // Fallthrough
3590 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3592 case ISD::SETLE: Swap = true; // Fallthrough
3594 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3595 case ISD::SETUGE: Swap = true; // Fallthrough
3596 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3597 case ISD::SETUGT: Swap = true; // Fallthrough
3598 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3599 case ISD::SETUEQ: Invert = true; // Fallthrough
3601 // Expand this to (OLT | OGT).
3605 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3606 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3608 case ISD::SETUO: Invert = true; // Fallthrough
3610 // Expand this to (OLT | OGE).
3614 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3615 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3619 // Integer comparisons.
3620 switch (SetCCOpcode) {
3621 default: llvm_unreachable("Illegal integer comparison");
3622 case ISD::SETNE: Invert = true;
3623 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3624 case ISD::SETLT: Swap = true;
3625 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3626 case ISD::SETLE: Swap = true;
3627 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3628 case ISD::SETULT: Swap = true;
3629 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3630 case ISD::SETULE: Swap = true;
3631 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3634 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3635 if (Opc == ARMISD::VCEQ) {
3638 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3640 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3643 // Ignore bitconvert.
3644 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3645 AndOp = AndOp.getOperand(0);
3647 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3649 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3650 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3657 std::swap(Op0, Op1);
3659 // If one of the operands is a constant vector zero, attempt to fold the
3660 // comparison to a specialized compare-against-zero form.
3662 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3664 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3665 if (Opc == ARMISD::VCGE)
3666 Opc = ARMISD::VCLEZ;
3667 else if (Opc == ARMISD::VCGT)
3668 Opc = ARMISD::VCLTZ;
3673 if (SingleOp.getNode()) {
3676 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3678 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3680 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3682 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3684 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3686 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3689 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3693 Result = DAG.getNOT(dl, Result, VT);
3698 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3699 /// valid vector constant for a NEON instruction with a "modified immediate"
3700 /// operand (e.g., VMOV). If so, return the encoded value.
3701 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3702 unsigned SplatBitSize, SelectionDAG &DAG,
3703 EVT &VT, bool is128Bits, NEONModImmType type) {
3704 unsigned OpCmode, Imm;
3706 // SplatBitSize is set to the smallest size that splats the vector, so a
3707 // zero vector will always have SplatBitSize == 8. However, NEON modified
3708 // immediate instructions others than VMOV do not support the 8-bit encoding
3709 // of a zero vector, and the default encoding of zero is supposed to be the
3714 switch (SplatBitSize) {
3716 if (type != VMOVModImm)
3718 // Any 1-byte value is OK. Op=0, Cmode=1110.
3719 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3722 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3726 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3727 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3728 if ((SplatBits & ~0xff) == 0) {
3729 // Value = 0x00nn: Op=x, Cmode=100x.
3734 if ((SplatBits & ~0xff00) == 0) {
3735 // Value = 0xnn00: Op=x, Cmode=101x.
3737 Imm = SplatBits >> 8;
3743 // NEON's 32-bit VMOV supports splat values where:
3744 // * only one byte is nonzero, or
3745 // * the least significant byte is 0xff and the second byte is nonzero, or
3746 // * the least significant 2 bytes are 0xff and the third is nonzero.
3747 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3748 if ((SplatBits & ~0xff) == 0) {
3749 // Value = 0x000000nn: Op=x, Cmode=000x.
3754 if ((SplatBits & ~0xff00) == 0) {
3755 // Value = 0x0000nn00: Op=x, Cmode=001x.
3757 Imm = SplatBits >> 8;
3760 if ((SplatBits & ~0xff0000) == 0) {
3761 // Value = 0x00nn0000: Op=x, Cmode=010x.
3763 Imm = SplatBits >> 16;
3766 if ((SplatBits & ~0xff000000) == 0) {
3767 // Value = 0xnn000000: Op=x, Cmode=011x.
3769 Imm = SplatBits >> 24;
3773 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3774 if (type == OtherModImm) return SDValue();
3776 if ((SplatBits & ~0xffff) == 0 &&
3777 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3778 // Value = 0x0000nnff: Op=x, Cmode=1100.
3780 Imm = SplatBits >> 8;
3785 if ((SplatBits & ~0xffffff) == 0 &&
3786 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3787 // Value = 0x00nnffff: Op=x, Cmode=1101.
3789 Imm = SplatBits >> 16;
3790 SplatBits |= 0xffff;
3794 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3795 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3796 // VMOV.I32. A (very) minor optimization would be to replicate the value
3797 // and fall through here to test for a valid 64-bit splat. But, then the
3798 // caller would also need to check and handle the change in size.
3802 if (type != VMOVModImm)
3804 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3805 uint64_t BitMask = 0xff;
3807 unsigned ImmMask = 1;
3809 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3810 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3813 } else if ((SplatBits & BitMask) != 0) {
3819 // Op=1, Cmode=1110.
3822 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3827 llvm_unreachable("unexpected size for isNEONModifiedImm");
3830 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3831 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3834 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3835 const ARMSubtarget *ST) const {
3836 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3839 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3840 assert(Op.getValueType() == MVT::f32 &&
3841 "ConstantFP custom lowering should only occur for f32.");
3843 // Try splatting with a VMOV.f32...
3844 APFloat FPVal = CFP->getValueAPF();
3845 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3847 DebugLoc DL = Op.getDebugLoc();
3848 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3849 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3851 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3852 DAG.getConstant(0, MVT::i32));
3855 // If that fails, try a VMOV.i32
3857 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3858 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3860 if (NewVal != SDValue()) {
3861 DebugLoc DL = Op.getDebugLoc();
3862 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3864 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3867 DAG.getConstant(0, MVT::i32));
3870 // Finally, try a VMVN.i32
3871 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3873 if (NewVal != SDValue()) {
3874 DebugLoc DL = Op.getDebugLoc();
3875 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3876 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3879 DAG.getConstant(0, MVT::i32));
3886 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3887 bool &ReverseVEXT, unsigned &Imm) {
3888 unsigned NumElts = VT.getVectorNumElements();
3889 ReverseVEXT = false;
3891 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3897 // If this is a VEXT shuffle, the immediate value is the index of the first
3898 // element. The other shuffle indices must be the successive elements after
3900 unsigned ExpectedElt = Imm;
3901 for (unsigned i = 1; i < NumElts; ++i) {
3902 // Increment the expected index. If it wraps around, it may still be
3903 // a VEXT but the source vectors must be swapped.
3905 if (ExpectedElt == NumElts * 2) {
3910 if (M[i] < 0) continue; // ignore UNDEF indices
3911 if (ExpectedElt != static_cast<unsigned>(M[i]))
3915 // Adjust the index value if the source operands will be swapped.
3922 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3923 /// instruction with the specified blocksize. (The order of the elements
3924 /// within each block of the vector is reversed.)
3925 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3926 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3927 "Only possible block sizes for VREV are: 16, 32, 64");
3929 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3933 unsigned NumElts = VT.getVectorNumElements();
3934 unsigned BlockElts = M[0] + 1;
3935 // If the first shuffle index is UNDEF, be optimistic.
3937 BlockElts = BlockSize / EltSz;
3939 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3942 for (unsigned i = 0; i < NumElts; ++i) {
3943 if (M[i] < 0) continue; // ignore UNDEF indices
3944 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3951 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3952 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3953 // range, then 0 is placed into the resulting vector. So pretty much any mask
3954 // of 8 elements can work here.
3955 return VT == MVT::v8i8 && M.size() == 8;
3958 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3959 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3963 unsigned NumElts = VT.getVectorNumElements();
3964 WhichResult = (M[0] == 0 ? 0 : 1);
3965 for (unsigned i = 0; i < NumElts; i += 2) {
3966 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3967 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3973 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3974 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3975 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3976 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3977 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3981 unsigned NumElts = VT.getVectorNumElements();
3982 WhichResult = (M[0] == 0 ? 0 : 1);
3983 for (unsigned i = 0; i < NumElts; i += 2) {
3984 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3985 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3991 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3992 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3996 unsigned NumElts = VT.getVectorNumElements();
3997 WhichResult = (M[0] == 0 ? 0 : 1);
3998 for (unsigned i = 0; i != NumElts; ++i) {
3999 if (M[i] < 0) continue; // ignore UNDEF indices
4000 if ((unsigned) M[i] != 2 * i + WhichResult)
4004 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4005 if (VT.is64BitVector() && EltSz == 32)
4011 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4012 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4013 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4014 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4015 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4019 unsigned Half = VT.getVectorNumElements() / 2;
4020 WhichResult = (M[0] == 0 ? 0 : 1);
4021 for (unsigned j = 0; j != 2; ++j) {
4022 unsigned Idx = WhichResult;
4023 for (unsigned i = 0; i != Half; ++i) {
4024 int MIdx = M[i + j * Half];
4025 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4031 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4032 if (VT.is64BitVector() && EltSz == 32)
4038 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4039 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4043 unsigned NumElts = VT.getVectorNumElements();
4044 WhichResult = (M[0] == 0 ? 0 : 1);
4045 unsigned Idx = WhichResult * NumElts / 2;
4046 for (unsigned i = 0; i != NumElts; i += 2) {
4047 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4048 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4053 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4054 if (VT.is64BitVector() && EltSz == 32)
4060 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4062 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4063 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4064 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4068 unsigned NumElts = VT.getVectorNumElements();
4069 WhichResult = (M[0] == 0 ? 0 : 1);
4070 unsigned Idx = WhichResult * NumElts / 2;
4071 for (unsigned i = 0; i != NumElts; i += 2) {
4072 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4073 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4078 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4079 if (VT.is64BitVector() && EltSz == 32)
4085 // If N is an integer constant that can be moved into a register in one
4086 // instruction, return an SDValue of such a constant (will become a MOV
4087 // instruction). Otherwise return null.
4088 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4089 const ARMSubtarget *ST, DebugLoc dl) {
4091 if (!isa<ConstantSDNode>(N))
4093 Val = cast<ConstantSDNode>(N)->getZExtValue();
4095 if (ST->isThumb1Only()) {
4096 if (Val <= 255 || ~Val <= 255)
4097 return DAG.getConstant(Val, MVT::i32);
4099 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4100 return DAG.getConstant(Val, MVT::i32);
4105 // If this is a case we can't handle, return null and let the default
4106 // expansion code take care of it.
4107 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4108 const ARMSubtarget *ST) const {
4109 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4110 DebugLoc dl = Op.getDebugLoc();
4111 EVT VT = Op.getValueType();
4113 APInt SplatBits, SplatUndef;
4114 unsigned SplatBitSize;
4116 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4117 if (SplatBitSize <= 64) {
4118 // Check if an immediate VMOV works.
4120 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4121 SplatUndef.getZExtValue(), SplatBitSize,
4122 DAG, VmovVT, VT.is128BitVector(),
4124 if (Val.getNode()) {
4125 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4126 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4129 // Try an immediate VMVN.
4130 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4131 Val = isNEONModifiedImm(NegatedImm,
4132 SplatUndef.getZExtValue(), SplatBitSize,
4133 DAG, VmovVT, VT.is128BitVector(),
4135 if (Val.getNode()) {
4136 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4137 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4140 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4141 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4142 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4144 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4145 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4151 // Scan through the operands to see if only one value is used.
4152 unsigned NumElts = VT.getVectorNumElements();
4153 bool isOnlyLowElement = true;
4154 bool usesOnlyOneValue = true;
4155 bool isConstant = true;
4157 for (unsigned i = 0; i < NumElts; ++i) {
4158 SDValue V = Op.getOperand(i);
4159 if (V.getOpcode() == ISD::UNDEF)
4162 isOnlyLowElement = false;
4163 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4166 if (!Value.getNode())
4168 else if (V != Value)
4169 usesOnlyOneValue = false;
4172 if (!Value.getNode())
4173 return DAG.getUNDEF(VT);
4175 if (isOnlyLowElement)
4176 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4178 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4180 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4181 // i32 and try again.
4182 if (usesOnlyOneValue && EltSize <= 32) {
4184 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4185 if (VT.getVectorElementType().isFloatingPoint()) {
4186 SmallVector<SDValue, 8> Ops;
4187 for (unsigned i = 0; i < NumElts; ++i)
4188 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4190 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4191 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4192 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4194 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4196 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4198 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4201 // If all elements are constants and the case above didn't get hit, fall back
4202 // to the default expansion, which will generate a load from the constant
4207 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4209 SDValue shuffle = ReconstructShuffle(Op, DAG);
4210 if (shuffle != SDValue())
4214 // Vectors with 32- or 64-bit elements can be built by directly assigning
4215 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4216 // will be legalized.
4217 if (EltSize >= 32) {
4218 // Do the expansion with floating-point types, since that is what the VFP
4219 // registers are defined to use, and since i64 is not legal.
4220 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4221 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4222 SmallVector<SDValue, 8> Ops;
4223 for (unsigned i = 0; i < NumElts; ++i)
4224 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4225 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4226 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4232 // Gather data to see if the operation can be modelled as a
4233 // shuffle in combination with VEXTs.
4234 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4235 SelectionDAG &DAG) const {
4236 DebugLoc dl = Op.getDebugLoc();
4237 EVT VT = Op.getValueType();
4238 unsigned NumElts = VT.getVectorNumElements();
4240 SmallVector<SDValue, 2> SourceVecs;
4241 SmallVector<unsigned, 2> MinElts;
4242 SmallVector<unsigned, 2> MaxElts;
4244 for (unsigned i = 0; i < NumElts; ++i) {
4245 SDValue V = Op.getOperand(i);
4246 if (V.getOpcode() == ISD::UNDEF)
4248 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4249 // A shuffle can only come from building a vector from various
4250 // elements of other vectors.
4252 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4253 VT.getVectorElementType()) {
4254 // This code doesn't know how to handle shuffles where the vector
4255 // element types do not match (this happens because type legalization
4256 // promotes the return type of EXTRACT_VECTOR_ELT).
4257 // FIXME: It might be appropriate to extend this code to handle
4258 // mismatched types.
4262 // Record this extraction against the appropriate vector if possible...
4263 SDValue SourceVec = V.getOperand(0);
4264 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4265 bool FoundSource = false;
4266 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4267 if (SourceVecs[j] == SourceVec) {
4268 if (MinElts[j] > EltNo)
4270 if (MaxElts[j] < EltNo)
4277 // Or record a new source if not...
4279 SourceVecs.push_back(SourceVec);
4280 MinElts.push_back(EltNo);
4281 MaxElts.push_back(EltNo);
4285 // Currently only do something sane when at most two source vectors
4287 if (SourceVecs.size() > 2)
4290 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4291 int VEXTOffsets[2] = {0, 0};
4293 // This loop extracts the usage patterns of the source vectors
4294 // and prepares appropriate SDValues for a shuffle if possible.
4295 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4296 if (SourceVecs[i].getValueType() == VT) {
4297 // No VEXT necessary
4298 ShuffleSrcs[i] = SourceVecs[i];
4301 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4302 // It probably isn't worth padding out a smaller vector just to
4303 // break it down again in a shuffle.
4307 // Since only 64-bit and 128-bit vectors are legal on ARM and
4308 // we've eliminated the other cases...
4309 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4310 "unexpected vector sizes in ReconstructShuffle");
4312 if (MaxElts[i] - MinElts[i] >= NumElts) {
4313 // Span too large for a VEXT to cope
4317 if (MinElts[i] >= NumElts) {
4318 // The extraction can just take the second half
4319 VEXTOffsets[i] = NumElts;
4320 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4322 DAG.getIntPtrConstant(NumElts));
4323 } else if (MaxElts[i] < NumElts) {
4324 // The extraction can just take the first half
4326 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4328 DAG.getIntPtrConstant(0));
4330 // An actual VEXT is needed
4331 VEXTOffsets[i] = MinElts[i];
4332 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4334 DAG.getIntPtrConstant(0));
4335 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4337 DAG.getIntPtrConstant(NumElts));
4338 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4339 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4343 SmallVector<int, 8> Mask;
4345 for (unsigned i = 0; i < NumElts; ++i) {
4346 SDValue Entry = Op.getOperand(i);
4347 if (Entry.getOpcode() == ISD::UNDEF) {
4352 SDValue ExtractVec = Entry.getOperand(0);
4353 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4354 .getOperand(1))->getSExtValue();
4355 if (ExtractVec == SourceVecs[0]) {
4356 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4358 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4362 // Final check before we try to produce nonsense...
4363 if (isShuffleMaskLegal(Mask, VT))
4364 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4370 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4371 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4372 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4373 /// are assumed to be legal.
4375 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4377 if (VT.getVectorNumElements() == 4 &&
4378 (VT.is128BitVector() || VT.is64BitVector())) {
4379 unsigned PFIndexes[4];
4380 for (unsigned i = 0; i != 4; ++i) {
4384 PFIndexes[i] = M[i];
4387 // Compute the index in the perfect shuffle table.
4388 unsigned PFTableIndex =
4389 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4390 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4391 unsigned Cost = (PFEntry >> 30);
4398 unsigned Imm, WhichResult;
4400 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4401 return (EltSize >= 32 ||
4402 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4403 isVREVMask(M, VT, 64) ||
4404 isVREVMask(M, VT, 32) ||
4405 isVREVMask(M, VT, 16) ||
4406 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4407 isVTBLMask(M, VT) ||
4408 isVTRNMask(M, VT, WhichResult) ||
4409 isVUZPMask(M, VT, WhichResult) ||
4410 isVZIPMask(M, VT, WhichResult) ||
4411 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4412 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4413 isVZIP_v_undef_Mask(M, VT, WhichResult));
4416 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4417 /// the specified operations to build the shuffle.
4418 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4419 SDValue RHS, SelectionDAG &DAG,
4421 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4422 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4423 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4426 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4435 OP_VUZPL, // VUZP, left result
4436 OP_VUZPR, // VUZP, right result
4437 OP_VZIPL, // VZIP, left result
4438 OP_VZIPR, // VZIP, right result
4439 OP_VTRNL, // VTRN, left result
4440 OP_VTRNR // VTRN, right result
4443 if (OpNum == OP_COPY) {
4444 if (LHSID == (1*9+2)*9+3) return LHS;
4445 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4449 SDValue OpLHS, OpRHS;
4450 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4451 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4452 EVT VT = OpLHS.getValueType();
4455 default: llvm_unreachable("Unknown shuffle opcode!");
4457 // VREV divides the vector in half and swaps within the half.
4458 if (VT.getVectorElementType() == MVT::i32 ||
4459 VT.getVectorElementType() == MVT::f32)
4460 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4461 // vrev <4 x i16> -> VREV32
4462 if (VT.getVectorElementType() == MVT::i16)
4463 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4464 // vrev <4 x i8> -> VREV16
4465 assert(VT.getVectorElementType() == MVT::i8);
4466 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4471 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4472 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4476 return DAG.getNode(ARMISD::VEXT, dl, VT,
4478 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4481 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4482 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4485 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4486 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4489 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4490 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4494 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4495 ArrayRef<int> ShuffleMask,
4496 SelectionDAG &DAG) {
4497 // Check to see if we can use the VTBL instruction.
4498 SDValue V1 = Op.getOperand(0);
4499 SDValue V2 = Op.getOperand(1);
4500 DebugLoc DL = Op.getDebugLoc();
4502 SmallVector<SDValue, 8> VTBLMask;
4503 for (ArrayRef<int>::iterator
4504 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4505 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4507 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4508 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4509 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4512 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4513 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4517 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4518 SDValue V1 = Op.getOperand(0);
4519 SDValue V2 = Op.getOperand(1);
4520 DebugLoc dl = Op.getDebugLoc();
4521 EVT VT = Op.getValueType();
4522 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4524 // Convert shuffles that are directly supported on NEON to target-specific
4525 // DAG nodes, instead of keeping them as shuffles and matching them again
4526 // during code selection. This is more efficient and avoids the possibility
4527 // of inconsistencies between legalization and selection.
4528 // FIXME: floating-point vectors should be canonicalized to integer vectors
4529 // of the same time so that they get CSEd properly.
4530 ArrayRef<int> ShuffleMask = SVN->getMask();
4532 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4533 if (EltSize <= 32) {
4534 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4535 int Lane = SVN->getSplatIndex();
4536 // If this is undef splat, generate it via "just" vdup, if possible.
4537 if (Lane == -1) Lane = 0;
4539 // Test if V1 is a SCALAR_TO_VECTOR.
4540 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4541 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4543 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4544 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4546 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4547 !isa<ConstantSDNode>(V1.getOperand(0))) {
4548 bool IsScalarToVector = true;
4549 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4550 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4551 IsScalarToVector = false;
4554 if (IsScalarToVector)
4555 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4557 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4558 DAG.getConstant(Lane, MVT::i32));
4563 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4566 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4567 DAG.getConstant(Imm, MVT::i32));
4570 if (isVREVMask(ShuffleMask, VT, 64))
4571 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4572 if (isVREVMask(ShuffleMask, VT, 32))
4573 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4574 if (isVREVMask(ShuffleMask, VT, 16))
4575 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4577 // Check for Neon shuffles that modify both input vectors in place.
4578 // If both results are used, i.e., if there are two shuffles with the same
4579 // source operands and with masks corresponding to both results of one of
4580 // these operations, DAG memoization will ensure that a single node is
4581 // used for both shuffles.
4582 unsigned WhichResult;
4583 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4584 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4585 V1, V2).getValue(WhichResult);
4586 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4587 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4588 V1, V2).getValue(WhichResult);
4589 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4590 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4591 V1, V2).getValue(WhichResult);
4593 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4594 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4595 V1, V1).getValue(WhichResult);
4596 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4597 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4598 V1, V1).getValue(WhichResult);
4599 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4600 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4601 V1, V1).getValue(WhichResult);
4604 // If the shuffle is not directly supported and it has 4 elements, use
4605 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4606 unsigned NumElts = VT.getVectorNumElements();
4608 unsigned PFIndexes[4];
4609 for (unsigned i = 0; i != 4; ++i) {
4610 if (ShuffleMask[i] < 0)
4613 PFIndexes[i] = ShuffleMask[i];
4616 // Compute the index in the perfect shuffle table.
4617 unsigned PFTableIndex =
4618 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4619 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4620 unsigned Cost = (PFEntry >> 30);
4623 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4626 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4627 if (EltSize >= 32) {
4628 // Do the expansion with floating-point types, since that is what the VFP
4629 // registers are defined to use, and since i64 is not legal.
4630 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4631 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4632 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4633 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4634 SmallVector<SDValue, 8> Ops;
4635 for (unsigned i = 0; i < NumElts; ++i) {
4636 if (ShuffleMask[i] < 0)
4637 Ops.push_back(DAG.getUNDEF(EltVT));
4639 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4640 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4641 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4644 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4645 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4648 if (VT == MVT::v8i8) {
4649 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4650 if (NewOp.getNode())
4657 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4658 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4659 SDValue Lane = Op.getOperand(2);
4660 if (!isa<ConstantSDNode>(Lane))
4666 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4667 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4668 SDValue Lane = Op.getOperand(1);
4669 if (!isa<ConstantSDNode>(Lane))
4672 SDValue Vec = Op.getOperand(0);
4673 if (Op.getValueType() == MVT::i32 &&
4674 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4675 DebugLoc dl = Op.getDebugLoc();
4676 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4682 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4683 // The only time a CONCAT_VECTORS operation can have legal types is when
4684 // two 64-bit vectors are concatenated to a 128-bit vector.
4685 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4686 "unexpected CONCAT_VECTORS");
4687 DebugLoc dl = Op.getDebugLoc();
4688 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4689 SDValue Op0 = Op.getOperand(0);
4690 SDValue Op1 = Op.getOperand(1);
4691 if (Op0.getOpcode() != ISD::UNDEF)
4692 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4693 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4694 DAG.getIntPtrConstant(0));
4695 if (Op1.getOpcode() != ISD::UNDEF)
4696 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4697 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4698 DAG.getIntPtrConstant(1));
4699 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4702 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4703 /// element has been zero/sign-extended, depending on the isSigned parameter,
4704 /// from an integer type half its size.
4705 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4707 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4708 EVT VT = N->getValueType(0);
4709 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4710 SDNode *BVN = N->getOperand(0).getNode();
4711 if (BVN->getValueType(0) != MVT::v4i32 ||
4712 BVN->getOpcode() != ISD::BUILD_VECTOR)
4714 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4715 unsigned HiElt = 1 - LoElt;
4716 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4717 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4718 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4719 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4720 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4723 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4724 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4727 if (Hi0->isNullValue() && Hi1->isNullValue())
4733 if (N->getOpcode() != ISD::BUILD_VECTOR)
4736 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4737 SDNode *Elt = N->getOperand(i).getNode();
4738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4739 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4740 unsigned HalfSize = EltSize / 2;
4742 if (!isIntN(HalfSize, C->getSExtValue()))
4745 if (!isUIntN(HalfSize, C->getZExtValue()))
4756 /// isSignExtended - Check if a node is a vector value that is sign-extended
4757 /// or a constant BUILD_VECTOR with sign-extended elements.
4758 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4759 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4761 if (isExtendedBUILD_VECTOR(N, DAG, true))
4766 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4767 /// or a constant BUILD_VECTOR with zero-extended elements.
4768 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4769 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4771 if (isExtendedBUILD_VECTOR(N, DAG, false))
4776 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4777 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4778 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4779 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4780 return N->getOperand(0);
4781 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4782 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4783 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4784 LD->isNonTemporal(), LD->isInvariant(),
4785 LD->getAlignment());
4786 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4787 // have been legalized as a BITCAST from v4i32.
4788 if (N->getOpcode() == ISD::BITCAST) {
4789 SDNode *BVN = N->getOperand(0).getNode();
4790 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4791 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4792 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4793 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4794 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4796 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4797 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4798 EVT VT = N->getValueType(0);
4799 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4800 unsigned NumElts = VT.getVectorNumElements();
4801 MVT TruncVT = MVT::getIntegerVT(EltSize);
4802 SmallVector<SDValue, 8> Ops;
4803 for (unsigned i = 0; i != NumElts; ++i) {
4804 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4805 const APInt &CInt = C->getAPIntValue();
4806 // Element types smaller than 32 bits are not legal, so use i32 elements.
4807 // The values are implicitly truncated so sext vs. zext doesn't matter.
4808 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4810 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4811 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4814 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4815 unsigned Opcode = N->getOpcode();
4816 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4817 SDNode *N0 = N->getOperand(0).getNode();
4818 SDNode *N1 = N->getOperand(1).getNode();
4819 return N0->hasOneUse() && N1->hasOneUse() &&
4820 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4825 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4826 unsigned Opcode = N->getOpcode();
4827 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4828 SDNode *N0 = N->getOperand(0).getNode();
4829 SDNode *N1 = N->getOperand(1).getNode();
4830 return N0->hasOneUse() && N1->hasOneUse() &&
4831 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4836 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4837 // Multiplications are only custom-lowered for 128-bit vectors so that
4838 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4839 EVT VT = Op.getValueType();
4840 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4841 SDNode *N0 = Op.getOperand(0).getNode();
4842 SDNode *N1 = Op.getOperand(1).getNode();
4843 unsigned NewOpc = 0;
4845 bool isN0SExt = isSignExtended(N0, DAG);
4846 bool isN1SExt = isSignExtended(N1, DAG);
4847 if (isN0SExt && isN1SExt)
4848 NewOpc = ARMISD::VMULLs;
4850 bool isN0ZExt = isZeroExtended(N0, DAG);
4851 bool isN1ZExt = isZeroExtended(N1, DAG);
4852 if (isN0ZExt && isN1ZExt)
4853 NewOpc = ARMISD::VMULLu;
4854 else if (isN1SExt || isN1ZExt) {
4855 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4856 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4857 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4858 NewOpc = ARMISD::VMULLs;
4860 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4861 NewOpc = ARMISD::VMULLu;
4863 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4865 NewOpc = ARMISD::VMULLu;
4871 if (VT == MVT::v2i64)
4872 // Fall through to expand this. It is not legal.
4875 // Other vector multiplications are legal.
4880 // Legalize to a VMULL instruction.
4881 DebugLoc DL = Op.getDebugLoc();
4883 SDValue Op1 = SkipExtension(N1, DAG);
4885 Op0 = SkipExtension(N0, DAG);
4886 assert(Op0.getValueType().is64BitVector() &&
4887 Op1.getValueType().is64BitVector() &&
4888 "unexpected types for extended operands to VMULL");
4889 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4892 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4893 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4900 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4901 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4902 EVT Op1VT = Op1.getValueType();
4903 return DAG.getNode(N0->getOpcode(), DL, VT,
4904 DAG.getNode(NewOpc, DL, VT,
4905 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4906 DAG.getNode(NewOpc, DL, VT,
4907 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4911 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4913 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4914 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4915 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4916 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4917 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4918 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4919 // Get reciprocal estimate.
4920 // float4 recip = vrecpeq_f32(yf);
4921 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4922 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4923 // Because char has a smaller range than uchar, we can actually get away
4924 // without any newton steps. This requires that we use a weird bias
4925 // of 0xb000, however (again, this has been exhaustively tested).
4926 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4927 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4928 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4929 Y = DAG.getConstant(0xb000, MVT::i32);
4930 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4931 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4932 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4933 // Convert back to short.
4934 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4935 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4940 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4942 // Convert to float.
4943 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4944 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4945 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4946 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4947 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4948 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4950 // Use reciprocal estimate and one refinement step.
4951 // float4 recip = vrecpeq_f32(yf);
4952 // recip *= vrecpsq_f32(yf, recip);
4953 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4954 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4955 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4956 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4958 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4959 // Because short has a smaller range than ushort, we can actually get away
4960 // with only a single newton step. This requires that we use a weird bias
4961 // of 89, however (again, this has been exhaustively tested).
4962 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4963 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4964 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4965 N1 = DAG.getConstant(0x89, MVT::i32);
4966 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4967 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4968 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4969 // Convert back to integer and return.
4970 // return vmovn_s32(vcvt_s32_f32(result));
4971 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4972 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4976 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4977 EVT VT = Op.getValueType();
4978 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4979 "unexpected type for custom-lowering ISD::SDIV");
4981 DebugLoc dl = Op.getDebugLoc();
4982 SDValue N0 = Op.getOperand(0);
4983 SDValue N1 = Op.getOperand(1);
4986 if (VT == MVT::v8i8) {
4987 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4988 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4990 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4991 DAG.getIntPtrConstant(4));
4992 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4993 DAG.getIntPtrConstant(4));
4994 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4995 DAG.getIntPtrConstant(0));
4996 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4997 DAG.getIntPtrConstant(0));
4999 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5000 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5002 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5003 N0 = LowerCONCAT_VECTORS(N0, DAG);
5005 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5008 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5011 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5012 EVT VT = Op.getValueType();
5013 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5014 "unexpected type for custom-lowering ISD::UDIV");
5016 DebugLoc dl = Op.getDebugLoc();
5017 SDValue N0 = Op.getOperand(0);
5018 SDValue N1 = Op.getOperand(1);
5021 if (VT == MVT::v8i8) {
5022 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5023 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5025 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5026 DAG.getIntPtrConstant(4));
5027 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5028 DAG.getIntPtrConstant(4));
5029 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5030 DAG.getIntPtrConstant(0));
5031 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5032 DAG.getIntPtrConstant(0));
5034 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5035 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5037 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5038 N0 = LowerCONCAT_VECTORS(N0, DAG);
5040 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5041 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5046 // v4i16 sdiv ... Convert to float.
5047 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5048 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5049 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5050 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5051 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5052 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5054 // Use reciprocal estimate and two refinement steps.
5055 // float4 recip = vrecpeq_f32(yf);
5056 // recip *= vrecpsq_f32(yf, recip);
5057 // recip *= vrecpsq_f32(yf, recip);
5058 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5059 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5060 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5061 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5063 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5064 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5065 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5067 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5068 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5069 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5070 // and that it will never cause us to return an answer too large).
5071 // float4 result = as_float4(as_int4(xf*recip) + 2);
5072 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5073 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5074 N1 = DAG.getConstant(2, MVT::i32);
5075 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5076 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5077 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5078 // Convert back to integer and return.
5079 // return vmovn_u32(vcvt_s32_f32(result));
5080 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5081 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5085 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5086 EVT VT = Op.getNode()->getValueType(0);
5087 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5090 bool ExtraOp = false;
5091 switch (Op.getOpcode()) {
5092 default: llvm_unreachable("Invalid code");
5093 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5094 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5095 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5096 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5100 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5102 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5103 Op.getOperand(1), Op.getOperand(2));
5106 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5107 // Monotonic load/store is legal for all targets
5108 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5111 // Aquire/Release load/store is not legal for targets without a
5112 // dmb or equivalent available.
5118 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5119 SelectionDAG &DAG, unsigned NewOp) {
5120 DebugLoc dl = Node->getDebugLoc();
5121 assert (Node->getValueType(0) == MVT::i64 &&
5122 "Only know how to expand i64 atomics");
5124 SmallVector<SDValue, 6> Ops;
5125 Ops.push_back(Node->getOperand(0)); // Chain
5126 Ops.push_back(Node->getOperand(1)); // Ptr
5128 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5129 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5130 // High part of Val1
5131 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5132 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5133 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5134 // High part of Val1
5135 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5136 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5137 // High part of Val2
5138 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5139 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5141 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5143 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5144 cast<MemSDNode>(Node)->getMemOperand());
5145 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5146 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5147 Results.push_back(Result.getValue(2));
5150 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5151 switch (Op.getOpcode()) {
5152 default: llvm_unreachable("Don't know how to custom lower this!");
5153 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5154 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5155 case ISD::GlobalAddress:
5156 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5157 LowerGlobalAddressELF(Op, DAG);
5158 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5159 case ISD::SELECT: return LowerSELECT(Op, DAG);
5160 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5161 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5162 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5163 case ISD::VASTART: return LowerVASTART(Op, DAG);
5164 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5165 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5166 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5167 case ISD::SINT_TO_FP:
5168 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5169 case ISD::FP_TO_SINT:
5170 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5171 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5172 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5173 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5174 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5175 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5176 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5177 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5179 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5182 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5183 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5184 case ISD::SRL_PARTS:
5185 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5186 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5187 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5188 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5189 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5190 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5191 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5192 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5193 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5194 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5195 case ISD::MUL: return LowerMUL(Op, DAG);
5196 case ISD::SDIV: return LowerSDIV(Op, DAG);
5197 case ISD::UDIV: return LowerUDIV(Op, DAG);
5201 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5202 case ISD::ATOMIC_LOAD:
5203 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5207 /// ReplaceNodeResults - Replace the results of node with an illegal result
5208 /// type with new values built out of custom code.
5209 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5210 SmallVectorImpl<SDValue>&Results,
5211 SelectionDAG &DAG) const {
5213 switch (N->getOpcode()) {
5215 llvm_unreachable("Don't know how to custom expand this!");
5217 Res = ExpandBITCAST(N, DAG);
5221 Res = Expand64BitShift(N, DAG, Subtarget);
5223 case ISD::ATOMIC_LOAD_ADD:
5224 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5226 case ISD::ATOMIC_LOAD_AND:
5227 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5229 case ISD::ATOMIC_LOAD_NAND:
5230 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5232 case ISD::ATOMIC_LOAD_OR:
5233 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5235 case ISD::ATOMIC_LOAD_SUB:
5236 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5238 case ISD::ATOMIC_LOAD_XOR:
5239 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5241 case ISD::ATOMIC_SWAP:
5242 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5244 case ISD::ATOMIC_CMP_SWAP:
5245 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5249 Results.push_back(Res);
5252 //===----------------------------------------------------------------------===//
5253 // ARM Scheduler Hooks
5254 //===----------------------------------------------------------------------===//
5257 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5258 MachineBasicBlock *BB,
5259 unsigned Size) const {
5260 unsigned dest = MI->getOperand(0).getReg();
5261 unsigned ptr = MI->getOperand(1).getReg();
5262 unsigned oldval = MI->getOperand(2).getReg();
5263 unsigned newval = MI->getOperand(3).getReg();
5264 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5265 DebugLoc dl = MI->getDebugLoc();
5266 bool isThumb2 = Subtarget->isThumb2();
5268 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5269 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5270 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5271 (const TargetRegisterClass*)&ARM::GPRRegClass);
5274 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5275 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5276 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5279 unsigned ldrOpc, strOpc;
5281 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5283 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5284 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5287 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5288 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5291 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5292 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5296 MachineFunction *MF = BB->getParent();
5297 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5298 MachineFunction::iterator It = BB;
5299 ++It; // insert the new blocks after the current block
5301 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5302 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5303 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5304 MF->insert(It, loop1MBB);
5305 MF->insert(It, loop2MBB);
5306 MF->insert(It, exitMBB);
5308 // Transfer the remainder of BB and its successor edges to exitMBB.
5309 exitMBB->splice(exitMBB->begin(), BB,
5310 llvm::next(MachineBasicBlock::iterator(MI)),
5312 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5316 // fallthrough --> loop1MBB
5317 BB->addSuccessor(loop1MBB);
5320 // ldrex dest, [ptr]
5324 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5325 if (ldrOpc == ARM::t2LDREX)
5327 AddDefaultPred(MIB);
5328 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5329 .addReg(dest).addReg(oldval));
5330 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5331 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5332 BB->addSuccessor(loop2MBB);
5333 BB->addSuccessor(exitMBB);
5336 // strex scratch, newval, [ptr]
5340 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5341 if (strOpc == ARM::t2STREX)
5343 AddDefaultPred(MIB);
5344 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5345 .addReg(scratch).addImm(0));
5346 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5347 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5348 BB->addSuccessor(loop1MBB);
5349 BB->addSuccessor(exitMBB);
5355 MI->eraseFromParent(); // The instruction is gone now.
5361 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5362 unsigned Size, unsigned BinOpcode) const {
5363 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5364 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5366 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5367 MachineFunction *MF = BB->getParent();
5368 MachineFunction::iterator It = BB;
5371 unsigned dest = MI->getOperand(0).getReg();
5372 unsigned ptr = MI->getOperand(1).getReg();
5373 unsigned incr = MI->getOperand(2).getReg();
5374 DebugLoc dl = MI->getDebugLoc();
5375 bool isThumb2 = Subtarget->isThumb2();
5377 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5379 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5380 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5383 unsigned ldrOpc, strOpc;
5385 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5387 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5388 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5391 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5392 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5395 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5396 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5400 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5401 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5402 MF->insert(It, loopMBB);
5403 MF->insert(It, exitMBB);
5405 // Transfer the remainder of BB and its successor edges to exitMBB.
5406 exitMBB->splice(exitMBB->begin(), BB,
5407 llvm::next(MachineBasicBlock::iterator(MI)),
5409 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5411 const TargetRegisterClass *TRC = isThumb2 ?
5412 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5413 (const TargetRegisterClass*)&ARM::GPRRegClass;
5414 unsigned scratch = MRI.createVirtualRegister(TRC);
5415 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5419 // fallthrough --> loopMBB
5420 BB->addSuccessor(loopMBB);
5424 // <binop> scratch2, dest, incr
5425 // strex scratch, scratch2, ptr
5428 // fallthrough --> exitMBB
5430 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5431 if (ldrOpc == ARM::t2LDREX)
5433 AddDefaultPred(MIB);
5435 // operand order needs to go the other way for NAND
5436 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5437 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5438 addReg(incr).addReg(dest)).addReg(0);
5440 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5441 addReg(dest).addReg(incr)).addReg(0);
5444 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5445 if (strOpc == ARM::t2STREX)
5447 AddDefaultPred(MIB);
5448 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5449 .addReg(scratch).addImm(0));
5450 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5451 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5453 BB->addSuccessor(loopMBB);
5454 BB->addSuccessor(exitMBB);
5460 MI->eraseFromParent(); // The instruction is gone now.
5466 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5467 MachineBasicBlock *BB,
5470 ARMCC::CondCodes Cond) const {
5471 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5473 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5474 MachineFunction *MF = BB->getParent();
5475 MachineFunction::iterator It = BB;
5478 unsigned dest = MI->getOperand(0).getReg();
5479 unsigned ptr = MI->getOperand(1).getReg();
5480 unsigned incr = MI->getOperand(2).getReg();
5481 unsigned oldval = dest;
5482 DebugLoc dl = MI->getDebugLoc();
5483 bool isThumb2 = Subtarget->isThumb2();
5485 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5487 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5488 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5491 unsigned ldrOpc, strOpc, extendOpc;
5493 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5495 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5496 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5497 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5500 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5501 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5502 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5505 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5506 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5511 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5512 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5513 MF->insert(It, loopMBB);
5514 MF->insert(It, exitMBB);
5516 // Transfer the remainder of BB and its successor edges to exitMBB.
5517 exitMBB->splice(exitMBB->begin(), BB,
5518 llvm::next(MachineBasicBlock::iterator(MI)),
5520 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5522 const TargetRegisterClass *TRC = isThumb2 ?
5523 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5524 (const TargetRegisterClass*)&ARM::GPRRegClass;
5525 unsigned scratch = MRI.createVirtualRegister(TRC);
5526 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5530 // fallthrough --> loopMBB
5531 BB->addSuccessor(loopMBB);
5535 // (sign extend dest, if required)
5537 // cmov.cond scratch2, dest, incr
5538 // strex scratch, scratch2, ptr
5541 // fallthrough --> exitMBB
5543 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5544 if (ldrOpc == ARM::t2LDREX)
5546 AddDefaultPred(MIB);
5548 // Sign extend the value, if necessary.
5549 if (signExtend && extendOpc) {
5550 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5551 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5556 // Build compare and cmov instructions.
5557 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5558 .addReg(oldval).addReg(incr));
5559 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5560 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5562 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5563 if (strOpc == ARM::t2STREX)
5565 AddDefaultPred(MIB);
5566 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5567 .addReg(scratch).addImm(0));
5568 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5569 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5571 BB->addSuccessor(loopMBB);
5572 BB->addSuccessor(exitMBB);
5578 MI->eraseFromParent(); // The instruction is gone now.
5584 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5585 unsigned Op1, unsigned Op2,
5586 bool NeedsCarry, bool IsCmpxchg) const {
5587 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5588 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5590 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5591 MachineFunction *MF = BB->getParent();
5592 MachineFunction::iterator It = BB;
5595 unsigned destlo = MI->getOperand(0).getReg();
5596 unsigned desthi = MI->getOperand(1).getReg();
5597 unsigned ptr = MI->getOperand(2).getReg();
5598 unsigned vallo = MI->getOperand(3).getReg();
5599 unsigned valhi = MI->getOperand(4).getReg();
5600 DebugLoc dl = MI->getDebugLoc();
5601 bool isThumb2 = Subtarget->isThumb2();
5603 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5605 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5606 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5607 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5610 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5611 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5613 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5614 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5616 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5617 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5619 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5620 MF->insert(It, loopMBB);
5622 MF->insert(It, contBB);
5623 MF->insert(It, cont2BB);
5625 MF->insert(It, exitMBB);
5627 // Transfer the remainder of BB and its successor edges to exitMBB.
5628 exitMBB->splice(exitMBB->begin(), BB,
5629 llvm::next(MachineBasicBlock::iterator(MI)),
5631 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5633 const TargetRegisterClass *TRC = isThumb2 ?
5634 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5635 (const TargetRegisterClass*)&ARM::GPRRegClass;
5636 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5640 // fallthrough --> loopMBB
5641 BB->addSuccessor(loopMBB);
5644 // ldrexd r2, r3, ptr
5645 // <binopa> r0, r2, incr
5646 // <binopb> r1, r3, incr
5647 // strexd storesuccess, r0, r1, ptr
5648 // cmp storesuccess, #0
5650 // fallthrough --> exitMBB
5652 // Note that the registers are explicitly specified because there is not any
5653 // way to force the register allocator to allocate a register pair.
5655 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5656 // need to properly enforce the restriction that the two output registers
5657 // for ldrexd must be different.
5660 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5661 .addReg(ARM::R2, RegState::Define)
5662 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5663 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5664 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5665 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5669 for (unsigned i = 0; i < 2; i++) {
5670 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5672 .addReg(i == 0 ? destlo : desthi)
5673 .addReg(i == 0 ? vallo : valhi));
5674 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5675 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5676 BB->addSuccessor(exitMBB);
5677 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5678 BB = (i == 0 ? contBB : cont2BB);
5681 // Copy to physregs for strexd
5682 unsigned setlo = MI->getOperand(5).getReg();
5683 unsigned sethi = MI->getOperand(6).getReg();
5684 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5685 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5687 // Perform binary operation
5688 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5689 .addReg(destlo).addReg(vallo))
5690 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5691 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5692 .addReg(desthi).addReg(valhi)).addReg(0);
5694 // Copy to physregs for strexd
5695 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5696 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5700 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5701 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5703 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5704 .addReg(storesuccess).addImm(0));
5705 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5706 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5708 BB->addSuccessor(loopMBB);
5709 BB->addSuccessor(exitMBB);
5715 MI->eraseFromParent(); // The instruction is gone now.
5720 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5721 /// registers the function context.
5722 void ARMTargetLowering::
5723 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5724 MachineBasicBlock *DispatchBB, int FI) const {
5725 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5726 DebugLoc dl = MI->getDebugLoc();
5727 MachineFunction *MF = MBB->getParent();
5728 MachineRegisterInfo *MRI = &MF->getRegInfo();
5729 MachineConstantPool *MCP = MF->getConstantPool();
5730 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5731 const Function *F = MF->getFunction();
5733 bool isThumb = Subtarget->isThumb();
5734 bool isThumb2 = Subtarget->isThumb2();
5736 unsigned PCLabelId = AFI->createPICLabelUId();
5737 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5738 ARMConstantPoolValue *CPV =
5739 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5740 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5742 const TargetRegisterClass *TRC = isThumb ?
5743 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5744 (const TargetRegisterClass*)&ARM::GPRRegClass;
5746 // Grab constant pool and fixed stack memory operands.
5747 MachineMemOperand *CPMMO =
5748 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5749 MachineMemOperand::MOLoad, 4, 4);
5751 MachineMemOperand *FIMMOSt =
5752 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5753 MachineMemOperand::MOStore, 4, 4);
5755 // Load the address of the dispatch MBB into the jump buffer.
5757 // Incoming value: jbuf
5758 // ldr.n r5, LCPI1_1
5761 // str r5, [$jbuf, #+4] ; &jbuf[1]
5762 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5763 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5764 .addConstantPoolIndex(CPI)
5765 .addMemOperand(CPMMO));
5766 // Set the low bit because of thumb mode.
5767 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5769 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5770 .addReg(NewVReg1, RegState::Kill)
5772 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5773 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5774 .addReg(NewVReg2, RegState::Kill)
5776 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5777 .addReg(NewVReg3, RegState::Kill)
5779 .addImm(36) // &jbuf[1] :: pc
5780 .addMemOperand(FIMMOSt));
5781 } else if (isThumb) {
5782 // Incoming value: jbuf
5783 // ldr.n r1, LCPI1_4
5787 // add r2, $jbuf, #+4 ; &jbuf[1]
5789 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5790 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5791 .addConstantPoolIndex(CPI)
5792 .addMemOperand(CPMMO));
5793 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5794 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5795 .addReg(NewVReg1, RegState::Kill)
5797 // Set the low bit because of thumb mode.
5798 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5799 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5800 .addReg(ARM::CPSR, RegState::Define)
5802 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5803 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5804 .addReg(ARM::CPSR, RegState::Define)
5805 .addReg(NewVReg2, RegState::Kill)
5806 .addReg(NewVReg3, RegState::Kill));
5807 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5808 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5810 .addImm(36)); // &jbuf[1] :: pc
5811 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5812 .addReg(NewVReg4, RegState::Kill)
5813 .addReg(NewVReg5, RegState::Kill)
5815 .addMemOperand(FIMMOSt));
5817 // Incoming value: jbuf
5820 // str r1, [$jbuf, #+4] ; &jbuf[1]
5821 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5822 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5823 .addConstantPoolIndex(CPI)
5825 .addMemOperand(CPMMO));
5826 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5827 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5828 .addReg(NewVReg1, RegState::Kill)
5829 .addImm(PCLabelId));
5830 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5831 .addReg(NewVReg2, RegState::Kill)
5833 .addImm(36) // &jbuf[1] :: pc
5834 .addMemOperand(FIMMOSt));
5838 MachineBasicBlock *ARMTargetLowering::
5839 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5840 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5841 DebugLoc dl = MI->getDebugLoc();
5842 MachineFunction *MF = MBB->getParent();
5843 MachineRegisterInfo *MRI = &MF->getRegInfo();
5844 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5845 MachineFrameInfo *MFI = MF->getFrameInfo();
5846 int FI = MFI->getFunctionContextIndex();
5848 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5849 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5850 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5852 // Get a mapping of the call site numbers to all of the landing pads they're
5854 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5855 unsigned MaxCSNum = 0;
5856 MachineModuleInfo &MMI = MF->getMMI();
5857 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5859 if (!BB->isLandingPad()) continue;
5861 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5863 for (MachineBasicBlock::iterator
5864 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5865 if (!II->isEHLabel()) continue;
5867 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5868 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5870 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5871 for (SmallVectorImpl<unsigned>::iterator
5872 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5873 CSI != CSE; ++CSI) {
5874 CallSiteNumToLPad[*CSI].push_back(BB);
5875 MaxCSNum = std::max(MaxCSNum, *CSI);
5881 // Get an ordered list of the machine basic blocks for the jump table.
5882 std::vector<MachineBasicBlock*> LPadList;
5883 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5884 LPadList.reserve(CallSiteNumToLPad.size());
5885 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5886 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5887 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5888 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5889 LPadList.push_back(*II);
5890 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5894 assert(!LPadList.empty() &&
5895 "No landing pad destinations for the dispatch jump table!");
5897 // Create the jump table and associated information.
5898 MachineJumpTableInfo *JTI =
5899 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5900 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5901 unsigned UId = AFI->createJumpTableUId();
5903 // Create the MBBs for the dispatch code.
5905 // Shove the dispatch's address into the return slot in the function context.
5906 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5907 DispatchBB->setIsLandingPad();
5909 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5910 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5911 DispatchBB->addSuccessor(TrapBB);
5913 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5914 DispatchBB->addSuccessor(DispContBB);
5917 MF->insert(MF->end(), DispatchBB);
5918 MF->insert(MF->end(), DispContBB);
5919 MF->insert(MF->end(), TrapBB);
5921 // Insert code into the entry block that creates and registers the function
5923 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5925 MachineMemOperand *FIMMOLd =
5926 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5927 MachineMemOperand::MOLoad |
5928 MachineMemOperand::MOVolatile, 4, 4);
5930 if (AFI->isThumb1OnlyFunction())
5931 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5932 else if (!Subtarget->hasVFP2())
5933 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5935 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5937 unsigned NumLPads = LPadList.size();
5938 if (Subtarget->isThumb2()) {
5939 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5940 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5943 .addMemOperand(FIMMOLd));
5945 if (NumLPads < 256) {
5946 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5948 .addImm(LPadList.size()));
5950 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5951 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5952 .addImm(NumLPads & 0xFFFF));
5954 unsigned VReg2 = VReg1;
5955 if ((NumLPads & 0xFFFF0000) != 0) {
5956 VReg2 = MRI->createVirtualRegister(TRC);
5957 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5959 .addImm(NumLPads >> 16));
5962 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5967 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5972 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5973 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5974 .addJumpTableIndex(MJTI)
5977 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5980 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5981 .addReg(NewVReg3, RegState::Kill)
5983 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5985 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5986 .addReg(NewVReg4, RegState::Kill)
5988 .addJumpTableIndex(MJTI)
5990 } else if (Subtarget->isThumb()) {
5991 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5992 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5995 .addMemOperand(FIMMOLd));
5997 if (NumLPads < 256) {
5998 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6002 MachineConstantPool *ConstantPool = MF->getConstantPool();
6003 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6004 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6006 // MachineConstantPool wants an explicit alignment.
6007 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6009 Align = getTargetData()->getTypeAllocSize(C->getType());
6010 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6012 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6013 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6014 .addReg(VReg1, RegState::Define)
6015 .addConstantPoolIndex(Idx));
6016 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6021 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6026 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6027 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6028 .addReg(ARM::CPSR, RegState::Define)
6032 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6033 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6034 .addJumpTableIndex(MJTI)
6037 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6038 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6039 .addReg(ARM::CPSR, RegState::Define)
6040 .addReg(NewVReg2, RegState::Kill)
6043 MachineMemOperand *JTMMOLd =
6044 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6045 MachineMemOperand::MOLoad, 4, 4);
6047 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6048 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6049 .addReg(NewVReg4, RegState::Kill)
6051 .addMemOperand(JTMMOLd));
6053 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6054 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6055 .addReg(ARM::CPSR, RegState::Define)
6056 .addReg(NewVReg5, RegState::Kill)
6059 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6060 .addReg(NewVReg6, RegState::Kill)
6061 .addJumpTableIndex(MJTI)
6064 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6065 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6068 .addMemOperand(FIMMOLd));
6070 if (NumLPads < 256) {
6071 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6074 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6075 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6076 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6077 .addImm(NumLPads & 0xFFFF));
6079 unsigned VReg2 = VReg1;
6080 if ((NumLPads & 0xFFFF0000) != 0) {
6081 VReg2 = MRI->createVirtualRegister(TRC);
6082 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6084 .addImm(NumLPads >> 16));
6087 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6091 MachineConstantPool *ConstantPool = MF->getConstantPool();
6092 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6093 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6095 // MachineConstantPool wants an explicit alignment.
6096 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6098 Align = getTargetData()->getTypeAllocSize(C->getType());
6099 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6101 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6102 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6103 .addReg(VReg1, RegState::Define)
6104 .addConstantPoolIndex(Idx)
6106 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6108 .addReg(VReg1, RegState::Kill));
6111 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6116 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6118 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6120 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6121 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6122 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6123 .addJumpTableIndex(MJTI)
6126 MachineMemOperand *JTMMOLd =
6127 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6128 MachineMemOperand::MOLoad, 4, 4);
6129 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6131 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6132 .addReg(NewVReg3, RegState::Kill)
6135 .addMemOperand(JTMMOLd));
6137 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6138 .addReg(NewVReg5, RegState::Kill)
6140 .addJumpTableIndex(MJTI)
6144 // Add the jump table entries as successors to the MBB.
6145 MachineBasicBlock *PrevMBB = 0;
6146 for (std::vector<MachineBasicBlock*>::iterator
6147 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6148 MachineBasicBlock *CurMBB = *I;
6149 if (PrevMBB != CurMBB)
6150 DispContBB->addSuccessor(CurMBB);
6154 // N.B. the order the invoke BBs are processed in doesn't matter here.
6155 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6156 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6157 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6158 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6159 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6160 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6161 MachineBasicBlock *BB = *I;
6163 // Remove the landing pad successor from the invoke block and replace it
6164 // with the new dispatch block.
6165 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6167 while (!Successors.empty()) {
6168 MachineBasicBlock *SMBB = Successors.pop_back_val();
6169 if (SMBB->isLandingPad()) {
6170 BB->removeSuccessor(SMBB);
6171 MBBLPads.push_back(SMBB);
6175 BB->addSuccessor(DispatchBB);
6177 // Find the invoke call and mark all of the callee-saved registers as
6178 // 'implicit defined' so that they're spilled. This prevents code from
6179 // moving instructions to before the EH block, where they will never be
6181 for (MachineBasicBlock::reverse_iterator
6182 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6183 if (!II->isCall()) continue;
6185 DenseMap<unsigned, bool> DefRegs;
6186 for (MachineInstr::mop_iterator
6187 OI = II->operands_begin(), OE = II->operands_end();
6189 if (!OI->isReg()) continue;
6190 DefRegs[OI->getReg()] = true;
6193 MachineInstrBuilder MIB(&*II);
6195 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6196 unsigned Reg = SavedRegs[i];
6197 if (Subtarget->isThumb2() &&
6198 !ARM::tGPRRegClass.contains(Reg) &&
6199 !ARM::hGPRRegClass.contains(Reg))
6201 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6203 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6206 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6213 // Mark all former landing pads as non-landing pads. The dispatch is the only
6215 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6216 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6217 (*I)->setIsLandingPad(false);
6219 // The instruction is gone now.
6220 MI->eraseFromParent();
6226 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6227 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6228 E = MBB->succ_end(); I != E; ++I)
6231 llvm_unreachable("Expecting a BB with two successors!");
6235 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6236 MachineBasicBlock *BB) const {
6237 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6238 DebugLoc dl = MI->getDebugLoc();
6239 bool isThumb2 = Subtarget->isThumb2();
6240 switch (MI->getOpcode()) {
6243 llvm_unreachable("Unexpected instr type to insert");
6245 // The Thumb2 pre-indexed stores have the same MI operands, they just
6246 // define them differently in the .td files from the isel patterns, so
6247 // they need pseudos.
6248 case ARM::t2STR_preidx:
6249 MI->setDesc(TII->get(ARM::t2STR_PRE));
6251 case ARM::t2STRB_preidx:
6252 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6254 case ARM::t2STRH_preidx:
6255 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6258 case ARM::STRi_preidx:
6259 case ARM::STRBi_preidx: {
6260 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6261 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6262 // Decode the offset.
6263 unsigned Offset = MI->getOperand(4).getImm();
6264 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6265 Offset = ARM_AM::getAM2Offset(Offset);
6269 MachineMemOperand *MMO = *MI->memoperands_begin();
6270 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6271 .addOperand(MI->getOperand(0)) // Rn_wb
6272 .addOperand(MI->getOperand(1)) // Rt
6273 .addOperand(MI->getOperand(2)) // Rn
6274 .addImm(Offset) // offset (skip GPR==zero_reg)
6275 .addOperand(MI->getOperand(5)) // pred
6276 .addOperand(MI->getOperand(6))
6277 .addMemOperand(MMO);
6278 MI->eraseFromParent();
6281 case ARM::STRr_preidx:
6282 case ARM::STRBr_preidx:
6283 case ARM::STRH_preidx: {
6285 switch (MI->getOpcode()) {
6286 default: llvm_unreachable("unexpected opcode!");
6287 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6288 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6289 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6291 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6292 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6293 MIB.addOperand(MI->getOperand(i));
6294 MI->eraseFromParent();
6297 case ARM::ATOMIC_LOAD_ADD_I8:
6298 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6299 case ARM::ATOMIC_LOAD_ADD_I16:
6300 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6301 case ARM::ATOMIC_LOAD_ADD_I32:
6302 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6304 case ARM::ATOMIC_LOAD_AND_I8:
6305 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6306 case ARM::ATOMIC_LOAD_AND_I16:
6307 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6308 case ARM::ATOMIC_LOAD_AND_I32:
6309 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6311 case ARM::ATOMIC_LOAD_OR_I8:
6312 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6313 case ARM::ATOMIC_LOAD_OR_I16:
6314 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6315 case ARM::ATOMIC_LOAD_OR_I32:
6316 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6318 case ARM::ATOMIC_LOAD_XOR_I8:
6319 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6320 case ARM::ATOMIC_LOAD_XOR_I16:
6321 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6322 case ARM::ATOMIC_LOAD_XOR_I32:
6323 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6325 case ARM::ATOMIC_LOAD_NAND_I8:
6326 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6327 case ARM::ATOMIC_LOAD_NAND_I16:
6328 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6329 case ARM::ATOMIC_LOAD_NAND_I32:
6330 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6332 case ARM::ATOMIC_LOAD_SUB_I8:
6333 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6334 case ARM::ATOMIC_LOAD_SUB_I16:
6335 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6336 case ARM::ATOMIC_LOAD_SUB_I32:
6337 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6339 case ARM::ATOMIC_LOAD_MIN_I8:
6340 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6341 case ARM::ATOMIC_LOAD_MIN_I16:
6342 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6343 case ARM::ATOMIC_LOAD_MIN_I32:
6344 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6346 case ARM::ATOMIC_LOAD_MAX_I8:
6347 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6348 case ARM::ATOMIC_LOAD_MAX_I16:
6349 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6350 case ARM::ATOMIC_LOAD_MAX_I32:
6351 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6353 case ARM::ATOMIC_LOAD_UMIN_I8:
6354 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6355 case ARM::ATOMIC_LOAD_UMIN_I16:
6356 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6357 case ARM::ATOMIC_LOAD_UMIN_I32:
6358 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6360 case ARM::ATOMIC_LOAD_UMAX_I8:
6361 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6362 case ARM::ATOMIC_LOAD_UMAX_I16:
6363 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6364 case ARM::ATOMIC_LOAD_UMAX_I32:
6365 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6367 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6368 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6369 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6371 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6372 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6373 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6376 case ARM::ATOMADD6432:
6377 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6378 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6379 /*NeedsCarry*/ true);
6380 case ARM::ATOMSUB6432:
6381 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6382 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6383 /*NeedsCarry*/ true);
6384 case ARM::ATOMOR6432:
6385 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6386 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6387 case ARM::ATOMXOR6432:
6388 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6389 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6390 case ARM::ATOMAND6432:
6391 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6392 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6393 case ARM::ATOMSWAP6432:
6394 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6395 case ARM::ATOMCMPXCHG6432:
6396 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6397 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6398 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6400 case ARM::tMOVCCr_pseudo: {
6401 // To "insert" a SELECT_CC instruction, we actually have to insert the
6402 // diamond control-flow pattern. The incoming instruction knows the
6403 // destination vreg to set, the condition code register to branch on, the
6404 // true/false values to select between, and a branch opcode to use.
6405 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6406 MachineFunction::iterator It = BB;
6412 // cmpTY ccX, r1, r2
6414 // fallthrough --> copy0MBB
6415 MachineBasicBlock *thisMBB = BB;
6416 MachineFunction *F = BB->getParent();
6417 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6418 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6419 F->insert(It, copy0MBB);
6420 F->insert(It, sinkMBB);
6422 // Transfer the remainder of BB and its successor edges to sinkMBB.
6423 sinkMBB->splice(sinkMBB->begin(), BB,
6424 llvm::next(MachineBasicBlock::iterator(MI)),
6426 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6428 BB->addSuccessor(copy0MBB);
6429 BB->addSuccessor(sinkMBB);
6431 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6432 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6435 // %FalseValue = ...
6436 // # fallthrough to sinkMBB
6439 // Update machine-CFG edges
6440 BB->addSuccessor(sinkMBB);
6443 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6446 BuildMI(*BB, BB->begin(), dl,
6447 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6448 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6449 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6451 MI->eraseFromParent(); // The pseudo instruction is gone now.
6456 case ARM::BCCZi64: {
6457 // If there is an unconditional branch to the other successor, remove it.
6458 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6460 // Compare both parts that make up the double comparison separately for
6462 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6464 unsigned LHS1 = MI->getOperand(1).getReg();
6465 unsigned LHS2 = MI->getOperand(2).getReg();
6467 AddDefaultPred(BuildMI(BB, dl,
6468 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6469 .addReg(LHS1).addImm(0));
6470 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6471 .addReg(LHS2).addImm(0)
6472 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6474 unsigned RHS1 = MI->getOperand(3).getReg();
6475 unsigned RHS2 = MI->getOperand(4).getReg();
6476 AddDefaultPred(BuildMI(BB, dl,
6477 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6478 .addReg(LHS1).addReg(RHS1));
6479 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6480 .addReg(LHS2).addReg(RHS2)
6481 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6484 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6485 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6486 if (MI->getOperand(0).getImm() == ARMCC::NE)
6487 std::swap(destMBB, exitMBB);
6489 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6490 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6492 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6494 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6496 MI->eraseFromParent(); // The pseudo instruction is gone now.
6500 case ARM::Int_eh_sjlj_setjmp:
6501 case ARM::Int_eh_sjlj_setjmp_nofp:
6502 case ARM::tInt_eh_sjlj_setjmp:
6503 case ARM::t2Int_eh_sjlj_setjmp:
6504 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6505 EmitSjLjDispatchBlock(MI, BB);
6510 // To insert an ABS instruction, we have to insert the
6511 // diamond control-flow pattern. The incoming instruction knows the
6512 // source vreg to test against 0, the destination vreg to set,
6513 // the condition code register to branch on, the
6514 // true/false values to select between, and a branch opcode to use.
6519 // BCC (branch to SinkBB if V0 >= 0)
6520 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6521 // SinkBB: V1 = PHI(V2, V3)
6522 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6523 MachineFunction::iterator BBI = BB;
6525 MachineFunction *Fn = BB->getParent();
6526 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6527 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6528 Fn->insert(BBI, RSBBB);
6529 Fn->insert(BBI, SinkBB);
6531 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6532 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6533 bool isThumb2 = Subtarget->isThumb2();
6534 MachineRegisterInfo &MRI = Fn->getRegInfo();
6535 // In Thumb mode S must not be specified if source register is the SP or
6536 // PC and if destination register is the SP, so restrict register class
6537 unsigned NewMovDstReg = MRI.createVirtualRegister(isThumb2 ?
6538 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6539 (const TargetRegisterClass*)&ARM::GPRRegClass);
6540 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6541 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6542 (const TargetRegisterClass*)&ARM::GPRRegClass);
6544 // Transfer the remainder of BB and its successor edges to sinkMBB.
6545 SinkBB->splice(SinkBB->begin(), BB,
6546 llvm::next(MachineBasicBlock::iterator(MI)),
6548 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6550 BB->addSuccessor(RSBBB);
6551 BB->addSuccessor(SinkBB);
6553 // fall through to SinkMBB
6554 RSBBB->addSuccessor(SinkBB);
6556 // insert a movs at the end of BB
6557 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6559 .addReg(ABSSrcReg, RegState::Kill)
6560 .addImm((unsigned)ARMCC::AL).addReg(0)
6561 .addReg(ARM::CPSR, RegState::Define);
6563 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6565 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6566 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6568 // insert rsbri in RSBBB
6569 // Note: BCC and rsbri will be converted into predicated rsbmi
6570 // by if-conversion pass
6571 BuildMI(*RSBBB, RSBBB->begin(), dl,
6572 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6573 .addReg(NewMovDstReg, RegState::Kill)
6574 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6576 // insert PHI in SinkBB,
6577 // reuse ABSDstReg to not change uses of ABS instruction
6578 BuildMI(*SinkBB, SinkBB->begin(), dl,
6579 TII->get(ARM::PHI), ABSDstReg)
6580 .addReg(NewRsbDstReg).addMBB(RSBBB)
6581 .addReg(NewMovDstReg).addMBB(BB);
6583 // remove ABS instruction
6584 MI->eraseFromParent();
6586 // return last added BB
6592 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6593 SDNode *Node) const {
6594 if (!MI->hasPostISelHook()) {
6595 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6596 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6600 const MCInstrDesc *MCID = &MI->getDesc();
6601 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6602 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6603 // operand is still set to noreg. If needed, set the optional operand's
6604 // register to CPSR, and remove the redundant implicit def.
6606 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6608 // Rename pseudo opcodes.
6609 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6611 const ARMBaseInstrInfo *TII =
6612 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6613 MCID = &TII->get(NewOpc);
6615 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6616 "converted opcode should be the same except for cc_out");
6620 // Add the optional cc_out operand
6621 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6623 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6625 // Any ARM instruction that sets the 's' bit should specify an optional
6626 // "cc_out" operand in the last operand position.
6627 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6628 assert(!NewOpc && "Optional cc_out operand required");
6631 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6632 // since we already have an optional CPSR def.
6633 bool definesCPSR = false;
6634 bool deadCPSR = false;
6635 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6637 const MachineOperand &MO = MI->getOperand(i);
6638 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6642 MI->RemoveOperand(i);
6647 assert(!NewOpc && "Optional cc_out operand required");
6650 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6652 assert(!MI->getOperand(ccOutIdx).getReg() &&
6653 "expect uninitialized optional cc_out operand");
6657 // If this instruction was defined with an optional CPSR def and its dag node
6658 // had a live implicit CPSR def, then activate the optional CPSR def.
6659 MachineOperand &MO = MI->getOperand(ccOutIdx);
6660 MO.setReg(ARM::CPSR);
6664 //===----------------------------------------------------------------------===//
6665 // ARM Optimization Hooks
6666 //===----------------------------------------------------------------------===//
6669 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6670 TargetLowering::DAGCombinerInfo &DCI) {
6671 SelectionDAG &DAG = DCI.DAG;
6672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6673 EVT VT = N->getValueType(0);
6674 unsigned Opc = N->getOpcode();
6675 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6676 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6677 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6678 ISD::CondCode CC = ISD::SETCC_INVALID;
6681 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6683 SDValue CCOp = Slct.getOperand(0);
6684 if (CCOp.getOpcode() == ISD::SETCC)
6685 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6688 bool DoXform = false;
6690 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6693 if (LHS.getOpcode() == ISD::Constant &&
6694 cast<ConstantSDNode>(LHS)->isNullValue()) {
6696 } else if (CC != ISD::SETCC_INVALID &&
6697 RHS.getOpcode() == ISD::Constant &&
6698 cast<ConstantSDNode>(RHS)->isNullValue()) {
6699 std::swap(LHS, RHS);
6700 SDValue Op0 = Slct.getOperand(0);
6701 EVT OpVT = isSlctCC ? Op0.getValueType() :
6702 Op0.getOperand(0).getValueType();
6703 bool isInt = OpVT.isInteger();
6704 CC = ISD::getSetCCInverse(CC, isInt);
6706 if (!TLI.isCondCodeLegal(CC, OpVT))
6707 return SDValue(); // Inverse operator isn't legal.
6714 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6716 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6717 Slct.getOperand(0), Slct.getOperand(1), CC);
6718 SDValue CCOp = Slct.getOperand(0);
6720 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6721 CCOp.getOperand(0), CCOp.getOperand(1), CC);
6722 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6723 CCOp, OtherOp, Result);
6728 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6729 // (only after legalization).
6730 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6731 TargetLowering::DAGCombinerInfo &DCI,
6732 const ARMSubtarget *Subtarget) {
6734 // Only perform optimization if after legalize, and if NEON is available. We
6735 // also expected both operands to be BUILD_VECTORs.
6736 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6737 || N0.getOpcode() != ISD::BUILD_VECTOR
6738 || N1.getOpcode() != ISD::BUILD_VECTOR)
6741 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6742 EVT VT = N->getValueType(0);
6743 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6746 // Check that the vector operands are of the right form.
6747 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6748 // operands, where N is the size of the formed vector.
6749 // Each EXTRACT_VECTOR should have the same input vector and odd or even
6750 // index such that we have a pair wise add pattern.
6752 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6753 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6755 SDValue Vec = N0->getOperand(0)->getOperand(0);
6756 SDNode *V = Vec.getNode();
6757 unsigned nextIndex = 0;
6759 // For each operands to the ADD which are BUILD_VECTORs,
6760 // check to see if each of their operands are an EXTRACT_VECTOR with
6761 // the same vector and appropriate index.
6762 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6763 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6764 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6766 SDValue ExtVec0 = N0->getOperand(i);
6767 SDValue ExtVec1 = N1->getOperand(i);
6769 // First operand is the vector, verify its the same.
6770 if (V != ExtVec0->getOperand(0).getNode() ||
6771 V != ExtVec1->getOperand(0).getNode())
6774 // Second is the constant, verify its correct.
6775 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6776 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6778 // For the constant, we want to see all the even or all the odd.
6779 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6780 || C1->getZExtValue() != nextIndex+1)
6789 // Create VPADDL node.
6790 SelectionDAG &DAG = DCI.DAG;
6791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6793 // Build operand list.
6794 SmallVector<SDValue, 8> Ops;
6795 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6796 TLI.getPointerTy()));
6798 // Input is the vector.
6801 // Get widened type and narrowed type.
6803 unsigned numElem = VT.getVectorNumElements();
6804 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6805 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6806 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6807 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6809 llvm_unreachable("Invalid vector element type for padd optimization.");
6812 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6813 widenType, &Ops[0], Ops.size());
6814 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6817 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6818 /// operands N0 and N1. This is a helper for PerformADDCombine that is
6819 /// called with the default operands, and if that fails, with commuted
6821 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6822 TargetLowering::DAGCombinerInfo &DCI,
6823 const ARMSubtarget *Subtarget){
6825 // Attempt to create vpaddl for this add.
6826 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6827 if (Result.getNode())
6830 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6831 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6832 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6833 if (Result.getNode()) return Result;
6838 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6840 static SDValue PerformADDCombine(SDNode *N,
6841 TargetLowering::DAGCombinerInfo &DCI,
6842 const ARMSubtarget *Subtarget) {
6843 SDValue N0 = N->getOperand(0);
6844 SDValue N1 = N->getOperand(1);
6846 // First try with the default operand order.
6847 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6848 if (Result.getNode())
6851 // If that didn't work, try again with the operands commuted.
6852 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6855 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6857 static SDValue PerformSUBCombine(SDNode *N,
6858 TargetLowering::DAGCombinerInfo &DCI) {
6859 SDValue N0 = N->getOperand(0);
6860 SDValue N1 = N->getOperand(1);
6862 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6863 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6864 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6865 if (Result.getNode()) return Result;
6871 /// PerformVMULCombine
6872 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6873 /// special multiplier accumulator forwarding.
6879 static SDValue PerformVMULCombine(SDNode *N,
6880 TargetLowering::DAGCombinerInfo &DCI,
6881 const ARMSubtarget *Subtarget) {
6882 if (!Subtarget->hasVMLxForwarding())
6885 SelectionDAG &DAG = DCI.DAG;
6886 SDValue N0 = N->getOperand(0);
6887 SDValue N1 = N->getOperand(1);
6888 unsigned Opcode = N0.getOpcode();
6889 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6890 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6891 Opcode = N1.getOpcode();
6892 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6893 Opcode != ISD::FADD && Opcode != ISD::FSUB)
6898 EVT VT = N->getValueType(0);
6899 DebugLoc DL = N->getDebugLoc();
6900 SDValue N00 = N0->getOperand(0);
6901 SDValue N01 = N0->getOperand(1);
6902 return DAG.getNode(Opcode, DL, VT,
6903 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6904 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6907 static SDValue PerformMULCombine(SDNode *N,
6908 TargetLowering::DAGCombinerInfo &DCI,
6909 const ARMSubtarget *Subtarget) {
6910 SelectionDAG &DAG = DCI.DAG;
6912 if (Subtarget->isThumb1Only())
6915 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6918 EVT VT = N->getValueType(0);
6919 if (VT.is64BitVector() || VT.is128BitVector())
6920 return PerformVMULCombine(N, DCI, Subtarget);
6924 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6928 int64_t MulAmt = C->getSExtValue();
6929 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6931 ShiftAmt = ShiftAmt & (32 - 1);
6932 SDValue V = N->getOperand(0);
6933 DebugLoc DL = N->getDebugLoc();
6936 MulAmt >>= ShiftAmt;
6939 if (isPowerOf2_32(MulAmt - 1)) {
6940 // (mul x, 2^N + 1) => (add (shl x, N), x)
6941 Res = DAG.getNode(ISD::ADD, DL, VT,
6943 DAG.getNode(ISD::SHL, DL, VT,
6945 DAG.getConstant(Log2_32(MulAmt - 1),
6947 } else if (isPowerOf2_32(MulAmt + 1)) {
6948 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6949 Res = DAG.getNode(ISD::SUB, DL, VT,
6950 DAG.getNode(ISD::SHL, DL, VT,
6952 DAG.getConstant(Log2_32(MulAmt + 1),
6958 uint64_t MulAmtAbs = -MulAmt;
6959 if (isPowerOf2_32(MulAmtAbs + 1)) {
6960 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6961 Res = DAG.getNode(ISD::SUB, DL, VT,
6963 DAG.getNode(ISD::SHL, DL, VT,
6965 DAG.getConstant(Log2_32(MulAmtAbs + 1),
6967 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
6968 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6969 Res = DAG.getNode(ISD::ADD, DL, VT,
6971 DAG.getNode(ISD::SHL, DL, VT,
6973 DAG.getConstant(Log2_32(MulAmtAbs-1),
6975 Res = DAG.getNode(ISD::SUB, DL, VT,
6976 DAG.getConstant(0, MVT::i32),Res);
6983 Res = DAG.getNode(ISD::SHL, DL, VT,
6984 Res, DAG.getConstant(ShiftAmt, MVT::i32));
6986 // Do not add new nodes to DAG combiner worklist.
6987 DCI.CombineTo(N, Res, false);
6991 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6992 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
6995 SDValue FalseVal = N.getOperand(0);
6996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7000 return C->isAllOnesValue();
7001 return C->isNullValue();
7004 /// formConditionalOp - Combine an operation with a conditional move operand
7005 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7006 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7007 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7009 SDValue N0 = N->getOperand(0);
7010 SDValue N1 = N->getOperand(1);
7012 bool isAND = N->getOpcode() == ISD::AND;
7013 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7014 if (!isCand && Commutable) {
7015 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7023 switch (N->getOpcode()) {
7024 default: llvm_unreachable("Unexpected node");
7025 case ISD::AND: Opc = ARMISD::CAND; break;
7026 case ISD::OR: Opc = ARMISD::COR; break;
7027 case ISD::XOR: Opc = ARMISD::CXOR; break;
7029 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7030 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7034 static SDValue PerformANDCombine(SDNode *N,
7035 TargetLowering::DAGCombinerInfo &DCI,
7036 const ARMSubtarget *Subtarget) {
7038 // Attempt to use immediate-form VBIC
7039 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7040 DebugLoc dl = N->getDebugLoc();
7041 EVT VT = N->getValueType(0);
7042 SelectionDAG &DAG = DCI.DAG;
7044 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7047 APInt SplatBits, SplatUndef;
7048 unsigned SplatBitSize;
7051 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7052 if (SplatBitSize <= 64) {
7054 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7055 SplatUndef.getZExtValue(), SplatBitSize,
7056 DAG, VbicVT, VT.is128BitVector(),
7058 if (Val.getNode()) {
7060 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7061 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7062 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7067 if (!Subtarget->isThumb1Only()) {
7068 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7069 SDValue CAND = formConditionalOp(N, DAG, true);
7077 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7078 static SDValue PerformORCombine(SDNode *N,
7079 TargetLowering::DAGCombinerInfo &DCI,
7080 const ARMSubtarget *Subtarget) {
7081 // Attempt to use immediate-form VORR
7082 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7083 DebugLoc dl = N->getDebugLoc();
7084 EVT VT = N->getValueType(0);
7085 SelectionDAG &DAG = DCI.DAG;
7087 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7090 APInt SplatBits, SplatUndef;
7091 unsigned SplatBitSize;
7093 if (BVN && Subtarget->hasNEON() &&
7094 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7095 if (SplatBitSize <= 64) {
7097 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7098 SplatUndef.getZExtValue(), SplatBitSize,
7099 DAG, VorrVT, VT.is128BitVector(),
7101 if (Val.getNode()) {
7103 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7104 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7105 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7110 if (!Subtarget->isThumb1Only()) {
7111 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7112 SDValue COR = formConditionalOp(N, DAG, true);
7117 SDValue N0 = N->getOperand(0);
7118 if (N0.getOpcode() != ISD::AND)
7120 SDValue N1 = N->getOperand(1);
7122 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7123 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7124 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7126 unsigned SplatBitSize;
7129 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7131 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7132 HasAnyUndefs) && !HasAnyUndefs) {
7133 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7135 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7136 HasAnyUndefs) && !HasAnyUndefs &&
7137 SplatBits0 == ~SplatBits1) {
7138 // Canonicalize the vector type to make instruction selection simpler.
7139 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7140 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7141 N0->getOperand(1), N0->getOperand(0),
7143 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7148 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7151 // BFI is only available on V6T2+
7152 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7155 DebugLoc DL = N->getDebugLoc();
7156 // 1) or (and A, mask), val => ARMbfi A, val, mask
7157 // iff (val & mask) == val
7159 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7160 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7161 // && mask == ~mask2
7162 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7163 // && ~mask == mask2
7164 // (i.e., copy a bitfield value into another bitfield of the same width)
7169 SDValue N00 = N0.getOperand(0);
7171 // The value and the mask need to be constants so we can verify this is
7172 // actually a bitfield set. If the mask is 0xffff, we can do better
7173 // via a movt instruction, so don't use BFI in that case.
7174 SDValue MaskOp = N0.getOperand(1);
7175 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7178 unsigned Mask = MaskC->getZExtValue();
7182 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7183 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7185 unsigned Val = N1C->getZExtValue();
7186 if ((Val & ~Mask) != Val)
7189 if (ARM::isBitFieldInvertedMask(Mask)) {
7190 Val >>= CountTrailingZeros_32(~Mask);
7192 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7193 DAG.getConstant(Val, MVT::i32),
7194 DAG.getConstant(Mask, MVT::i32));
7196 // Do not add new nodes to DAG combiner worklist.
7197 DCI.CombineTo(N, Res, false);
7200 } else if (N1.getOpcode() == ISD::AND) {
7201 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7202 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7205 unsigned Mask2 = N11C->getZExtValue();
7207 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7209 if (ARM::isBitFieldInvertedMask(Mask) &&
7211 // The pack halfword instruction works better for masks that fit it,
7212 // so use that when it's available.
7213 if (Subtarget->hasT2ExtractPack() &&
7214 (Mask == 0xffff || Mask == 0xffff0000))
7217 unsigned amt = CountTrailingZeros_32(Mask2);
7218 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7219 DAG.getConstant(amt, MVT::i32));
7220 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7221 DAG.getConstant(Mask, MVT::i32));
7222 // Do not add new nodes to DAG combiner worklist.
7223 DCI.CombineTo(N, Res, false);
7225 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7227 // The pack halfword instruction works better for masks that fit it,
7228 // so use that when it's available.
7229 if (Subtarget->hasT2ExtractPack() &&
7230 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7233 unsigned lsb = CountTrailingZeros_32(Mask);
7234 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7235 DAG.getConstant(lsb, MVT::i32));
7236 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7237 DAG.getConstant(Mask2, MVT::i32));
7238 // Do not add new nodes to DAG combiner worklist.
7239 DCI.CombineTo(N, Res, false);
7244 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7245 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7246 ARM::isBitFieldInvertedMask(~Mask)) {
7247 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7248 // where lsb(mask) == #shamt and masked bits of B are known zero.
7249 SDValue ShAmt = N00.getOperand(1);
7250 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7251 unsigned LSB = CountTrailingZeros_32(Mask);
7255 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7256 DAG.getConstant(~Mask, MVT::i32));
7258 // Do not add new nodes to DAG combiner worklist.
7259 DCI.CombineTo(N, Res, false);
7265 static SDValue PerformXORCombine(SDNode *N,
7266 TargetLowering::DAGCombinerInfo &DCI,
7267 const ARMSubtarget *Subtarget) {
7268 EVT VT = N->getValueType(0);
7269 SelectionDAG &DAG = DCI.DAG;
7271 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7274 if (!Subtarget->isThumb1Only()) {
7275 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7276 SDValue CXOR = formConditionalOp(N, DAG, true);
7284 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7285 /// the bits being cleared by the AND are not demanded by the BFI.
7286 static SDValue PerformBFICombine(SDNode *N,
7287 TargetLowering::DAGCombinerInfo &DCI) {
7288 SDValue N1 = N->getOperand(1);
7289 if (N1.getOpcode() == ISD::AND) {
7290 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7293 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7294 unsigned LSB = CountTrailingZeros_32(~InvMask);
7295 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7296 unsigned Mask = (1 << Width)-1;
7297 unsigned Mask2 = N11C->getZExtValue();
7298 if ((Mask & (~Mask2)) == 0)
7299 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7300 N->getOperand(0), N1.getOperand(0),
7306 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7307 /// ARMISD::VMOVRRD.
7308 static SDValue PerformVMOVRRDCombine(SDNode *N,
7309 TargetLowering::DAGCombinerInfo &DCI) {
7310 // vmovrrd(vmovdrr x, y) -> x,y
7311 SDValue InDouble = N->getOperand(0);
7312 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7313 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7315 // vmovrrd(load f64) -> (load i32), (load i32)
7316 SDNode *InNode = InDouble.getNode();
7317 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7318 InNode->getValueType(0) == MVT::f64 &&
7319 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7320 !cast<LoadSDNode>(InNode)->isVolatile()) {
7321 // TODO: Should this be done for non-FrameIndex operands?
7322 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7324 SelectionDAG &DAG = DCI.DAG;
7325 DebugLoc DL = LD->getDebugLoc();
7326 SDValue BasePtr = LD->getBasePtr();
7327 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7328 LD->getPointerInfo(), LD->isVolatile(),
7329 LD->isNonTemporal(), LD->isInvariant(),
7330 LD->getAlignment());
7332 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7333 DAG.getConstant(4, MVT::i32));
7334 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7335 LD->getPointerInfo(), LD->isVolatile(),
7336 LD->isNonTemporal(), LD->isInvariant(),
7337 std::min(4U, LD->getAlignment() / 2));
7339 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7340 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7341 DCI.RemoveFromWorklist(LD);
7349 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7350 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7351 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7352 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7353 SDValue Op0 = N->getOperand(0);
7354 SDValue Op1 = N->getOperand(1);
7355 if (Op0.getOpcode() == ISD::BITCAST)
7356 Op0 = Op0.getOperand(0);
7357 if (Op1.getOpcode() == ISD::BITCAST)
7358 Op1 = Op1.getOperand(0);
7359 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7360 Op0.getNode() == Op1.getNode() &&
7361 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7362 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7363 N->getValueType(0), Op0.getOperand(0));
7367 /// PerformSTORECombine - Target-specific dag combine xforms for
7369 static SDValue PerformSTORECombine(SDNode *N,
7370 TargetLowering::DAGCombinerInfo &DCI) {
7371 StoreSDNode *St = cast<StoreSDNode>(N);
7372 if (St->isVolatile())
7375 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7376 // pack all of the elements in one place. Next, store to memory in fewer
7378 SDValue StVal = St->getValue();
7379 EVT VT = StVal.getValueType();
7380 if (St->isTruncatingStore() && VT.isVector()) {
7381 SelectionDAG &DAG = DCI.DAG;
7382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7383 EVT StVT = St->getMemoryVT();
7384 unsigned NumElems = VT.getVectorNumElements();
7385 assert(StVT != VT && "Cannot truncate to the same type");
7386 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7387 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7389 // From, To sizes and ElemCount must be pow of two
7390 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7392 // We are going to use the original vector elt for storing.
7393 // Accumulated smaller vector elements must be a multiple of the store size.
7394 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7396 unsigned SizeRatio = FromEltSz / ToEltSz;
7397 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7399 // Create a type on which we perform the shuffle.
7400 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7401 NumElems*SizeRatio);
7402 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7404 DebugLoc DL = St->getDebugLoc();
7405 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7406 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7407 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7409 // Can't shuffle using an illegal type.
7410 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7412 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7413 DAG.getUNDEF(WideVec.getValueType()),
7415 // At this point all of the data is stored at the bottom of the
7416 // register. We now need to save it to mem.
7418 // Find the largest store unit
7419 MVT StoreType = MVT::i8;
7420 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7421 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7422 MVT Tp = (MVT::SimpleValueType)tp;
7423 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7426 // Didn't find a legal store type.
7427 if (!TLI.isTypeLegal(StoreType))
7430 // Bitcast the original vector into a vector of store-size units
7431 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7432 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7433 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7434 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7435 SmallVector<SDValue, 8> Chains;
7436 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7437 TLI.getPointerTy());
7438 SDValue BasePtr = St->getBasePtr();
7440 // Perform one or more big stores into memory.
7441 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7442 for (unsigned I = 0; I < E; I++) {
7443 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7444 StoreType, ShuffWide,
7445 DAG.getIntPtrConstant(I));
7446 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7447 St->getPointerInfo(), St->isVolatile(),
7448 St->isNonTemporal(), St->getAlignment());
7449 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7451 Chains.push_back(Ch);
7453 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7457 if (!ISD::isNormalStore(St))
7460 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7461 // ARM stores of arguments in the same cache line.
7462 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7463 StVal.getNode()->hasOneUse()) {
7464 SelectionDAG &DAG = DCI.DAG;
7465 DebugLoc DL = St->getDebugLoc();
7466 SDValue BasePtr = St->getBasePtr();
7467 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7468 StVal.getNode()->getOperand(0), BasePtr,
7469 St->getPointerInfo(), St->isVolatile(),
7470 St->isNonTemporal(), St->getAlignment());
7472 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7473 DAG.getConstant(4, MVT::i32));
7474 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7475 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7476 St->isNonTemporal(),
7477 std::min(4U, St->getAlignment() / 2));
7480 if (StVal.getValueType() != MVT::i64 ||
7481 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7484 // Bitcast an i64 store extracted from a vector to f64.
7485 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7486 SelectionDAG &DAG = DCI.DAG;
7487 DebugLoc dl = StVal.getDebugLoc();
7488 SDValue IntVec = StVal.getOperand(0);
7489 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7490 IntVec.getValueType().getVectorNumElements());
7491 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7492 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7493 Vec, StVal.getOperand(1));
7494 dl = N->getDebugLoc();
7495 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7496 // Make the DAGCombiner fold the bitcasts.
7497 DCI.AddToWorklist(Vec.getNode());
7498 DCI.AddToWorklist(ExtElt.getNode());
7499 DCI.AddToWorklist(V.getNode());
7500 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7501 St->getPointerInfo(), St->isVolatile(),
7502 St->isNonTemporal(), St->getAlignment(),
7506 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7507 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7508 /// i64 vector to have f64 elements, since the value can then be loaded
7509 /// directly into a VFP register.
7510 static bool hasNormalLoadOperand(SDNode *N) {
7511 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7512 for (unsigned i = 0; i < NumElts; ++i) {
7513 SDNode *Elt = N->getOperand(i).getNode();
7514 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7520 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7521 /// ISD::BUILD_VECTOR.
7522 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7523 TargetLowering::DAGCombinerInfo &DCI){
7524 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7525 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7526 // into a pair of GPRs, which is fine when the value is used as a scalar,
7527 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7528 SelectionDAG &DAG = DCI.DAG;
7529 if (N->getNumOperands() == 2) {
7530 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7535 // Load i64 elements as f64 values so that type legalization does not split
7536 // them up into i32 values.
7537 EVT VT = N->getValueType(0);
7538 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7540 DebugLoc dl = N->getDebugLoc();
7541 SmallVector<SDValue, 8> Ops;
7542 unsigned NumElts = VT.getVectorNumElements();
7543 for (unsigned i = 0; i < NumElts; ++i) {
7544 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7546 // Make the DAGCombiner fold the bitcast.
7547 DCI.AddToWorklist(V.getNode());
7549 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7550 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7551 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7554 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7555 /// ISD::INSERT_VECTOR_ELT.
7556 static SDValue PerformInsertEltCombine(SDNode *N,
7557 TargetLowering::DAGCombinerInfo &DCI) {
7558 // Bitcast an i64 load inserted into a vector to f64.
7559 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7560 EVT VT = N->getValueType(0);
7561 SDNode *Elt = N->getOperand(1).getNode();
7562 if (VT.getVectorElementType() != MVT::i64 ||
7563 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7566 SelectionDAG &DAG = DCI.DAG;
7567 DebugLoc dl = N->getDebugLoc();
7568 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7569 VT.getVectorNumElements());
7570 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7571 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7572 // Make the DAGCombiner fold the bitcasts.
7573 DCI.AddToWorklist(Vec.getNode());
7574 DCI.AddToWorklist(V.getNode());
7575 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7576 Vec, V, N->getOperand(2));
7577 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7580 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7581 /// ISD::VECTOR_SHUFFLE.
7582 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7583 // The LLVM shufflevector instruction does not require the shuffle mask
7584 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7585 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
7586 // operands do not match the mask length, they are extended by concatenating
7587 // them with undef vectors. That is probably the right thing for other
7588 // targets, but for NEON it is better to concatenate two double-register
7589 // size vector operands into a single quad-register size vector. Do that
7590 // transformation here:
7591 // shuffle(concat(v1, undef), concat(v2, undef)) ->
7592 // shuffle(concat(v1, v2), undef)
7593 SDValue Op0 = N->getOperand(0);
7594 SDValue Op1 = N->getOperand(1);
7595 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7596 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7597 Op0.getNumOperands() != 2 ||
7598 Op1.getNumOperands() != 2)
7600 SDValue Concat0Op1 = Op0.getOperand(1);
7601 SDValue Concat1Op1 = Op1.getOperand(1);
7602 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7603 Concat1Op1.getOpcode() != ISD::UNDEF)
7605 // Skip the transformation if any of the types are illegal.
7606 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7607 EVT VT = N->getValueType(0);
7608 if (!TLI.isTypeLegal(VT) ||
7609 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7610 !TLI.isTypeLegal(Concat1Op1.getValueType()))
7613 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7614 Op0.getOperand(0), Op1.getOperand(0));
7615 // Translate the shuffle mask.
7616 SmallVector<int, 16> NewMask;
7617 unsigned NumElts = VT.getVectorNumElements();
7618 unsigned HalfElts = NumElts/2;
7619 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7620 for (unsigned n = 0; n < NumElts; ++n) {
7621 int MaskElt = SVN->getMaskElt(n);
7623 if (MaskElt < (int)HalfElts)
7625 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7626 NewElt = HalfElts + MaskElt - NumElts;
7627 NewMask.push_back(NewElt);
7629 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7630 DAG.getUNDEF(VT), NewMask.data());
7633 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7634 /// NEON load/store intrinsics to merge base address updates.
7635 static SDValue CombineBaseUpdate(SDNode *N,
7636 TargetLowering::DAGCombinerInfo &DCI) {
7637 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7640 SelectionDAG &DAG = DCI.DAG;
7641 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7642 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7643 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7644 SDValue Addr = N->getOperand(AddrOpIdx);
7646 // Search for a use of the address operand that is an increment.
7647 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7648 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7650 if (User->getOpcode() != ISD::ADD ||
7651 UI.getUse().getResNo() != Addr.getResNo())
7654 // Check that the add is independent of the load/store. Otherwise, folding
7655 // it would create a cycle.
7656 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7659 // Find the new opcode for the updating load/store.
7661 bool isLaneOp = false;
7662 unsigned NewOpc = 0;
7663 unsigned NumVecs = 0;
7665 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7667 default: llvm_unreachable("unexpected intrinsic for Neon base update");
7668 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
7670 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
7672 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
7674 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
7676 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7677 NumVecs = 2; isLaneOp = true; break;
7678 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7679 NumVecs = 3; isLaneOp = true; break;
7680 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7681 NumVecs = 4; isLaneOp = true; break;
7682 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
7683 NumVecs = 1; isLoad = false; break;
7684 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
7685 NumVecs = 2; isLoad = false; break;
7686 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
7687 NumVecs = 3; isLoad = false; break;
7688 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
7689 NumVecs = 4; isLoad = false; break;
7690 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7691 NumVecs = 2; isLoad = false; isLaneOp = true; break;
7692 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7693 NumVecs = 3; isLoad = false; isLaneOp = true; break;
7694 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7695 NumVecs = 4; isLoad = false; isLaneOp = true; break;
7699 switch (N->getOpcode()) {
7700 default: llvm_unreachable("unexpected opcode for Neon base update");
7701 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7702 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7703 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7707 // Find the size of memory referenced by the load/store.
7710 VecTy = N->getValueType(0);
7712 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7713 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7715 NumBytes /= VecTy.getVectorNumElements();
7717 // If the increment is a constant, it must match the memory ref size.
7718 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7719 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7720 uint64_t IncVal = CInc->getZExtValue();
7721 if (IncVal != NumBytes)
7723 } else if (NumBytes >= 3 * 16) {
7724 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7725 // separate instructions that make it harder to use a non-constant update.
7729 // Create the new updating load/store node.
7731 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7733 for (n = 0; n < NumResultVecs; ++n)
7735 Tys[n++] = MVT::i32;
7736 Tys[n] = MVT::Other;
7737 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7738 SmallVector<SDValue, 8> Ops;
7739 Ops.push_back(N->getOperand(0)); // incoming chain
7740 Ops.push_back(N->getOperand(AddrOpIdx));
7742 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7743 Ops.push_back(N->getOperand(i));
7745 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7746 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7747 Ops.data(), Ops.size(),
7748 MemInt->getMemoryVT(),
7749 MemInt->getMemOperand());
7752 std::vector<SDValue> NewResults;
7753 for (unsigned i = 0; i < NumResultVecs; ++i) {
7754 NewResults.push_back(SDValue(UpdN.getNode(), i));
7756 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7757 DCI.CombineTo(N, NewResults);
7758 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7765 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7766 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7767 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
7769 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7770 SelectionDAG &DAG = DCI.DAG;
7771 EVT VT = N->getValueType(0);
7772 // vldN-dup instructions only support 64-bit vectors for N > 1.
7773 if (!VT.is64BitVector())
7776 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7777 SDNode *VLD = N->getOperand(0).getNode();
7778 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7780 unsigned NumVecs = 0;
7781 unsigned NewOpc = 0;
7782 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7783 if (IntNo == Intrinsic::arm_neon_vld2lane) {
7785 NewOpc = ARMISD::VLD2DUP;
7786 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7788 NewOpc = ARMISD::VLD3DUP;
7789 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7791 NewOpc = ARMISD::VLD4DUP;
7796 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7797 // numbers match the load.
7798 unsigned VLDLaneNo =
7799 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7800 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7802 // Ignore uses of the chain result.
7803 if (UI.getUse().getResNo() == NumVecs)
7806 if (User->getOpcode() != ARMISD::VDUPLANE ||
7807 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7811 // Create the vldN-dup node.
7814 for (n = 0; n < NumVecs; ++n)
7816 Tys[n] = MVT::Other;
7817 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7818 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7819 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7820 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7821 Ops, 2, VLDMemInt->getMemoryVT(),
7822 VLDMemInt->getMemOperand());
7825 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7827 unsigned ResNo = UI.getUse().getResNo();
7828 // Ignore uses of the chain result.
7829 if (ResNo == NumVecs)
7832 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7835 // Now the vldN-lane intrinsic is dead except for its chain result.
7836 // Update uses of the chain.
7837 std::vector<SDValue> VLDDupResults;
7838 for (unsigned n = 0; n < NumVecs; ++n)
7839 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7840 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7841 DCI.CombineTo(VLD, VLDDupResults);
7846 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7847 /// ARMISD::VDUPLANE.
7848 static SDValue PerformVDUPLANECombine(SDNode *N,
7849 TargetLowering::DAGCombinerInfo &DCI) {
7850 SDValue Op = N->getOperand(0);
7852 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7853 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7854 if (CombineVLDDUP(N, DCI))
7855 return SDValue(N, 0);
7857 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7858 // redundant. Ignore bit_converts for now; element sizes are checked below.
7859 while (Op.getOpcode() == ISD::BITCAST)
7860 Op = Op.getOperand(0);
7861 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7864 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7865 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7866 // The canonical VMOV for a zero vector uses a 32-bit element size.
7867 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7869 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7871 EVT VT = N->getValueType(0);
7872 if (EltSize > VT.getVectorElementType().getSizeInBits())
7875 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7878 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7879 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7880 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7884 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7886 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7891 APFloat APF = C->getValueAPF();
7892 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7893 != APFloat::opOK || !isExact)
7896 c0 = (I == 0) ? cN : c0;
7897 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7904 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7905 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7906 /// when the VMUL has a constant operand that is a power of 2.
7908 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7909 /// vmul.f32 d16, d17, d16
7910 /// vcvt.s32.f32 d16, d16
7912 /// vcvt.s32.f32 d16, d16, #3
7913 static SDValue PerformVCVTCombine(SDNode *N,
7914 TargetLowering::DAGCombinerInfo &DCI,
7915 const ARMSubtarget *Subtarget) {
7916 SelectionDAG &DAG = DCI.DAG;
7917 SDValue Op = N->getOperand(0);
7919 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7920 Op.getOpcode() != ISD::FMUL)
7924 SDValue N0 = Op->getOperand(0);
7925 SDValue ConstVec = Op->getOperand(1);
7926 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7928 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7929 !isConstVecPow2(ConstVec, isSigned, C))
7932 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7933 Intrinsic::arm_neon_vcvtfp2fxu;
7934 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7936 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7937 DAG.getConstant(Log2_64(C), MVT::i32));
7940 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7941 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7942 /// when the VDIV has a constant operand that is a power of 2.
7944 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7945 /// vcvt.f32.s32 d16, d16
7946 /// vdiv.f32 d16, d17, d16
7948 /// vcvt.f32.s32 d16, d16, #3
7949 static SDValue PerformVDIVCombine(SDNode *N,
7950 TargetLowering::DAGCombinerInfo &DCI,
7951 const ARMSubtarget *Subtarget) {
7952 SelectionDAG &DAG = DCI.DAG;
7953 SDValue Op = N->getOperand(0);
7954 unsigned OpOpcode = Op.getNode()->getOpcode();
7956 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7957 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7961 SDValue ConstVec = N->getOperand(1);
7962 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7964 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7965 !isConstVecPow2(ConstVec, isSigned, C))
7968 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7969 Intrinsic::arm_neon_vcvtfxu2fp;
7970 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7972 DAG.getConstant(IntrinsicOpcode, MVT::i32),
7973 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7976 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7977 /// operand of a vector shift operation, where all the elements of the
7978 /// build_vector must have the same constant integer value.
7979 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7980 // Ignore bit_converts.
7981 while (Op.getOpcode() == ISD::BITCAST)
7982 Op = Op.getOperand(0);
7983 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7984 APInt SplatBits, SplatUndef;
7985 unsigned SplatBitSize;
7987 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7988 HasAnyUndefs, ElementBits) ||
7989 SplatBitSize > ElementBits)
7991 Cnt = SplatBits.getSExtValue();
7995 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7996 /// operand of a vector shift left operation. That value must be in the range:
7997 /// 0 <= Value < ElementBits for a left shift; or
7998 /// 0 <= Value <= ElementBits for a long left shift.
7999 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8000 assert(VT.isVector() && "vector shift count is not a vector type");
8001 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8002 if (! getVShiftImm(Op, ElementBits, Cnt))
8004 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8007 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8008 /// operand of a vector shift right operation. For a shift opcode, the value
8009 /// is positive, but for an intrinsic the value count must be negative. The
8010 /// absolute value must be in the range:
8011 /// 1 <= |Value| <= ElementBits for a right shift; or
8012 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8013 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8015 assert(VT.isVector() && "vector shift count is not a vector type");
8016 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8017 if (! getVShiftImm(Op, ElementBits, Cnt))
8021 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8024 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8025 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8026 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8029 // Don't do anything for most intrinsics.
8032 // Vector shifts: check for immediate versions and lower them.
8033 // Note: This is done during DAG combining instead of DAG legalizing because
8034 // the build_vectors for 64-bit vector element shift counts are generally
8035 // not legal, and it is hard to see their values after they get legalized to
8036 // loads from a constant pool.
8037 case Intrinsic::arm_neon_vshifts:
8038 case Intrinsic::arm_neon_vshiftu:
8039 case Intrinsic::arm_neon_vshiftls:
8040 case Intrinsic::arm_neon_vshiftlu:
8041 case Intrinsic::arm_neon_vshiftn:
8042 case Intrinsic::arm_neon_vrshifts:
8043 case Intrinsic::arm_neon_vrshiftu:
8044 case Intrinsic::arm_neon_vrshiftn:
8045 case Intrinsic::arm_neon_vqshifts:
8046 case Intrinsic::arm_neon_vqshiftu:
8047 case Intrinsic::arm_neon_vqshiftsu:
8048 case Intrinsic::arm_neon_vqshiftns:
8049 case Intrinsic::arm_neon_vqshiftnu:
8050 case Intrinsic::arm_neon_vqshiftnsu:
8051 case Intrinsic::arm_neon_vqrshiftns:
8052 case Intrinsic::arm_neon_vqrshiftnu:
8053 case Intrinsic::arm_neon_vqrshiftnsu: {
8054 EVT VT = N->getOperand(1).getValueType();
8056 unsigned VShiftOpc = 0;
8059 case Intrinsic::arm_neon_vshifts:
8060 case Intrinsic::arm_neon_vshiftu:
8061 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8062 VShiftOpc = ARMISD::VSHL;
8065 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8066 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8067 ARMISD::VSHRs : ARMISD::VSHRu);
8072 case Intrinsic::arm_neon_vshiftls:
8073 case Intrinsic::arm_neon_vshiftlu:
8074 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8076 llvm_unreachable("invalid shift count for vshll intrinsic");
8078 case Intrinsic::arm_neon_vrshifts:
8079 case Intrinsic::arm_neon_vrshiftu:
8080 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8084 case Intrinsic::arm_neon_vqshifts:
8085 case Intrinsic::arm_neon_vqshiftu:
8086 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8090 case Intrinsic::arm_neon_vqshiftsu:
8091 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8093 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8095 case Intrinsic::arm_neon_vshiftn:
8096 case Intrinsic::arm_neon_vrshiftn:
8097 case Intrinsic::arm_neon_vqshiftns:
8098 case Intrinsic::arm_neon_vqshiftnu:
8099 case Intrinsic::arm_neon_vqshiftnsu:
8100 case Intrinsic::arm_neon_vqrshiftns:
8101 case Intrinsic::arm_neon_vqrshiftnu:
8102 case Intrinsic::arm_neon_vqrshiftnsu:
8103 // Narrowing shifts require an immediate right shift.
8104 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8106 llvm_unreachable("invalid shift count for narrowing vector shift "
8110 llvm_unreachable("unhandled vector shift");
8114 case Intrinsic::arm_neon_vshifts:
8115 case Intrinsic::arm_neon_vshiftu:
8116 // Opcode already set above.
8118 case Intrinsic::arm_neon_vshiftls:
8119 case Intrinsic::arm_neon_vshiftlu:
8120 if (Cnt == VT.getVectorElementType().getSizeInBits())
8121 VShiftOpc = ARMISD::VSHLLi;
8123 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8124 ARMISD::VSHLLs : ARMISD::VSHLLu);
8126 case Intrinsic::arm_neon_vshiftn:
8127 VShiftOpc = ARMISD::VSHRN; break;
8128 case Intrinsic::arm_neon_vrshifts:
8129 VShiftOpc = ARMISD::VRSHRs; break;
8130 case Intrinsic::arm_neon_vrshiftu:
8131 VShiftOpc = ARMISD::VRSHRu; break;
8132 case Intrinsic::arm_neon_vrshiftn:
8133 VShiftOpc = ARMISD::VRSHRN; break;
8134 case Intrinsic::arm_neon_vqshifts:
8135 VShiftOpc = ARMISD::VQSHLs; break;
8136 case Intrinsic::arm_neon_vqshiftu:
8137 VShiftOpc = ARMISD::VQSHLu; break;
8138 case Intrinsic::arm_neon_vqshiftsu:
8139 VShiftOpc = ARMISD::VQSHLsu; break;
8140 case Intrinsic::arm_neon_vqshiftns:
8141 VShiftOpc = ARMISD::VQSHRNs; break;
8142 case Intrinsic::arm_neon_vqshiftnu:
8143 VShiftOpc = ARMISD::VQSHRNu; break;
8144 case Intrinsic::arm_neon_vqshiftnsu:
8145 VShiftOpc = ARMISD::VQSHRNsu; break;
8146 case Intrinsic::arm_neon_vqrshiftns:
8147 VShiftOpc = ARMISD::VQRSHRNs; break;
8148 case Intrinsic::arm_neon_vqrshiftnu:
8149 VShiftOpc = ARMISD::VQRSHRNu; break;
8150 case Intrinsic::arm_neon_vqrshiftnsu:
8151 VShiftOpc = ARMISD::VQRSHRNsu; break;
8154 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8155 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8158 case Intrinsic::arm_neon_vshiftins: {
8159 EVT VT = N->getOperand(1).getValueType();
8161 unsigned VShiftOpc = 0;
8163 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8164 VShiftOpc = ARMISD::VSLI;
8165 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8166 VShiftOpc = ARMISD::VSRI;
8168 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8171 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8172 N->getOperand(1), N->getOperand(2),
8173 DAG.getConstant(Cnt, MVT::i32));
8176 case Intrinsic::arm_neon_vqrshifts:
8177 case Intrinsic::arm_neon_vqrshiftu:
8178 // No immediate versions of these to check for.
8185 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8186 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8187 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8188 /// vector element shift counts are generally not legal, and it is hard to see
8189 /// their values after they get legalized to loads from a constant pool.
8190 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8191 const ARMSubtarget *ST) {
8192 EVT VT = N->getValueType(0);
8193 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8194 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8195 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8196 SDValue N1 = N->getOperand(1);
8197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8198 SDValue N0 = N->getOperand(0);
8199 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8200 DAG.MaskedValueIsZero(N0.getOperand(0),
8201 APInt::getHighBitsSet(32, 16)))
8202 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8206 // Nothing to be done for scalar shifts.
8207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8208 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8211 assert(ST->hasNEON() && "unexpected vector shift");
8214 switch (N->getOpcode()) {
8215 default: llvm_unreachable("unexpected shift opcode");
8218 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8219 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8220 DAG.getConstant(Cnt, MVT::i32));
8225 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8226 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8227 ARMISD::VSHRs : ARMISD::VSHRu);
8228 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8229 DAG.getConstant(Cnt, MVT::i32));
8235 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8236 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8237 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8238 const ARMSubtarget *ST) {
8239 SDValue N0 = N->getOperand(0);
8241 // Check for sign- and zero-extensions of vector extract operations of 8-
8242 // and 16-bit vector elements. NEON supports these directly. They are
8243 // handled during DAG combining because type legalization will promote them
8244 // to 32-bit types and it is messy to recognize the operations after that.
8245 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8246 SDValue Vec = N0.getOperand(0);
8247 SDValue Lane = N0.getOperand(1);
8248 EVT VT = N->getValueType(0);
8249 EVT EltVT = N0.getValueType();
8250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8252 if (VT == MVT::i32 &&
8253 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8254 TLI.isTypeLegal(Vec.getValueType()) &&
8255 isa<ConstantSDNode>(Lane)) {
8258 switch (N->getOpcode()) {
8259 default: llvm_unreachable("unexpected opcode");
8260 case ISD::SIGN_EXTEND:
8261 Opc = ARMISD::VGETLANEs;
8263 case ISD::ZERO_EXTEND:
8264 case ISD::ANY_EXTEND:
8265 Opc = ARMISD::VGETLANEu;
8268 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8275 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8276 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8277 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8278 const ARMSubtarget *ST) {
8279 // If the target supports NEON, try to use vmax/vmin instructions for f32
8280 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8281 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8282 // a NaN; only do the transformation when it matches that behavior.
8284 // For now only do this when using NEON for FP operations; if using VFP, it
8285 // is not obvious that the benefit outweighs the cost of switching to the
8287 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8288 N->getValueType(0) != MVT::f32)
8291 SDValue CondLHS = N->getOperand(0);
8292 SDValue CondRHS = N->getOperand(1);
8293 SDValue LHS = N->getOperand(2);
8294 SDValue RHS = N->getOperand(3);
8295 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8297 unsigned Opcode = 0;
8299 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8300 IsReversed = false; // x CC y ? x : y
8301 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8302 IsReversed = true ; // x CC y ? y : x
8316 // If LHS is NaN, an ordered comparison will be false and the result will
8317 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8318 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8319 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8320 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8322 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8323 // will return -0, so vmin can only be used for unsafe math or if one of
8324 // the operands is known to be nonzero.
8325 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8326 !DAG.getTarget().Options.UnsafeFPMath &&
8327 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8329 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8338 // If LHS is NaN, an ordered comparison will be false and the result will
8339 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8340 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8341 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8342 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8344 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8345 // will return +0, so vmax can only be used for unsafe math or if one of
8346 // the operands is known to be nonzero.
8347 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8348 !DAG.getTarget().Options.UnsafeFPMath &&
8349 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8351 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8357 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8360 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8362 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8363 SDValue Cmp = N->getOperand(4);
8364 if (Cmp.getOpcode() != ARMISD::CMPZ)
8365 // Only looking at EQ and NE cases.
8368 EVT VT = N->getValueType(0);
8369 DebugLoc dl = N->getDebugLoc();
8370 SDValue LHS = Cmp.getOperand(0);
8371 SDValue RHS = Cmp.getOperand(1);
8372 SDValue FalseVal = N->getOperand(0);
8373 SDValue TrueVal = N->getOperand(1);
8374 SDValue ARMcc = N->getOperand(2);
8375 ARMCC::CondCodes CC =
8376 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8394 /// FIXME: Turn this into a target neutral optimization?
8396 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8397 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8398 N->getOperand(3), Cmp);
8399 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8401 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8402 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8403 N->getOperand(3), NewCmp);
8406 if (Res.getNode()) {
8407 APInt KnownZero, KnownOne;
8408 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8409 // Capture demanded bits information that would be otherwise lost.
8410 if (KnownZero == 0xfffffffe)
8411 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8412 DAG.getValueType(MVT::i1));
8413 else if (KnownZero == 0xffffff00)
8414 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8415 DAG.getValueType(MVT::i8));
8416 else if (KnownZero == 0xffff0000)
8417 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8418 DAG.getValueType(MVT::i16));
8424 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8425 DAGCombinerInfo &DCI) const {
8426 switch (N->getOpcode()) {
8428 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8429 case ISD::SUB: return PerformSUBCombine(N, DCI);
8430 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8431 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8432 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8433 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8434 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8435 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8436 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8437 case ISD::STORE: return PerformSTORECombine(N, DCI);
8438 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8439 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8440 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8441 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8442 case ISD::FP_TO_SINT:
8443 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8444 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8445 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8448 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8449 case ISD::SIGN_EXTEND:
8450 case ISD::ZERO_EXTEND:
8451 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8452 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8453 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8454 case ARMISD::VLD2DUP:
8455 case ARMISD::VLD3DUP:
8456 case ARMISD::VLD4DUP:
8457 return CombineBaseUpdate(N, DCI);
8458 case ISD::INTRINSIC_VOID:
8459 case ISD::INTRINSIC_W_CHAIN:
8460 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8461 case Intrinsic::arm_neon_vld1:
8462 case Intrinsic::arm_neon_vld2:
8463 case Intrinsic::arm_neon_vld3:
8464 case Intrinsic::arm_neon_vld4:
8465 case Intrinsic::arm_neon_vld2lane:
8466 case Intrinsic::arm_neon_vld3lane:
8467 case Intrinsic::arm_neon_vld4lane:
8468 case Intrinsic::arm_neon_vst1:
8469 case Intrinsic::arm_neon_vst2:
8470 case Intrinsic::arm_neon_vst3:
8471 case Intrinsic::arm_neon_vst4:
8472 case Intrinsic::arm_neon_vst2lane:
8473 case Intrinsic::arm_neon_vst3lane:
8474 case Intrinsic::arm_neon_vst4lane:
8475 return CombineBaseUpdate(N, DCI);
8483 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8485 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8488 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8489 if (!Subtarget->allowsUnalignedMem())
8492 switch (VT.getSimpleVT().SimpleTy) {
8499 // FIXME: VLD1 etc with standard alignment is legal.
8503 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8504 unsigned AlignCheck) {
8505 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8506 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8509 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8510 unsigned DstAlign, unsigned SrcAlign,
8513 MachineFunction &MF) const {
8514 const Function *F = MF.getFunction();
8516 // See if we can use NEON instructions for this...
8518 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8519 Subtarget->hasNEON()) {
8520 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8522 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8527 // Lowering to i32/i16 if the size permits.
8530 } else if (Size >= 2) {
8534 // Let the target-independent logic figure it out.
8538 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8543 switch (VT.getSimpleVT().SimpleTy) {
8544 default: return false;
8559 if ((V & (Scale - 1)) != 0)
8562 return V == (V & ((1LL << 5) - 1));
8565 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8566 const ARMSubtarget *Subtarget) {
8573 switch (VT.getSimpleVT().SimpleTy) {
8574 default: return false;
8579 // + imm12 or - imm8
8581 return V == (V & ((1LL << 8) - 1));
8582 return V == (V & ((1LL << 12) - 1));
8585 // Same as ARM mode. FIXME: NEON?
8586 if (!Subtarget->hasVFP2())
8591 return V == (V & ((1LL << 8) - 1));
8595 /// isLegalAddressImmediate - Return true if the integer value can be used
8596 /// as the offset of the target addressing mode for load / store of the
8598 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8599 const ARMSubtarget *Subtarget) {
8606 if (Subtarget->isThumb1Only())
8607 return isLegalT1AddressImmediate(V, VT);
8608 else if (Subtarget->isThumb2())
8609 return isLegalT2AddressImmediate(V, VT, Subtarget);
8614 switch (VT.getSimpleVT().SimpleTy) {
8615 default: return false;
8620 return V == (V & ((1LL << 12) - 1));
8623 return V == (V & ((1LL << 8) - 1));
8626 if (!Subtarget->hasVFP2()) // FIXME: NEON?
8631 return V == (V & ((1LL << 8) - 1));
8635 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8637 int Scale = AM.Scale;
8641 switch (VT.getSimpleVT().SimpleTy) {
8642 default: return false;
8651 return Scale == 2 || Scale == 4 || Scale == 8;
8654 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8658 // Note, we allow "void" uses (basically, uses that aren't loads or
8659 // stores), because arm allows folding a scale into many arithmetic
8660 // operations. This should be made more precise and revisited later.
8662 // Allow r << imm, but the imm has to be a multiple of two.
8663 if (Scale & 1) return false;
8664 return isPowerOf2_32(Scale);
8668 /// isLegalAddressingMode - Return true if the addressing mode represented
8669 /// by AM is legal for this target, for a load/store of the specified type.
8670 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8672 EVT VT = getValueType(Ty, true);
8673 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8676 // Can never fold addr of global into load/store.
8681 case 0: // no scale reg, must be "r+i" or "r", or "i".
8684 if (Subtarget->isThumb1Only())
8688 // ARM doesn't support any R+R*scale+imm addr modes.
8695 if (Subtarget->isThumb2())
8696 return isLegalT2ScaledAddressingMode(AM, VT);
8698 int Scale = AM.Scale;
8699 switch (VT.getSimpleVT().SimpleTy) {
8700 default: return false;
8704 if (Scale < 0) Scale = -Scale;
8708 return isPowerOf2_32(Scale & ~1);
8712 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8717 // Note, we allow "void" uses (basically, uses that aren't loads or
8718 // stores), because arm allows folding a scale into many arithmetic
8719 // operations. This should be made more precise and revisited later.
8721 // Allow r << imm, but the imm has to be a multiple of two.
8722 if (Scale & 1) return false;
8723 return isPowerOf2_32(Scale);
8729 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8730 /// icmp immediate, that is the target has icmp instructions which can compare
8731 /// a register against the immediate without having to materialize the
8732 /// immediate into a register.
8733 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8734 // Thumb2 and ARM modes can use cmn for negative immediates.
8735 if (!Subtarget->isThumb())
8736 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
8737 if (Subtarget->isThumb2())
8738 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
8739 // Thumb1 doesn't have cmn, and only 8-bit immediates.
8740 return Imm >= 0 && Imm <= 255;
8743 /// isLegalAddImmediate - Return true if the specified immediate is legal
8744 /// add immediate, that is the target has add instructions which can add
8745 /// a register with the immediate without having to materialize the
8746 /// immediate into a register.
8747 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8748 return ARM_AM::getSOImmVal(Imm) != -1;
8751 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8752 bool isSEXTLoad, SDValue &Base,
8753 SDValue &Offset, bool &isInc,
8754 SelectionDAG &DAG) {
8755 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8758 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8760 Base = Ptr->getOperand(0);
8761 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8762 int RHSC = (int)RHS->getZExtValue();
8763 if (RHSC < 0 && RHSC > -256) {
8764 assert(Ptr->getOpcode() == ISD::ADD);
8766 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8770 isInc = (Ptr->getOpcode() == ISD::ADD);
8771 Offset = Ptr->getOperand(1);
8773 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8775 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8776 int RHSC = (int)RHS->getZExtValue();
8777 if (RHSC < 0 && RHSC > -0x1000) {
8778 assert(Ptr->getOpcode() == ISD::ADD);
8780 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8781 Base = Ptr->getOperand(0);
8786 if (Ptr->getOpcode() == ISD::ADD) {
8788 ARM_AM::ShiftOpc ShOpcVal=
8789 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8790 if (ShOpcVal != ARM_AM::no_shift) {
8791 Base = Ptr->getOperand(1);
8792 Offset = Ptr->getOperand(0);
8794 Base = Ptr->getOperand(0);
8795 Offset = Ptr->getOperand(1);
8800 isInc = (Ptr->getOpcode() == ISD::ADD);
8801 Base = Ptr->getOperand(0);
8802 Offset = Ptr->getOperand(1);
8806 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8810 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8811 bool isSEXTLoad, SDValue &Base,
8812 SDValue &Offset, bool &isInc,
8813 SelectionDAG &DAG) {
8814 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8817 Base = Ptr->getOperand(0);
8818 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8819 int RHSC = (int)RHS->getZExtValue();
8820 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8821 assert(Ptr->getOpcode() == ISD::ADD);
8823 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8825 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8826 isInc = Ptr->getOpcode() == ISD::ADD;
8827 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8835 /// getPreIndexedAddressParts - returns true by value, base pointer and
8836 /// offset pointer and addressing mode by reference if the node's address
8837 /// can be legally represented as pre-indexed load / store address.
8839 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8841 ISD::MemIndexedMode &AM,
8842 SelectionDAG &DAG) const {
8843 if (Subtarget->isThumb1Only())
8848 bool isSEXTLoad = false;
8849 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8850 Ptr = LD->getBasePtr();
8851 VT = LD->getMemoryVT();
8852 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8853 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8854 Ptr = ST->getBasePtr();
8855 VT = ST->getMemoryVT();
8860 bool isLegal = false;
8861 if (Subtarget->isThumb2())
8862 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8863 Offset, isInc, DAG);
8865 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8866 Offset, isInc, DAG);
8870 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8874 /// getPostIndexedAddressParts - returns true by value, base pointer and
8875 /// offset pointer and addressing mode by reference if this node can be
8876 /// combined with a load / store to form a post-indexed load / store.
8877 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8880 ISD::MemIndexedMode &AM,
8881 SelectionDAG &DAG) const {
8882 if (Subtarget->isThumb1Only())
8887 bool isSEXTLoad = false;
8888 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8889 VT = LD->getMemoryVT();
8890 Ptr = LD->getBasePtr();
8891 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8892 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8893 VT = ST->getMemoryVT();
8894 Ptr = ST->getBasePtr();
8899 bool isLegal = false;
8900 if (Subtarget->isThumb2())
8901 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8904 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8910 // Swap base ptr and offset to catch more post-index load / store when
8911 // it's legal. In Thumb2 mode, offset must be an immediate.
8912 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8913 !Subtarget->isThumb2())
8914 std::swap(Base, Offset);
8916 // Post-indexed load / store update the base pointer.
8921 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8925 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8928 const SelectionDAG &DAG,
8929 unsigned Depth) const {
8930 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
8931 switch (Op.getOpcode()) {
8933 case ARMISD::CMOV: {
8934 // Bits are known zero/one if known on the LHS and RHS.
8935 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
8936 if (KnownZero == 0 && KnownOne == 0) return;
8938 APInt KnownZeroRHS, KnownOneRHS;
8939 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
8940 KnownZero &= KnownZeroRHS;
8941 KnownOne &= KnownOneRHS;
8947 //===----------------------------------------------------------------------===//
8948 // ARM Inline Assembly Support
8949 //===----------------------------------------------------------------------===//
8951 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8952 // Looking for "rev" which is V6+.
8953 if (!Subtarget->hasV6Ops())
8956 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8957 std::string AsmStr = IA->getAsmString();
8958 SmallVector<StringRef, 4> AsmPieces;
8959 SplitString(AsmStr, AsmPieces, ";\n");
8961 switch (AsmPieces.size()) {
8962 default: return false;
8964 AsmStr = AsmPieces[0];
8966 SplitString(AsmStr, AsmPieces, " \t,");
8969 if (AsmPieces.size() == 3 &&
8970 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8971 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8972 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8973 if (Ty && Ty->getBitWidth() == 32)
8974 return IntrinsicLowering::LowerToByteSwap(CI);
8982 /// getConstraintType - Given a constraint letter, return the type of
8983 /// constraint it is for this target.
8984 ARMTargetLowering::ConstraintType
8985 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8986 if (Constraint.size() == 1) {
8987 switch (Constraint[0]) {
8989 case 'l': return C_RegisterClass;
8990 case 'w': return C_RegisterClass;
8991 case 'h': return C_RegisterClass;
8992 case 'x': return C_RegisterClass;
8993 case 't': return C_RegisterClass;
8994 case 'j': return C_Other; // Constant for movw.
8995 // An address with a single base register. Due to the way we
8996 // currently handle addresses it is the same as an 'r' memory constraint.
8997 case 'Q': return C_Memory;
8999 } else if (Constraint.size() == 2) {
9000 switch (Constraint[0]) {
9002 // All 'U+' constraints are addresses.
9003 case 'U': return C_Memory;
9006 return TargetLowering::getConstraintType(Constraint);
9009 /// Examine constraint type and operand type and determine a weight value.
9010 /// This object must already have been set up with the operand type
9011 /// and the current alternative constraint selected.
9012 TargetLowering::ConstraintWeight
9013 ARMTargetLowering::getSingleConstraintMatchWeight(
9014 AsmOperandInfo &info, const char *constraint) const {
9015 ConstraintWeight weight = CW_Invalid;
9016 Value *CallOperandVal = info.CallOperandVal;
9017 // If we don't have a value, we can't do a match,
9018 // but allow it at the lowest weight.
9019 if (CallOperandVal == NULL)
9021 Type *type = CallOperandVal->getType();
9022 // Look at the constraint type.
9023 switch (*constraint) {
9025 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9028 if (type->isIntegerTy()) {
9029 if (Subtarget->isThumb())
9030 weight = CW_SpecificReg;
9032 weight = CW_Register;
9036 if (type->isFloatingPointTy())
9037 weight = CW_Register;
9043 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9045 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9047 if (Constraint.size() == 1) {
9048 // GCC ARM Constraint Letters
9049 switch (Constraint[0]) {
9050 case 'l': // Low regs or general regs.
9051 if (Subtarget->isThumb())
9052 return RCPair(0U, &ARM::tGPRRegClass);
9053 return RCPair(0U, &ARM::GPRRegClass);
9054 case 'h': // High regs or no regs.
9055 if (Subtarget->isThumb())
9056 return RCPair(0U, &ARM::hGPRRegClass);
9059 return RCPair(0U, &ARM::GPRRegClass);
9062 return RCPair(0U, &ARM::SPRRegClass);
9063 if (VT.getSizeInBits() == 64)
9064 return RCPair(0U, &ARM::DPRRegClass);
9065 if (VT.getSizeInBits() == 128)
9066 return RCPair(0U, &ARM::QPRRegClass);
9070 return RCPair(0U, &ARM::SPR_8RegClass);
9071 if (VT.getSizeInBits() == 64)
9072 return RCPair(0U, &ARM::DPR_8RegClass);
9073 if (VT.getSizeInBits() == 128)
9074 return RCPair(0U, &ARM::QPR_8RegClass);
9078 return RCPair(0U, &ARM::SPRRegClass);
9082 if (StringRef("{cc}").equals_lower(Constraint))
9083 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9085 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9088 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9089 /// vector. If it is invalid, don't add anything to Ops.
9090 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9091 std::string &Constraint,
9092 std::vector<SDValue>&Ops,
9093 SelectionDAG &DAG) const {
9094 SDValue Result(0, 0);
9096 // Currently only support length 1 constraints.
9097 if (Constraint.length() != 1) return;
9099 char ConstraintLetter = Constraint[0];
9100 switch (ConstraintLetter) {
9103 case 'I': case 'J': case 'K': case 'L':
9104 case 'M': case 'N': case 'O':
9105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9109 int64_t CVal64 = C->getSExtValue();
9110 int CVal = (int) CVal64;
9111 // None of these constraints allow values larger than 32 bits. Check
9112 // that the value fits in an int.
9116 switch (ConstraintLetter) {
9118 // Constant suitable for movw, must be between 0 and
9120 if (Subtarget->hasV6T2Ops())
9121 if (CVal >= 0 && CVal <= 65535)
9125 if (Subtarget->isThumb1Only()) {
9126 // This must be a constant between 0 and 255, for ADD
9128 if (CVal >= 0 && CVal <= 255)
9130 } else if (Subtarget->isThumb2()) {
9131 // A constant that can be used as an immediate value in a
9132 // data-processing instruction.
9133 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9136 // A constant that can be used as an immediate value in a
9137 // data-processing instruction.
9138 if (ARM_AM::getSOImmVal(CVal) != -1)
9144 if (Subtarget->isThumb()) { // FIXME thumb2
9145 // This must be a constant between -255 and -1, for negated ADD
9146 // immediates. This can be used in GCC with an "n" modifier that
9147 // prints the negated value, for use with SUB instructions. It is
9148 // not useful otherwise but is implemented for compatibility.
9149 if (CVal >= -255 && CVal <= -1)
9152 // This must be a constant between -4095 and 4095. It is not clear
9153 // what this constraint is intended for. Implemented for
9154 // compatibility with GCC.
9155 if (CVal >= -4095 && CVal <= 4095)
9161 if (Subtarget->isThumb1Only()) {
9162 // A 32-bit value where only one byte has a nonzero value. Exclude
9163 // zero to match GCC. This constraint is used by GCC internally for
9164 // constants that can be loaded with a move/shift combination.
9165 // It is not useful otherwise but is implemented for compatibility.
9166 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9168 } else if (Subtarget->isThumb2()) {
9169 // A constant whose bitwise inverse can be used as an immediate
9170 // value in a data-processing instruction. This can be used in GCC
9171 // with a "B" modifier that prints the inverted value, for use with
9172 // BIC and MVN instructions. It is not useful otherwise but is
9173 // implemented for compatibility.
9174 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9177 // A constant whose bitwise inverse can be used as an immediate
9178 // value in a data-processing instruction. This can be used in GCC
9179 // with a "B" modifier that prints the inverted value, for use with
9180 // BIC and MVN instructions. It is not useful otherwise but is
9181 // implemented for compatibility.
9182 if (ARM_AM::getSOImmVal(~CVal) != -1)
9188 if (Subtarget->isThumb1Only()) {
9189 // This must be a constant between -7 and 7,
9190 // for 3-operand ADD/SUB immediate instructions.
9191 if (CVal >= -7 && CVal < 7)
9193 } else if (Subtarget->isThumb2()) {
9194 // A constant whose negation can be used as an immediate value in a
9195 // data-processing instruction. This can be used in GCC with an "n"
9196 // modifier that prints the negated value, for use with SUB
9197 // instructions. It is not useful otherwise but is implemented for
9199 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9202 // A constant whose negation can be used as an immediate value in a
9203 // data-processing instruction. This can be used in GCC with an "n"
9204 // modifier that prints the negated value, for use with SUB
9205 // instructions. It is not useful otherwise but is implemented for
9207 if (ARM_AM::getSOImmVal(-CVal) != -1)
9213 if (Subtarget->isThumb()) { // FIXME thumb2
9214 // This must be a multiple of 4 between 0 and 1020, for
9215 // ADD sp + immediate.
9216 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9219 // A power of two or a constant between 0 and 32. This is used in
9220 // GCC for the shift amount on shifted register operands, but it is
9221 // useful in general for any shift amounts.
9222 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9228 if (Subtarget->isThumb()) { // FIXME thumb2
9229 // This must be a constant between 0 and 31, for shift amounts.
9230 if (CVal >= 0 && CVal <= 31)
9236 if (Subtarget->isThumb()) { // FIXME thumb2
9237 // This must be a multiple of 4 between -508 and 508, for
9238 // ADD/SUB sp = sp + immediate.
9239 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9244 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9248 if (Result.getNode()) {
9249 Ops.push_back(Result);
9252 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9256 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9257 // The ARM target isn't yet aware of offsets.
9261 bool ARM::isBitFieldInvertedMask(unsigned v) {
9262 if (v == 0xffffffff)
9264 // there can be 1's on either or both "outsides", all the "inside"
9266 unsigned int lsb = 0, msb = 31;
9267 while (v & (1 << msb)) --msb;
9268 while (v & (1 << lsb)) ++lsb;
9269 for (unsigned int i = lsb; i <= msb; ++i) {
9276 /// isFPImmLegal - Returns true if the target can instruction select the
9277 /// specified FP immediate natively. If false, the legalizer will
9278 /// materialize the FP immediate as a load from a constant pool.
9279 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9280 if (!Subtarget->hasVFP3())
9283 return ARM_AM::getFP32Imm(Imm) != -1;
9285 return ARM_AM::getFP64Imm(Imm) != -1;
9289 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9290 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9291 /// specified in the intrinsic calls.
9292 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9294 unsigned Intrinsic) const {
9295 switch (Intrinsic) {
9296 case Intrinsic::arm_neon_vld1:
9297 case Intrinsic::arm_neon_vld2:
9298 case Intrinsic::arm_neon_vld3:
9299 case Intrinsic::arm_neon_vld4:
9300 case Intrinsic::arm_neon_vld2lane:
9301 case Intrinsic::arm_neon_vld3lane:
9302 case Intrinsic::arm_neon_vld4lane: {
9303 Info.opc = ISD::INTRINSIC_W_CHAIN;
9304 // Conservatively set memVT to the entire set of vectors loaded.
9305 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9306 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9307 Info.ptrVal = I.getArgOperand(0);
9309 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9310 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9311 Info.vol = false; // volatile loads with NEON intrinsics not supported
9312 Info.readMem = true;
9313 Info.writeMem = false;
9316 case Intrinsic::arm_neon_vst1:
9317 case Intrinsic::arm_neon_vst2:
9318 case Intrinsic::arm_neon_vst3:
9319 case Intrinsic::arm_neon_vst4:
9320 case Intrinsic::arm_neon_vst2lane:
9321 case Intrinsic::arm_neon_vst3lane:
9322 case Intrinsic::arm_neon_vst4lane: {
9323 Info.opc = ISD::INTRINSIC_VOID;
9324 // Conservatively set memVT to the entire set of vectors stored.
9325 unsigned NumElts = 0;
9326 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9327 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9328 if (!ArgTy->isVectorTy())
9330 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9332 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9333 Info.ptrVal = I.getArgOperand(0);
9335 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9336 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9337 Info.vol = false; // volatile stores with NEON intrinsics not supported
9338 Info.readMem = false;
9339 Info.writeMem = true;
9342 case Intrinsic::arm_strexd: {
9343 Info.opc = ISD::INTRINSIC_W_CHAIN;
9344 Info.memVT = MVT::i64;
9345 Info.ptrVal = I.getArgOperand(2);
9349 Info.readMem = false;
9350 Info.writeMem = true;
9353 case Intrinsic::arm_ldrexd: {
9354 Info.opc = ISD::INTRINSIC_W_CHAIN;
9355 Info.memVT = MVT::i64;
9356 Info.ptrVal = I.getArgOperand(0);
9360 Info.readMem = true;
9361 Info.writeMem = false;