1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/MC/MCSectionMachO.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include <utility>
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "arm-isel"
59 
60 STATISTIC(NumTailCalls, "Number of tail calls");
61 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
62 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
63 STATISTIC(NumConstpoolPromoted,
64   "Number of constants with their storage promoted into constant pools");
65 
66 static cl::opt<bool>
67 ARMInterworking("arm-interworking", cl::Hidden,
68   cl::desc("Enable / disable ARM interworking (for debugging only)"),
69   cl::init(true));
70 
71 static cl::opt<bool> EnableConstpoolPromotion(
72     "arm-promote-constant", cl::Hidden,
73     cl::desc("Enable / disable promotion of unnamed_addr constants into "
74              "constant pools"),
75     cl::init(true));
76 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
77     "arm-promote-constant-max-size", cl::Hidden,
78     cl::desc("Maximum size of constant to promote into a constant pool"),
79     cl::init(64));
80 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
81     "arm-promote-constant-max-total", cl::Hidden,
82     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
83     cl::init(128));
84 
85 namespace {
86   class ARMCCState : public CCState {
87   public:
88     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
89                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
90                ParmContext PC)
91         : CCState(CC, isVarArg, MF, locs, C) {
92       assert(((PC == Call) || (PC == Prologue)) &&
93              "ARMCCState users must specify whether their context is call"
94              "or prologue generation.");
95       CallOrPrologue = PC;
96     }
97   };
98 }
99 
100 void ARMTargetLowering::InitLibcallCallingConvs() {
101   // The builtins on ARM always use AAPCS, irrespective of wheter C is AAPCS or
102   // AAPCS_VFP.
103   for (const auto LC : {
104            RTLIB::SHL_I16,
105            RTLIB::SHL_I32,
106            RTLIB::SHL_I64,
107            RTLIB::SHL_I128,
108            RTLIB::SRL_I16,
109            RTLIB::SRL_I32,
110            RTLIB::SRL_I64,
111            RTLIB::SRL_I128,
112            RTLIB::SRA_I16,
113            RTLIB::SRA_I32,
114            RTLIB::SRA_I64,
115            RTLIB::SRA_I128,
116            RTLIB::MUL_I8,
117            RTLIB::MUL_I16,
118            RTLIB::MUL_I32,
119            RTLIB::MUL_I64,
120            RTLIB::MUL_I128,
121            RTLIB::MULO_I32,
122            RTLIB::MULO_I64,
123            RTLIB::MULO_I128,
124            RTLIB::SDIV_I8,
125            RTLIB::SDIV_I16,
126            RTLIB::SDIV_I32,
127            RTLIB::SDIV_I64,
128            RTLIB::SDIV_I128,
129            RTLIB::UDIV_I8,
130            RTLIB::UDIV_I16,
131            RTLIB::UDIV_I32,
132            RTLIB::UDIV_I64,
133            RTLIB::UDIV_I128,
134            RTLIB::SREM_I8,
135            RTLIB::SREM_I16,
136            RTLIB::SREM_I32,
137            RTLIB::SREM_I64,
138            RTLIB::SREM_I128,
139            RTLIB::UREM_I8,
140            RTLIB::UREM_I16,
141            RTLIB::UREM_I32,
142            RTLIB::UREM_I64,
143            RTLIB::UREM_I128,
144            RTLIB::SDIVREM_I8,
145            RTLIB::SDIVREM_I16,
146            RTLIB::SDIVREM_I32,
147            RTLIB::SDIVREM_I64,
148            RTLIB::SDIVREM_I128,
149            RTLIB::UDIVREM_I8,
150            RTLIB::UDIVREM_I16,
151            RTLIB::UDIVREM_I32,
152            RTLIB::UDIVREM_I64,
153            RTLIB::UDIVREM_I128,
154            RTLIB::NEG_I32,
155            RTLIB::NEG_I64,
156            RTLIB::ADD_F32,
157            RTLIB::ADD_F64,
158            RTLIB::ADD_F80,
159            RTLIB::ADD_F128,
160            RTLIB::SUB_F32,
161            RTLIB::SUB_F64,
162            RTLIB::SUB_F80,
163            RTLIB::SUB_F128,
164            RTLIB::MUL_F32,
165            RTLIB::MUL_F64,
166            RTLIB::MUL_F80,
167            RTLIB::MUL_F128,
168            RTLIB::DIV_F32,
169            RTLIB::DIV_F64,
170            RTLIB::DIV_F80,
171            RTLIB::DIV_F128,
172            RTLIB::POWI_F32,
173            RTLIB::POWI_F64,
174            RTLIB::POWI_F80,
175            RTLIB::POWI_F128,
176            RTLIB::FPEXT_F64_F128,
177            RTLIB::FPEXT_F32_F128,
178            RTLIB::FPEXT_F32_F64,
179            RTLIB::FPEXT_F16_F32,
180            RTLIB::FPROUND_F32_F16,
181            RTLIB::FPROUND_F64_F16,
182            RTLIB::FPROUND_F80_F16,
183            RTLIB::FPROUND_F128_F16,
184            RTLIB::FPROUND_F64_F32,
185            RTLIB::FPROUND_F80_F32,
186            RTLIB::FPROUND_F128_F32,
187            RTLIB::FPROUND_F80_F64,
188            RTLIB::FPROUND_F128_F64,
189            RTLIB::FPTOSINT_F32_I32,
190            RTLIB::FPTOSINT_F32_I64,
191            RTLIB::FPTOSINT_F32_I128,
192            RTLIB::FPTOSINT_F64_I32,
193            RTLIB::FPTOSINT_F64_I64,
194            RTLIB::FPTOSINT_F64_I128,
195            RTLIB::FPTOSINT_F80_I32,
196            RTLIB::FPTOSINT_F80_I64,
197            RTLIB::FPTOSINT_F80_I128,
198            RTLIB::FPTOSINT_F128_I32,
199            RTLIB::FPTOSINT_F128_I64,
200            RTLIB::FPTOSINT_F128_I128,
201            RTLIB::FPTOUINT_F32_I32,
202            RTLIB::FPTOUINT_F32_I64,
203            RTLIB::FPTOUINT_F32_I128,
204            RTLIB::FPTOUINT_F64_I32,
205            RTLIB::FPTOUINT_F64_I64,
206            RTLIB::FPTOUINT_F64_I128,
207            RTLIB::FPTOUINT_F80_I32,
208            RTLIB::FPTOUINT_F80_I64,
209            RTLIB::FPTOUINT_F80_I128,
210            RTLIB::FPTOUINT_F128_I32,
211            RTLIB::FPTOUINT_F128_I64,
212            RTLIB::FPTOUINT_F128_I128,
213            RTLIB::SINTTOFP_I32_F32,
214            RTLIB::SINTTOFP_I32_F64,
215            RTLIB::SINTTOFP_I32_F80,
216            RTLIB::SINTTOFP_I32_F128,
217            RTLIB::SINTTOFP_I64_F32,
218            RTLIB::SINTTOFP_I64_F64,
219            RTLIB::SINTTOFP_I64_F80,
220            RTLIB::SINTTOFP_I64_F128,
221            RTLIB::SINTTOFP_I128_F32,
222            RTLIB::SINTTOFP_I128_F64,
223            RTLIB::SINTTOFP_I128_F80,
224            RTLIB::SINTTOFP_I128_F128,
225            RTLIB::UINTTOFP_I32_F32,
226            RTLIB::UINTTOFP_I32_F64,
227            RTLIB::UINTTOFP_I32_F80,
228            RTLIB::UINTTOFP_I32_F128,
229            RTLIB::UINTTOFP_I64_F32,
230            RTLIB::UINTTOFP_I64_F64,
231            RTLIB::UINTTOFP_I64_F80,
232            RTLIB::UINTTOFP_I64_F128,
233            RTLIB::UINTTOFP_I128_F32,
234            RTLIB::UINTTOFP_I128_F64,
235            RTLIB::UINTTOFP_I128_F80,
236            RTLIB::UINTTOFP_I128_F128,
237            RTLIB::OEQ_F32,
238            RTLIB::OEQ_F64,
239            RTLIB::OEQ_F128,
240            RTLIB::UNE_F32,
241            RTLIB::UNE_F64,
242            RTLIB::UNE_F128,
243            RTLIB::OGE_F32,
244            RTLIB::OGE_F64,
245            RTLIB::OGE_F128,
246            RTLIB::OLT_F32,
247            RTLIB::OLT_F64,
248            RTLIB::OLT_F128,
249            RTLIB::OLE_F32,
250            RTLIB::OLE_F64,
251            RTLIB::OLE_F128,
252            RTLIB::OGT_F32,
253            RTLIB::OGT_F64,
254            RTLIB::OGT_F128,
255            RTLIB::UO_F32,
256            RTLIB::UO_F64,
257            RTLIB::UO_F128,
258            RTLIB::O_F32,
259            RTLIB::O_F64,
260            RTLIB::O_F128,
261        })
262   setLibcallCallingConv(LC, CallingConv::ARM_AAPCS);
263 }
264 
265 // The APCS parameter registers.
266 static const MCPhysReg GPRArgRegs[] = {
267   ARM::R0, ARM::R1, ARM::R2, ARM::R3
268 };
269 
270 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
271                                        MVT PromotedBitwiseVT) {
272   if (VT != PromotedLdStVT) {
273     setOperationAction(ISD::LOAD, VT, Promote);
274     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
275 
276     setOperationAction(ISD::STORE, VT, Promote);
277     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
278   }
279 
280   MVT ElemTy = VT.getVectorElementType();
281   if (ElemTy != MVT::f64)
282     setOperationAction(ISD::SETCC, VT, Custom);
283   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
284   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
285   if (ElemTy == MVT::i32) {
286     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
287     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
288     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
289     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
290   } else {
291     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
292     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
293     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
294     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
295   }
296   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
297   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
298   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
299   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
300   setOperationAction(ISD::SELECT,            VT, Expand);
301   setOperationAction(ISD::SELECT_CC,         VT, Expand);
302   setOperationAction(ISD::VSELECT,           VT, Expand);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
304   if (VT.isInteger()) {
305     setOperationAction(ISD::SHL, VT, Custom);
306     setOperationAction(ISD::SRA, VT, Custom);
307     setOperationAction(ISD::SRL, VT, Custom);
308   }
309 
310   // Promote all bit-wise operations.
311   if (VT.isInteger() && VT != PromotedBitwiseVT) {
312     setOperationAction(ISD::AND, VT, Promote);
313     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
314     setOperationAction(ISD::OR,  VT, Promote);
315     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
316     setOperationAction(ISD::XOR, VT, Promote);
317     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
318   }
319 
320   // Neon does not support vector divide/remainder operations.
321   setOperationAction(ISD::SDIV, VT, Expand);
322   setOperationAction(ISD::UDIV, VT, Expand);
323   setOperationAction(ISD::FDIV, VT, Expand);
324   setOperationAction(ISD::SREM, VT, Expand);
325   setOperationAction(ISD::UREM, VT, Expand);
326   setOperationAction(ISD::FREM, VT, Expand);
327 
328   if (!VT.isFloatingPoint() &&
329       VT != MVT::v2i64 && VT != MVT::v1i64)
330     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
331       setOperationAction(Opcode, VT, Legal);
332 }
333 
334 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
335   addRegisterClass(VT, &ARM::DPRRegClass);
336   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
337 }
338 
339 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
340   addRegisterClass(VT, &ARM::DPairRegClass);
341   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
342 }
343 
344 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
345                                      const ARMSubtarget &STI)
346     : TargetLowering(TM), Subtarget(&STI) {
347   RegInfo = Subtarget->getRegisterInfo();
348   Itins = Subtarget->getInstrItineraryData();
349 
350   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
351 
352   InitLibcallCallingConvs();
353 
354   if (Subtarget->isTargetMachO()) {
355     // Uses VFP for Thumb libfuncs if available.
356     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
357         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
358       static const struct {
359         const RTLIB::Libcall Op;
360         const char * const Name;
361         const ISD::CondCode Cond;
362       } LibraryCalls[] = {
363         // Single-precision floating-point arithmetic.
364         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
365         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
366         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
367         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
368 
369         // Double-precision floating-point arithmetic.
370         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
371         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
372         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
373         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
374 
375         // Single-precision comparisons.
376         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
377         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
378         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
379         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
380         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
381         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
382         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
383         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
384 
385         // Double-precision comparisons.
386         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
387         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
388         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
389         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
390         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
391         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
392         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
393         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
394 
395         // Floating-point to integer conversions.
396         // i64 conversions are done via library routines even when generating VFP
397         // instructions, so use the same ones.
398         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
399         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
400         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
401         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
402 
403         // Conversions between floating types.
404         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
405         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
406 
407         // Integer to floating-point conversions.
408         // i64 conversions are done via library routines even when generating VFP
409         // instructions, so use the same ones.
410         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
411         // e.g., __floatunsidf vs. __floatunssidfvfp.
412         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
413         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
414         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
415         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
416       };
417 
418       for (const auto &LC : LibraryCalls) {
419         setLibcallName(LC.Op, LC.Name);
420         if (LC.Cond != ISD::SETCC_INVALID)
421           setCmpLibcallCC(LC.Op, LC.Cond);
422       }
423     }
424 
425     // Set the correct calling convention for ARMv7k WatchOS. It's just
426     // AAPCS_VFP for functions as simple as libcalls.
427     if (Subtarget->isTargetWatchABI()) {
428       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
429         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
430     }
431   }
432 
433   // These libcalls are not available in 32-bit.
434   setLibcallName(RTLIB::SHL_I128, nullptr);
435   setLibcallName(RTLIB::SRL_I128, nullptr);
436   setLibcallName(RTLIB::SRA_I128, nullptr);
437 
438   // RTLIB
439   if (Subtarget->isAAPCS_ABI() &&
440       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
441        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
442     static const struct {
443       const RTLIB::Libcall Op;
444       const char * const Name;
445       const CallingConv::ID CC;
446       const ISD::CondCode Cond;
447     } LibraryCalls[] = {
448       // Double-precision floating-point arithmetic helper functions
449       // RTABI chapter 4.1.2, Table 2
450       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
451       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
452       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
453       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
454 
455       // Double-precision floating-point comparison helper functions
456       // RTABI chapter 4.1.2, Table 3
457       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
458       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
459       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
460       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
461       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
462       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
463       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
464       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
465 
466       // Single-precision floating-point arithmetic helper functions
467       // RTABI chapter 4.1.2, Table 4
468       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
469       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
470       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
471       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
472 
473       // Single-precision floating-point comparison helper functions
474       // RTABI chapter 4.1.2, Table 5
475       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
476       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
477       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
478       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
479       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
480       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
481       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
482       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
483 
484       // Floating-point to integer conversions.
485       // RTABI chapter 4.1.2, Table 6
486       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
487       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
488       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
489       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
490       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
491       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 
495       // Conversions between floating types.
496       // RTABI chapter 4.1.2, Table 7
497       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
498       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
499       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
500 
501       // Integer to floating-point conversions.
502       // RTABI chapter 4.1.2, Table 8
503       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
504       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
505       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
506       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
507       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
508       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
509       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 
512       // Long long helper functions
513       // RTABI chapter 4.2, Table 9
514       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
515       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
516       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
517       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
518 
519       // Integer division functions
520       // RTABI chapter 4.3.1
521       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
522       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
523       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
524       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
525       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
526       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
527       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529     };
530 
531     for (const auto &LC : LibraryCalls) {
532       setLibcallName(LC.Op, LC.Name);
533       setLibcallCallingConv(LC.Op, LC.CC);
534       if (LC.Cond != ISD::SETCC_INVALID)
535         setCmpLibcallCC(LC.Op, LC.Cond);
536     }
537 
538     // EABI dependent RTLIB
539     if (TM.Options.EABIVersion == EABI::EABI4 ||
540         TM.Options.EABIVersion == EABI::EABI5) {
541       static const struct {
542         const RTLIB::Libcall Op;
543         const char *const Name;
544         const CallingConv::ID CC;
545         const ISD::CondCode Cond;
546       } MemOpsLibraryCalls[] = {
547         // Memory operations
548         // RTABI chapter 4.3.4
549         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552       };
553 
554       for (const auto &LC : MemOpsLibraryCalls) {
555         setLibcallName(LC.Op, LC.Name);
556         setLibcallCallingConv(LC.Op, LC.CC);
557         if (LC.Cond != ISD::SETCC_INVALID)
558           setCmpLibcallCC(LC.Op, LC.Cond);
559       }
560     }
561   }
562 
563   if (Subtarget->isTargetWindows()) {
564     static const struct {
565       const RTLIB::Libcall Op;
566       const char * const Name;
567       const CallingConv::ID CC;
568     } LibraryCalls[] = {
569       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
570       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
571       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
572       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
573       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
574       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
575       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
576       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
577     };
578 
579     for (const auto &LC : LibraryCalls) {
580       setLibcallName(LC.Op, LC.Name);
581       setLibcallCallingConv(LC.Op, LC.CC);
582     }
583   }
584 
585   // Use divmod compiler-rt calls for iOS 5.0 and later.
586   if (Subtarget->isTargetWatchOS() ||
587       (Subtarget->isTargetIOS() &&
588        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
589     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
590     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
591   }
592 
593   // The half <-> float conversion functions are always soft-float on
594   // non-watchos platforms, but are needed for some targets which use a
595   // hard-float calling convention by default.
596   if (!Subtarget->isTargetWatchABI()) {
597     if (Subtarget->isAAPCS_ABI()) {
598       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
599       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
600       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
601     } else {
602       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
603       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
604       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
605     }
606   }
607 
608   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
609   // a __gnu_ prefix (which is the default).
610   if (Subtarget->isTargetAEABI()) {
611     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
612     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
613     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
614   }
615 
616   if (Subtarget->isThumb1Only())
617     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
618   else
619     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
620   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
621       !Subtarget->isThumb1Only()) {
622     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
623     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
624   }
625 
626   for (MVT VT : MVT::vector_valuetypes()) {
627     for (MVT InnerVT : MVT::vector_valuetypes()) {
628       setTruncStoreAction(VT, InnerVT, Expand);
629       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
630       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
631       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
632     }
633 
634     setOperationAction(ISD::MULHS, VT, Expand);
635     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
636     setOperationAction(ISD::MULHU, VT, Expand);
637     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
638 
639     setOperationAction(ISD::BSWAP, VT, Expand);
640   }
641 
642   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
643   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
644 
645   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
646   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
647 
648   if (Subtarget->hasNEON()) {
649     addDRTypeForNEON(MVT::v2f32);
650     addDRTypeForNEON(MVT::v8i8);
651     addDRTypeForNEON(MVT::v4i16);
652     addDRTypeForNEON(MVT::v2i32);
653     addDRTypeForNEON(MVT::v1i64);
654 
655     addQRTypeForNEON(MVT::v4f32);
656     addQRTypeForNEON(MVT::v2f64);
657     addQRTypeForNEON(MVT::v16i8);
658     addQRTypeForNEON(MVT::v8i16);
659     addQRTypeForNEON(MVT::v4i32);
660     addQRTypeForNEON(MVT::v2i64);
661 
662     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
663     // neither Neon nor VFP support any arithmetic operations on it.
664     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
665     // supported for v4f32.
666     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
667     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
668     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
669     // FIXME: Code duplication: FDIV and FREM are expanded always, see
670     // ARMTargetLowering::addTypeForNEON method for details.
671     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
672     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
673     // FIXME: Create unittest.
674     // In another words, find a way when "copysign" appears in DAG with vector
675     // operands.
676     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
677     // FIXME: Code duplication: SETCC has custom operation action, see
678     // ARMTargetLowering::addTypeForNEON method for details.
679     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
680     // FIXME: Create unittest for FNEG and for FABS.
681     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
682     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
683     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
684     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
685     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
686     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
687     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
688     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
689     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
690     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
691     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
692     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
693     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
694     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
695     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
696     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
697     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
698     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
699     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
700 
701     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
702     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
703     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
704     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
705     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
706     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
707     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
708     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
709     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
710     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
711     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
712     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
713     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
714     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
715     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
716 
717     // Mark v2f32 intrinsics.
718     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
719     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
720     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
721     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
722     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
723     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
724     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
725     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
726     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
727     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
728     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
729     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
730     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
731     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
732     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
733 
734     // Neon does not support some operations on v1i64 and v2i64 types.
735     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
736     // Custom handling for some quad-vector types to detect VMULL.
737     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
738     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
739     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
740     // Custom handling for some vector types to avoid expensive expansions
741     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
742     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
743     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
744     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
745     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
746     // a destination type that is wider than the source, and nor does
747     // it have a FP_TO_[SU]INT instruction with a narrower destination than
748     // source.
749     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
750     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
751     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
752     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
755     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
756 
757     // NEON does not have single instruction CTPOP for vectors with element
758     // types wider than 8-bits.  However, custom lowering can leverage the
759     // v8i8/v16i8 vcnt instruction.
760     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
761     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
762     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
763     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
764     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
765     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
766 
767     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
768     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
769 
770     // NEON does not have single instruction CTTZ for vectors.
771     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
772     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
773     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
774     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
775 
776     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
777     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
778     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
779     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
780 
781     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
782     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
783     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
784     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
785 
786     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
787     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
788     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
789     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
790 
791     // NEON only has FMA instructions as of VFP4.
792     if (!Subtarget->hasVFP4()) {
793       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
794       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
795     }
796 
797     setTargetDAGCombine(ISD::INTRINSIC_VOID);
798     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
799     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
800     setTargetDAGCombine(ISD::SHL);
801     setTargetDAGCombine(ISD::SRL);
802     setTargetDAGCombine(ISD::SRA);
803     setTargetDAGCombine(ISD::SIGN_EXTEND);
804     setTargetDAGCombine(ISD::ZERO_EXTEND);
805     setTargetDAGCombine(ISD::ANY_EXTEND);
806     setTargetDAGCombine(ISD::BUILD_VECTOR);
807     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
808     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
809     setTargetDAGCombine(ISD::STORE);
810     setTargetDAGCombine(ISD::FP_TO_SINT);
811     setTargetDAGCombine(ISD::FP_TO_UINT);
812     setTargetDAGCombine(ISD::FDIV);
813     setTargetDAGCombine(ISD::LOAD);
814 
815     // It is legal to extload from v4i8 to v4i16 or v4i32.
816     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
817                    MVT::v2i32}) {
818       for (MVT VT : MVT::integer_vector_valuetypes()) {
819         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
820         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
821         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
822       }
823     }
824   }
825 
826   // ARM and Thumb2 support UMLAL/SMLAL.
827   if (!Subtarget->isThumb1Only())
828     setTargetDAGCombine(ISD::ADDC);
829 
830   if (Subtarget->isFPOnlySP()) {
831     // When targeting a floating-point unit with only single-precision
832     // operations, f64 is legal for the few double-precision instructions which
833     // are present However, no double-precision operations other than moves,
834     // loads and stores are provided by the hardware.
835     setOperationAction(ISD::FADD,       MVT::f64, Expand);
836     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
837     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
838     setOperationAction(ISD::FMA,        MVT::f64, Expand);
839     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
840     setOperationAction(ISD::FREM,       MVT::f64, Expand);
841     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
842     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
843     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
844     setOperationAction(ISD::FABS,       MVT::f64, Expand);
845     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
846     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
847     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
848     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
849     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
850     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
851     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
852     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
853     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
854     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
855     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
856     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
857     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
858     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
859     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
860     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
861     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
862     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
863     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
865     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
866     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
867     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
868   }
869 
870   computeRegisterProperties(Subtarget->getRegisterInfo());
871 
872   // ARM does not have floating-point extending loads.
873   for (MVT VT : MVT::fp_valuetypes()) {
874     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
875     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
876   }
877 
878   // ... or truncating stores
879   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
880   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
881   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
882 
883   // ARM does not have i1 sign extending load.
884   for (MVT VT : MVT::integer_valuetypes())
885     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
886 
887   // ARM supports all 4 flavors of integer indexed load / store.
888   if (!Subtarget->isThumb1Only()) {
889     for (unsigned im = (unsigned)ISD::PRE_INC;
890          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
891       setIndexedLoadAction(im,  MVT::i1,  Legal);
892       setIndexedLoadAction(im,  MVT::i8,  Legal);
893       setIndexedLoadAction(im,  MVT::i16, Legal);
894       setIndexedLoadAction(im,  MVT::i32, Legal);
895       setIndexedStoreAction(im, MVT::i1,  Legal);
896       setIndexedStoreAction(im, MVT::i8,  Legal);
897       setIndexedStoreAction(im, MVT::i16, Legal);
898       setIndexedStoreAction(im, MVT::i32, Legal);
899     }
900   } else {
901     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
902     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
903     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
904   }
905 
906   setOperationAction(ISD::SADDO, MVT::i32, Custom);
907   setOperationAction(ISD::UADDO, MVT::i32, Custom);
908   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
909   setOperationAction(ISD::USUBO, MVT::i32, Custom);
910 
911   // i64 operation support.
912   setOperationAction(ISD::MUL,     MVT::i64, Expand);
913   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
914   if (Subtarget->isThumb1Only()) {
915     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
916     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
917   }
918   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
919       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
920     setOperationAction(ISD::MULHS, MVT::i32, Expand);
921 
922   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
923   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
924   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
925   setOperationAction(ISD::SRL,       MVT::i64, Custom);
926   setOperationAction(ISD::SRA,       MVT::i64, Custom);
927 
928   if (!Subtarget->isThumb1Only()) {
929     // FIXME: We should do this for Thumb1 as well.
930     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
931     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
932     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
933     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
934   }
935 
936   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
937     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
938 
939   // ARM does not have ROTL.
940   setOperationAction(ISD::ROTL, MVT::i32, Expand);
941   for (MVT VT : MVT::vector_valuetypes()) {
942     setOperationAction(ISD::ROTL, VT, Expand);
943     setOperationAction(ISD::ROTR, VT, Expand);
944   }
945   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
946   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
947   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
948     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
949 
950   // @llvm.readcyclecounter requires the Performance Monitors extension.
951   // Default to the 0 expansion on unsupported platforms.
952   // FIXME: Technically there are older ARM CPUs that have
953   // implementation-specific ways of obtaining this information.
954   if (Subtarget->hasPerfMon())
955     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
956 
957   // Only ARMv6 has BSWAP.
958   if (!Subtarget->hasV6Ops())
959     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
960 
961   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
962                                         : Subtarget->hasDivideInARMMode();
963   if (!hasDivide) {
964     // These are expanded into libcalls if the cpu doesn't have HW divider.
965     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
966     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
967   }
968 
969   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
970     setOperationAction(ISD::SDIV, MVT::i32, Custom);
971     setOperationAction(ISD::UDIV, MVT::i32, Custom);
972 
973     setOperationAction(ISD::SDIV, MVT::i64, Custom);
974     setOperationAction(ISD::UDIV, MVT::i64, Custom);
975   }
976 
977   setOperationAction(ISD::SREM,  MVT::i32, Expand);
978   setOperationAction(ISD::UREM,  MVT::i32, Expand);
979   // Register based DivRem for AEABI (RTABI 4.2)
980   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
981       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
982       Subtarget->isTargetWindows()) {
983     setOperationAction(ISD::SREM, MVT::i64, Custom);
984     setOperationAction(ISD::UREM, MVT::i64, Custom);
985     HasStandaloneRem = false;
986 
987     for (const auto &LC :
988          {RTLIB::SDIVREM_I8, RTLIB::SDIVREM_I16, RTLIB::SDIVREM_I32})
989       setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_sdiv"
990                                                       : "__aeabi_idivmod");
991     setLibcallName(RTLIB::SDIVREM_I64, Subtarget->isTargetWindows()
992                                            ? "__rt_sdiv64"
993                                            : "__aeabi_ldivmod");
994     for (const auto &LC :
995          {RTLIB::UDIVREM_I8, RTLIB::UDIVREM_I16, RTLIB::UDIVREM_I32})
996       setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_udiv"
997                                                       : "__aeabi_uidivmod");
998     setLibcallName(RTLIB::UDIVREM_I64, Subtarget->isTargetWindows()
999                                            ? "__rt_udiv64"
1000                                            : "__aeabi_uldivmod");
1001 
1002     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
1003     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
1004     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
1005     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
1006     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
1007     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
1008     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
1009     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
1010 
1011     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1012     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1013     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1014     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1015   } else {
1016     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1017     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1018   }
1019 
1020   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1021   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1022   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1023   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1024 
1025   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1026 
1027   // Use the default implementation.
1028   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1029   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1030   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1031   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1032   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1033   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1034 
1035   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
1036     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1037   else
1038     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1039 
1040   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1041   // the default expansion.
1042   InsertFencesForAtomic = false;
1043   if (Subtarget->hasAnyDataBarrier() &&
1044       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1045     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1046     // to ldrex/strex loops already.
1047     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1048     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1049       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1050 
1051     // On v8, we have particularly efficient implementations of atomic fences
1052     // if they can be combined with nearby atomic loads and stores.
1053     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
1054       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1055       InsertFencesForAtomic = true;
1056     }
1057   } else {
1058     // If there's anything we can use as a barrier, go through custom lowering
1059     // for ATOMIC_FENCE.
1060     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1061                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1062 
1063     // Set them all for expansion, which will force libcalls.
1064     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1065     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1066     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1067     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1068     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1069     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1070     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1071     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1072     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1073     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1074     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1075     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1076     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1077     // Unordered/Monotonic case.
1078     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1079     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1080   }
1081 
1082   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1083 
1084   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1085   if (!Subtarget->hasV6Ops()) {
1086     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1087     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1088   }
1089   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1090 
1091   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1092       !Subtarget->isThumb1Only()) {
1093     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1094     // iff target supports vfp2.
1095     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1096     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1097   }
1098 
1099   // We want to custom lower some of our intrinsics.
1100   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1101   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1102   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1103   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1104   if (Subtarget->useSjLjEH())
1105     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1106 
1107   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1108   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1109   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1110   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1111   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1112   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1113   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1114   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1115   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1116 
1117   // Thumb-1 cannot currently select ARMISD::SUBE.
1118   if (!Subtarget->isThumb1Only())
1119     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1120 
1121   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1122   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1123   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1124   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1125   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1126 
1127   // We don't support sin/cos/fmod/copysign/pow
1128   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1129   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1130   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1131   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1132   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1133   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1134   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1135   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1136   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1137       !Subtarget->isThumb1Only()) {
1138     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1139     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1140   }
1141   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1142   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1143 
1144   if (!Subtarget->hasVFP4()) {
1145     setOperationAction(ISD::FMA, MVT::f64, Expand);
1146     setOperationAction(ISD::FMA, MVT::f32, Expand);
1147   }
1148 
1149   // Various VFP goodness
1150   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1151     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1152     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1153       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1154       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1155     }
1156 
1157     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1158     if (!Subtarget->hasFP16()) {
1159       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1160       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1161     }
1162   }
1163 
1164   // Combine sin / cos into one node or libcall if possible.
1165   if (Subtarget->hasSinCos()) {
1166     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1167     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1168     if (Subtarget->isTargetWatchABI()) {
1169       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1170       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1171     }
1172     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1173       // For iOS, we don't want to the normal expansion of a libcall to
1174       // sincos. We want to issue a libcall to __sincos_stret.
1175       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1176       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1177     }
1178   }
1179 
1180   // FP-ARMv8 implements a lot of rounding-like FP operations.
1181   if (Subtarget->hasFPARMv8()) {
1182     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1183     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1184     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1185     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1186     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1187     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1188     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1189     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1190     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1191     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1192     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1193     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1194 
1195     if (!Subtarget->isFPOnlySP()) {
1196       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1197       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1198       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1199       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1200       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1201       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1202       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1203       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1204     }
1205   }
1206 
1207   if (Subtarget->hasNEON()) {
1208     // vmin and vmax aren't available in a scalar form, so we use
1209     // a NEON instruction with an undef lane instead.
1210     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1211     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1212     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1213     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1214     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1215     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1216   }
1217 
1218   // We have target-specific dag combine patterns for the following nodes:
1219   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1220   setTargetDAGCombine(ISD::ADD);
1221   setTargetDAGCombine(ISD::SUB);
1222   setTargetDAGCombine(ISD::MUL);
1223   setTargetDAGCombine(ISD::AND);
1224   setTargetDAGCombine(ISD::OR);
1225   setTargetDAGCombine(ISD::XOR);
1226 
1227   if (Subtarget->hasV6Ops())
1228     setTargetDAGCombine(ISD::SRL);
1229 
1230   setStackPointerRegisterToSaveRestore(ARM::SP);
1231 
1232   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1233       !Subtarget->hasVFP2())
1234     setSchedulingPreference(Sched::RegPressure);
1235   else
1236     setSchedulingPreference(Sched::Hybrid);
1237 
1238   //// temporary - rewrite interface to use type
1239   MaxStoresPerMemset = 8;
1240   MaxStoresPerMemsetOptSize = 4;
1241   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1242   MaxStoresPerMemcpyOptSize = 2;
1243   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1244   MaxStoresPerMemmoveOptSize = 2;
1245 
1246   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1247   // are at least 4 bytes aligned.
1248   setMinStackArgumentAlignment(4);
1249 
1250   // Prefer likely predicted branches to selects on out-of-order cores.
1251   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1252 
1253   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1254 }
1255 
1256 bool ARMTargetLowering::useSoftFloat() const {
1257   return Subtarget->useSoftFloat();
1258 }
1259 
1260 // FIXME: It might make sense to define the representative register class as the
1261 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1262 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1263 // SPR's representative would be DPR_VFP2. This should work well if register
1264 // pressure tracking were modified such that a register use would increment the
1265 // pressure of the register class's representative and all of it's super
1266 // classes' representatives transitively. We have not implemented this because
1267 // of the difficulty prior to coalescing of modeling operand register classes
1268 // due to the common occurrence of cross class copies and subregister insertions
1269 // and extractions.
1270 std::pair<const TargetRegisterClass *, uint8_t>
1271 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1272                                            MVT VT) const {
1273   const TargetRegisterClass *RRC = nullptr;
1274   uint8_t Cost = 1;
1275   switch (VT.SimpleTy) {
1276   default:
1277     return TargetLowering::findRepresentativeClass(TRI, VT);
1278   // Use DPR as representative register class for all floating point
1279   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1280   // the cost is 1 for both f32 and f64.
1281   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1282   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1283     RRC = &ARM::DPRRegClass;
1284     // When NEON is used for SP, only half of the register file is available
1285     // because operations that define both SP and DP results will be constrained
1286     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1287     // coalescing by double-counting the SP regs. See the FIXME above.
1288     if (Subtarget->useNEONForSinglePrecisionFP())
1289       Cost = 2;
1290     break;
1291   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1292   case MVT::v4f32: case MVT::v2f64:
1293     RRC = &ARM::DPRRegClass;
1294     Cost = 2;
1295     break;
1296   case MVT::v4i64:
1297     RRC = &ARM::DPRRegClass;
1298     Cost = 4;
1299     break;
1300   case MVT::v8i64:
1301     RRC = &ARM::DPRRegClass;
1302     Cost = 8;
1303     break;
1304   }
1305   return std::make_pair(RRC, Cost);
1306 }
1307 
1308 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1309   switch ((ARMISD::NodeType)Opcode) {
1310   case ARMISD::FIRST_NUMBER:  break;
1311   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1312   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1313   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1314   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1315   case ARMISD::CALL:          return "ARMISD::CALL";
1316   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1317   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1318   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1319   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1320   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1321   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1322   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1323   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1324   case ARMISD::CMP:           return "ARMISD::CMP";
1325   case ARMISD::CMN:           return "ARMISD::CMN";
1326   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1327   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1328   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1329   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1330   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1331 
1332   case ARMISD::CMOV:          return "ARMISD::CMOV";
1333 
1334   case ARMISD::SSAT:          return "ARMISD::SSAT";
1335 
1336   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1337   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1338   case ARMISD::RRX:           return "ARMISD::RRX";
1339 
1340   case ARMISD::ADDC:          return "ARMISD::ADDC";
1341   case ARMISD::ADDE:          return "ARMISD::ADDE";
1342   case ARMISD::SUBC:          return "ARMISD::SUBC";
1343   case ARMISD::SUBE:          return "ARMISD::SUBE";
1344 
1345   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1346   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1347 
1348   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1349   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1350   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1351 
1352   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1353 
1354   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1355 
1356   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1357 
1358   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1359 
1360   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1361 
1362   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1363   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1364 
1365   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1366   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1367   case ARMISD::VCGE:          return "ARMISD::VCGE";
1368   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1369   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1370   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1371   case ARMISD::VCGT:          return "ARMISD::VCGT";
1372   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1373   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1374   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1375   case ARMISD::VTST:          return "ARMISD::VTST";
1376 
1377   case ARMISD::VSHL:          return "ARMISD::VSHL";
1378   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1379   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1380   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1381   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1382   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1383   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1384   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1385   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1386   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1387   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1388   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1389   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1390   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1391   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1392   case ARMISD::VSLI:          return "ARMISD::VSLI";
1393   case ARMISD::VSRI:          return "ARMISD::VSRI";
1394   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1395   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1396   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1397   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1398   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1399   case ARMISD::VDUP:          return "ARMISD::VDUP";
1400   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1401   case ARMISD::VEXT:          return "ARMISD::VEXT";
1402   case ARMISD::VREV64:        return "ARMISD::VREV64";
1403   case ARMISD::VREV32:        return "ARMISD::VREV32";
1404   case ARMISD::VREV16:        return "ARMISD::VREV16";
1405   case ARMISD::VZIP:          return "ARMISD::VZIP";
1406   case ARMISD::VUZP:          return "ARMISD::VUZP";
1407   case ARMISD::VTRN:          return "ARMISD::VTRN";
1408   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1409   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1410   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1411   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1412   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1413   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1414   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1415   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1416   case ARMISD::BFI:           return "ARMISD::BFI";
1417   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1418   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1419   case ARMISD::VBSL:          return "ARMISD::VBSL";
1420   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1421   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1422   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1423   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1424   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1425   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1426   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1427   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1428   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1429   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1430   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1431   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1432   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1433   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1434   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1435   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1436   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1437   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1438   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1439   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1440   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1441   }
1442   return nullptr;
1443 }
1444 
1445 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1446                                           EVT VT) const {
1447   if (!VT.isVector())
1448     return getPointerTy(DL);
1449   return VT.changeVectorElementTypeToInteger();
1450 }
1451 
1452 /// getRegClassFor - Return the register class that should be used for the
1453 /// specified value type.
1454 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1455   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1456   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1457   // load / store 4 to 8 consecutive D registers.
1458   if (Subtarget->hasNEON()) {
1459     if (VT == MVT::v4i64)
1460       return &ARM::QQPRRegClass;
1461     if (VT == MVT::v8i64)
1462       return &ARM::QQQQPRRegClass;
1463   }
1464   return TargetLowering::getRegClassFor(VT);
1465 }
1466 
1467 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1468 // source/dest is aligned and the copy size is large enough. We therefore want
1469 // to align such objects passed to memory intrinsics.
1470 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1471                                                unsigned &PrefAlign) const {
1472   if (!isa<MemIntrinsic>(CI))
1473     return false;
1474   MinSize = 8;
1475   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1476   // cycle faster than 4-byte aligned LDM.
1477   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1478   return true;
1479 }
1480 
1481 // Create a fast isel object.
1482 FastISel *
1483 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1484                                   const TargetLibraryInfo *libInfo) const {
1485   return ARM::createFastISel(funcInfo, libInfo);
1486 }
1487 
1488 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1489   unsigned NumVals = N->getNumValues();
1490   if (!NumVals)
1491     return Sched::RegPressure;
1492 
1493   for (unsigned i = 0; i != NumVals; ++i) {
1494     EVT VT = N->getValueType(i);
1495     if (VT == MVT::Glue || VT == MVT::Other)
1496       continue;
1497     if (VT.isFloatingPoint() || VT.isVector())
1498       return Sched::ILP;
1499   }
1500 
1501   if (!N->isMachineOpcode())
1502     return Sched::RegPressure;
1503 
1504   // Load are scheduled for latency even if there instruction itinerary
1505   // is not available.
1506   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1507   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1508 
1509   if (MCID.getNumDefs() == 0)
1510     return Sched::RegPressure;
1511   if (!Itins->isEmpty() &&
1512       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1513     return Sched::ILP;
1514 
1515   return Sched::RegPressure;
1516 }
1517 
1518 //===----------------------------------------------------------------------===//
1519 // Lowering Code
1520 //===----------------------------------------------------------------------===//
1521 
1522 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1523 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1524   switch (CC) {
1525   default: llvm_unreachable("Unknown condition code!");
1526   case ISD::SETNE:  return ARMCC::NE;
1527   case ISD::SETEQ:  return ARMCC::EQ;
1528   case ISD::SETGT:  return ARMCC::GT;
1529   case ISD::SETGE:  return ARMCC::GE;
1530   case ISD::SETLT:  return ARMCC::LT;
1531   case ISD::SETLE:  return ARMCC::LE;
1532   case ISD::SETUGT: return ARMCC::HI;
1533   case ISD::SETUGE: return ARMCC::HS;
1534   case ISD::SETULT: return ARMCC::LO;
1535   case ISD::SETULE: return ARMCC::LS;
1536   }
1537 }
1538 
1539 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1540 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1541                         ARMCC::CondCodes &CondCode2) {
1542   CondCode2 = ARMCC::AL;
1543   switch (CC) {
1544   default: llvm_unreachable("Unknown FP condition!");
1545   case ISD::SETEQ:
1546   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1547   case ISD::SETGT:
1548   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1549   case ISD::SETGE:
1550   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1551   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1552   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1553   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1554   case ISD::SETO:   CondCode = ARMCC::VC; break;
1555   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1556   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1557   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1558   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1559   case ISD::SETLT:
1560   case ISD::SETULT: CondCode = ARMCC::LT; break;
1561   case ISD::SETLE:
1562   case ISD::SETULE: CondCode = ARMCC::LE; break;
1563   case ISD::SETNE:
1564   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1565   }
1566 }
1567 
1568 //===----------------------------------------------------------------------===//
1569 //                      Calling Convention Implementation
1570 //===----------------------------------------------------------------------===//
1571 
1572 #include "ARMGenCallingConv.inc"
1573 
1574 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1575 /// account presence of floating point hardware and calling convention
1576 /// limitations, such as support for variadic functions.
1577 CallingConv::ID
1578 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1579                                            bool isVarArg) const {
1580   switch (CC) {
1581   default:
1582     llvm_unreachable("Unsupported calling convention");
1583   case CallingConv::ARM_AAPCS:
1584   case CallingConv::ARM_APCS:
1585   case CallingConv::GHC:
1586     return CC;
1587   case CallingConv::PreserveMost:
1588     return CallingConv::PreserveMost;
1589   case CallingConv::ARM_AAPCS_VFP:
1590   case CallingConv::Swift:
1591     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1592   case CallingConv::C:
1593     if (!Subtarget->isAAPCS_ABI())
1594       return CallingConv::ARM_APCS;
1595     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1596              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1597              !isVarArg)
1598       return CallingConv::ARM_AAPCS_VFP;
1599     else
1600       return CallingConv::ARM_AAPCS;
1601   case CallingConv::Fast:
1602   case CallingConv::CXX_FAST_TLS:
1603     if (!Subtarget->isAAPCS_ABI()) {
1604       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1605         return CallingConv::Fast;
1606       return CallingConv::ARM_APCS;
1607     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1608       return CallingConv::ARM_AAPCS_VFP;
1609     else
1610       return CallingConv::ARM_AAPCS;
1611   }
1612 }
1613 
1614 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1615 /// CallingConvention.
1616 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1617                                                  bool Return,
1618                                                  bool isVarArg) const {
1619   switch (getEffectiveCallingConv(CC, isVarArg)) {
1620   default:
1621     llvm_unreachable("Unsupported calling convention");
1622   case CallingConv::ARM_APCS:
1623     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1624   case CallingConv::ARM_AAPCS:
1625     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1626   case CallingConv::ARM_AAPCS_VFP:
1627     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1628   case CallingConv::Fast:
1629     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1630   case CallingConv::GHC:
1631     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1632   case CallingConv::PreserveMost:
1633     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1634   }
1635 }
1636 
1637 /// LowerCallResult - Lower the result values of a call into the
1638 /// appropriate copies out of appropriate physical registers.
1639 SDValue ARMTargetLowering::LowerCallResult(
1640     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1641     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1642     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1643     SDValue ThisVal) const {
1644 
1645   // Assign locations to each value returned by this call.
1646   SmallVector<CCValAssign, 16> RVLocs;
1647   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1648                     *DAG.getContext(), Call);
1649   CCInfo.AnalyzeCallResult(Ins,
1650                            CCAssignFnForNode(CallConv, /* Return*/ true,
1651                                              isVarArg));
1652 
1653   // Copy all of the result registers out of their specified physreg.
1654   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1655     CCValAssign VA = RVLocs[i];
1656 
1657     // Pass 'this' value directly from the argument to return value, to avoid
1658     // reg unit interference
1659     if (i == 0 && isThisReturn) {
1660       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1661              "unexpected return calling convention register assignment");
1662       InVals.push_back(ThisVal);
1663       continue;
1664     }
1665 
1666     SDValue Val;
1667     if (VA.needsCustom()) {
1668       // Handle f64 or half of a v2f64.
1669       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1670                                       InFlag);
1671       Chain = Lo.getValue(1);
1672       InFlag = Lo.getValue(2);
1673       VA = RVLocs[++i]; // skip ahead to next loc
1674       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1675                                       InFlag);
1676       Chain = Hi.getValue(1);
1677       InFlag = Hi.getValue(2);
1678       if (!Subtarget->isLittle())
1679         std::swap (Lo, Hi);
1680       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1681 
1682       if (VA.getLocVT() == MVT::v2f64) {
1683         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1684         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1685                           DAG.getConstant(0, dl, MVT::i32));
1686 
1687         VA = RVLocs[++i]; // skip ahead to next loc
1688         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1689         Chain = Lo.getValue(1);
1690         InFlag = Lo.getValue(2);
1691         VA = RVLocs[++i]; // skip ahead to next loc
1692         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1693         Chain = Hi.getValue(1);
1694         InFlag = Hi.getValue(2);
1695         if (!Subtarget->isLittle())
1696           std::swap (Lo, Hi);
1697         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1698         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1699                           DAG.getConstant(1, dl, MVT::i32));
1700       }
1701     } else {
1702       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1703                                InFlag);
1704       Chain = Val.getValue(1);
1705       InFlag = Val.getValue(2);
1706     }
1707 
1708     switch (VA.getLocInfo()) {
1709     default: llvm_unreachable("Unknown loc info!");
1710     case CCValAssign::Full: break;
1711     case CCValAssign::BCvt:
1712       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1713       break;
1714     }
1715 
1716     InVals.push_back(Val);
1717   }
1718 
1719   return Chain;
1720 }
1721 
1722 /// LowerMemOpCallTo - Store the argument to the stack.
1723 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1724                                             SDValue Arg, const SDLoc &dl,
1725                                             SelectionDAG &DAG,
1726                                             const CCValAssign &VA,
1727                                             ISD::ArgFlagsTy Flags) const {
1728   unsigned LocMemOffset = VA.getLocMemOffset();
1729   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1730   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1731                        StackPtr, PtrOff);
1732   return DAG.getStore(
1733       Chain, dl, Arg, PtrOff,
1734       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1735 }
1736 
1737 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1738                                          SDValue Chain, SDValue &Arg,
1739                                          RegsToPassVector &RegsToPass,
1740                                          CCValAssign &VA, CCValAssign &NextVA,
1741                                          SDValue &StackPtr,
1742                                          SmallVectorImpl<SDValue> &MemOpChains,
1743                                          ISD::ArgFlagsTy Flags) const {
1744 
1745   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1746                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1747   unsigned id = Subtarget->isLittle() ? 0 : 1;
1748   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1749 
1750   if (NextVA.isRegLoc())
1751     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1752   else {
1753     assert(NextVA.isMemLoc());
1754     if (!StackPtr.getNode())
1755       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1756                                     getPointerTy(DAG.getDataLayout()));
1757 
1758     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1759                                            dl, DAG, NextVA,
1760                                            Flags));
1761   }
1762 }
1763 
1764 /// LowerCall - Lowering a call into a callseq_start <-
1765 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1766 /// nodes.
1767 SDValue
1768 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1769                              SmallVectorImpl<SDValue> &InVals) const {
1770   SelectionDAG &DAG                     = CLI.DAG;
1771   SDLoc &dl                             = CLI.DL;
1772   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1773   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1774   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1775   SDValue Chain                         = CLI.Chain;
1776   SDValue Callee                        = CLI.Callee;
1777   bool &isTailCall                      = CLI.IsTailCall;
1778   CallingConv::ID CallConv              = CLI.CallConv;
1779   bool doesNotRet                       = CLI.DoesNotReturn;
1780   bool isVarArg                         = CLI.IsVarArg;
1781 
1782   MachineFunction &MF = DAG.getMachineFunction();
1783   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1784   bool isThisReturn   = false;
1785   bool isSibCall      = false;
1786   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1787 
1788   // Disable tail calls if they're not supported.
1789   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1790     isTailCall = false;
1791 
1792   if (isTailCall) {
1793     // Check if it's really possible to do a tail call.
1794     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1795                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1796                                                    Outs, OutVals, Ins, DAG);
1797     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1798       report_fatal_error("failed to perform tail call elimination on a call "
1799                          "site marked musttail");
1800     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1801     // detected sibcalls.
1802     if (isTailCall) {
1803       ++NumTailCalls;
1804       isSibCall = true;
1805     }
1806   }
1807 
1808   // Analyze operands of the call, assigning locations to each operand.
1809   SmallVector<CCValAssign, 16> ArgLocs;
1810   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1811                     *DAG.getContext(), Call);
1812   CCInfo.AnalyzeCallOperands(Outs,
1813                              CCAssignFnForNode(CallConv, /* Return*/ false,
1814                                                isVarArg));
1815 
1816   // Get a count of how many bytes are to be pushed on the stack.
1817   unsigned NumBytes = CCInfo.getNextStackOffset();
1818 
1819   // For tail calls, memory operands are available in our caller's stack.
1820   if (isSibCall)
1821     NumBytes = 0;
1822 
1823   // Adjust the stack pointer for the new arguments...
1824   // These operations are automatically eliminated by the prolog/epilog pass
1825   if (!isSibCall)
1826     Chain = DAG.getCALLSEQ_START(Chain,
1827                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1828 
1829   SDValue StackPtr =
1830       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1831 
1832   RegsToPassVector RegsToPass;
1833   SmallVector<SDValue, 8> MemOpChains;
1834 
1835   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1836   // of tail call optimization, arguments are handled later.
1837   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1838        i != e;
1839        ++i, ++realArgIdx) {
1840     CCValAssign &VA = ArgLocs[i];
1841     SDValue Arg = OutVals[realArgIdx];
1842     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1843     bool isByVal = Flags.isByVal();
1844 
1845     // Promote the value if needed.
1846     switch (VA.getLocInfo()) {
1847     default: llvm_unreachable("Unknown loc info!");
1848     case CCValAssign::Full: break;
1849     case CCValAssign::SExt:
1850       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1851       break;
1852     case CCValAssign::ZExt:
1853       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1854       break;
1855     case CCValAssign::AExt:
1856       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1857       break;
1858     case CCValAssign::BCvt:
1859       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1860       break;
1861     }
1862 
1863     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1864     if (VA.needsCustom()) {
1865       if (VA.getLocVT() == MVT::v2f64) {
1866         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1867                                   DAG.getConstant(0, dl, MVT::i32));
1868         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1869                                   DAG.getConstant(1, dl, MVT::i32));
1870 
1871         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1872                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1873 
1874         VA = ArgLocs[++i]; // skip ahead to next loc
1875         if (VA.isRegLoc()) {
1876           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1877                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1878         } else {
1879           assert(VA.isMemLoc());
1880 
1881           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1882                                                  dl, DAG, VA, Flags));
1883         }
1884       } else {
1885         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1886                          StackPtr, MemOpChains, Flags);
1887       }
1888     } else if (VA.isRegLoc()) {
1889       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1890         assert(VA.getLocVT() == MVT::i32 &&
1891                "unexpected calling convention register assignment");
1892         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1893                "unexpected use of 'returned'");
1894         isThisReturn = true;
1895       }
1896       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1897     } else if (isByVal) {
1898       assert(VA.isMemLoc());
1899       unsigned offset = 0;
1900 
1901       // True if this byval aggregate will be split between registers
1902       // and memory.
1903       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1904       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1905 
1906       if (CurByValIdx < ByValArgsCount) {
1907 
1908         unsigned RegBegin, RegEnd;
1909         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1910 
1911         EVT PtrVT =
1912             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1913         unsigned int i, j;
1914         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1915           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1916           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1917           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1918                                      MachinePointerInfo(),
1919                                      DAG.InferPtrAlignment(AddArg));
1920           MemOpChains.push_back(Load.getValue(1));
1921           RegsToPass.push_back(std::make_pair(j, Load));
1922         }
1923 
1924         // If parameter size outsides register area, "offset" value
1925         // helps us to calculate stack slot for remained part properly.
1926         offset = RegEnd - RegBegin;
1927 
1928         CCInfo.nextInRegsParam();
1929       }
1930 
1931       if (Flags.getByValSize() > 4*offset) {
1932         auto PtrVT = getPointerTy(DAG.getDataLayout());
1933         unsigned LocMemOffset = VA.getLocMemOffset();
1934         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1935         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1936         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1937         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1938         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1939                                            MVT::i32);
1940         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1941                                             MVT::i32);
1942 
1943         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1944         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1945         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1946                                           Ops));
1947       }
1948     } else if (!isSibCall) {
1949       assert(VA.isMemLoc());
1950 
1951       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1952                                              dl, DAG, VA, Flags));
1953     }
1954   }
1955 
1956   if (!MemOpChains.empty())
1957     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1958 
1959   // Build a sequence of copy-to-reg nodes chained together with token chain
1960   // and flag operands which copy the outgoing args into the appropriate regs.
1961   SDValue InFlag;
1962   // Tail call byval lowering might overwrite argument registers so in case of
1963   // tail call optimization the copies to registers are lowered later.
1964   if (!isTailCall)
1965     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1966       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1967                                RegsToPass[i].second, InFlag);
1968       InFlag = Chain.getValue(1);
1969     }
1970 
1971   // For tail calls lower the arguments to the 'real' stack slot.
1972   if (isTailCall) {
1973     // Force all the incoming stack arguments to be loaded from the stack
1974     // before any new outgoing arguments are stored to the stack, because the
1975     // outgoing stack slots may alias the incoming argument stack slots, and
1976     // the alias isn't otherwise explicit. This is slightly more conservative
1977     // than necessary, because it means that each store effectively depends
1978     // on every argument instead of just those arguments it would clobber.
1979 
1980     // Do not flag preceding copytoreg stuff together with the following stuff.
1981     InFlag = SDValue();
1982     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1983       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1984                                RegsToPass[i].second, InFlag);
1985       InFlag = Chain.getValue(1);
1986     }
1987     InFlag = SDValue();
1988   }
1989 
1990   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1991   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1992   // node so that legalize doesn't hack it.
1993   bool isDirect = false;
1994 
1995   const TargetMachine &TM = getTargetMachine();
1996   const Module *Mod = MF.getFunction()->getParent();
1997   const GlobalValue *GV = nullptr;
1998   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1999     GV = G->getGlobal();
2000   bool isStub =
2001       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2002 
2003   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2004   bool isLocalARMFunc = false;
2005   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2006   auto PtrVt = getPointerTy(DAG.getDataLayout());
2007 
2008   if (Subtarget->genLongCalls()) {
2009     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2010            "long-calls codegen is not position independent!");
2011     // Handle a global address or an external symbol. If it's not one of
2012     // those, the target's already in a register, so we don't need to do
2013     // anything extra.
2014     if (isa<GlobalAddressSDNode>(Callee)) {
2015       // Create a constant pool entry for the callee address
2016       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2017       ARMConstantPoolValue *CPV =
2018         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2019 
2020       // Get the address of the callee into a register
2021       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2022       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2023       Callee = DAG.getLoad(
2024           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2025           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2026     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2027       const char *Sym = S->getSymbol();
2028 
2029       // Create a constant pool entry for the callee address
2030       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2031       ARMConstantPoolValue *CPV =
2032         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2033                                       ARMPCLabelIndex, 0);
2034       // Get the address of the callee into a register
2035       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2036       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2037       Callee = DAG.getLoad(
2038           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2039           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2040     }
2041   } else if (isa<GlobalAddressSDNode>(Callee)) {
2042     // If we're optimizing for minimum size and the function is called three or
2043     // more times in this block, we can improve codesize by calling indirectly
2044     // as BLXr has a 16-bit encoding.
2045     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2046     auto *BB = CLI.CS->getParent();
2047     bool PreferIndirect =
2048         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2049         count_if(GV->users(), [&BB](const User *U) {
2050           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2051         }) > 2;
2052 
2053     if (!PreferIndirect) {
2054       isDirect = true;
2055       bool isDef = GV->isStrongDefinitionForLinker();
2056 
2057       // ARM call to a local ARM function is predicable.
2058       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2059       // tBX takes a register source operand.
2060       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2061         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2062         Callee = DAG.getNode(
2063             ARMISD::WrapperPIC, dl, PtrVt,
2064             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2065         Callee = DAG.getLoad(
2066             PtrVt, dl, DAG.getEntryNode(), Callee,
2067             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2068             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2069                                      MachineMemOperand::MOInvariant);
2070       } else if (Subtarget->isTargetCOFF()) {
2071         assert(Subtarget->isTargetWindows() &&
2072                "Windows is the only supported COFF target");
2073         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2074                                    ? ARMII::MO_DLLIMPORT
2075                                    : ARMII::MO_NO_FLAG;
2076         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2077                                             TargetFlags);
2078         if (GV->hasDLLImportStorageClass())
2079           Callee =
2080               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2081                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2082                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2083       } else {
2084         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2085       }
2086     }
2087   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088     isDirect = true;
2089     // tBX takes a register source operand.
2090     const char *Sym = S->getSymbol();
2091     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2092       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2093       ARMConstantPoolValue *CPV =
2094         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2095                                       ARMPCLabelIndex, 4);
2096       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2097       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2098       Callee = DAG.getLoad(
2099           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2100           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2101       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2102       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2103     } else {
2104       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2105     }
2106   }
2107 
2108   // FIXME: handle tail calls differently.
2109   unsigned CallOpc;
2110   if (Subtarget->isThumb()) {
2111     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2112       CallOpc = ARMISD::CALL_NOLINK;
2113     else
2114       CallOpc = ARMISD::CALL;
2115   } else {
2116     if (!isDirect && !Subtarget->hasV5TOps())
2117       CallOpc = ARMISD::CALL_NOLINK;
2118     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2119              // Emit regular call when code size is the priority
2120              !MF.getFunction()->optForMinSize())
2121       // "mov lr, pc; b _foo" to avoid confusing the RSP
2122       CallOpc = ARMISD::CALL_NOLINK;
2123     else
2124       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2125   }
2126 
2127   std::vector<SDValue> Ops;
2128   Ops.push_back(Chain);
2129   Ops.push_back(Callee);
2130 
2131   // Add argument registers to the end of the list so that they are known live
2132   // into the call.
2133   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2134     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2135                                   RegsToPass[i].second.getValueType()));
2136 
2137   // Add a register mask operand representing the call-preserved registers.
2138   if (!isTailCall) {
2139     const uint32_t *Mask;
2140     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2141     if (isThisReturn) {
2142       // For 'this' returns, use the R0-preserving mask if applicable
2143       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2144       if (!Mask) {
2145         // Set isThisReturn to false if the calling convention is not one that
2146         // allows 'returned' to be modeled in this way, so LowerCallResult does
2147         // not try to pass 'this' straight through
2148         isThisReturn = false;
2149         Mask = ARI->getCallPreservedMask(MF, CallConv);
2150       }
2151     } else
2152       Mask = ARI->getCallPreservedMask(MF, CallConv);
2153 
2154     assert(Mask && "Missing call preserved mask for calling convention");
2155     Ops.push_back(DAG.getRegisterMask(Mask));
2156   }
2157 
2158   if (InFlag.getNode())
2159     Ops.push_back(InFlag);
2160 
2161   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2162   if (isTailCall) {
2163     MF.getFrameInfo().setHasTailCall();
2164     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2165   }
2166 
2167   // Returns a chain and a flag for retval copy to use.
2168   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2169   InFlag = Chain.getValue(1);
2170 
2171   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2172                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2173   if (!Ins.empty())
2174     InFlag = Chain.getValue(1);
2175 
2176   // Handle result values, copying them out of physregs into vregs that we
2177   // return.
2178   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2179                          InVals, isThisReturn,
2180                          isThisReturn ? OutVals[0] : SDValue());
2181 }
2182 
2183 /// HandleByVal - Every parameter *after* a byval parameter is passed
2184 /// on the stack.  Remember the next parameter register to allocate,
2185 /// and then confiscate the rest of the parameter registers to insure
2186 /// this.
2187 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2188                                     unsigned Align) const {
2189   assert((State->getCallOrPrologue() == Prologue ||
2190           State->getCallOrPrologue() == Call) &&
2191          "unhandled ParmContext");
2192 
2193   // Byval (as with any stack) slots are always at least 4 byte aligned.
2194   Align = std::max(Align, 4U);
2195 
2196   unsigned Reg = State->AllocateReg(GPRArgRegs);
2197   if (!Reg)
2198     return;
2199 
2200   unsigned AlignInRegs = Align / 4;
2201   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2202   for (unsigned i = 0; i < Waste; ++i)
2203     Reg = State->AllocateReg(GPRArgRegs);
2204 
2205   if (!Reg)
2206     return;
2207 
2208   unsigned Excess = 4 * (ARM::R4 - Reg);
2209 
2210   // Special case when NSAA != SP and parameter size greater than size of
2211   // all remained GPR regs. In that case we can't split parameter, we must
2212   // send it to stack. We also must set NCRN to R4, so waste all
2213   // remained registers.
2214   const unsigned NSAAOffset = State->getNextStackOffset();
2215   if (NSAAOffset != 0 && Size > Excess) {
2216     while (State->AllocateReg(GPRArgRegs))
2217       ;
2218     return;
2219   }
2220 
2221   // First register for byval parameter is the first register that wasn't
2222   // allocated before this method call, so it would be "reg".
2223   // If parameter is small enough to be saved in range [reg, r4), then
2224   // the end (first after last) register would be reg + param-size-in-regs,
2225   // else parameter would be splitted between registers and stack,
2226   // end register would be r4 in this case.
2227   unsigned ByValRegBegin = Reg;
2228   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2229   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2230   // Note, first register is allocated in the beginning of function already,
2231   // allocate remained amount of registers we need.
2232   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2233     State->AllocateReg(GPRArgRegs);
2234   // A byval parameter that is split between registers and memory needs its
2235   // size truncated here.
2236   // In the case where the entire structure fits in registers, we set the
2237   // size in memory to zero.
2238   Size = std::max<int>(Size - Excess, 0);
2239 }
2240 
2241 /// MatchingStackOffset - Return true if the given stack call argument is
2242 /// already available in the same position (relatively) of the caller's
2243 /// incoming argument stack.
2244 static
2245 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2246                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2247                          const TargetInstrInfo *TII) {
2248   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2249   int FI = INT_MAX;
2250   if (Arg.getOpcode() == ISD::CopyFromReg) {
2251     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2252     if (!TargetRegisterInfo::isVirtualRegister(VR))
2253       return false;
2254     MachineInstr *Def = MRI->getVRegDef(VR);
2255     if (!Def)
2256       return false;
2257     if (!Flags.isByVal()) {
2258       if (!TII->isLoadFromStackSlot(*Def, FI))
2259         return false;
2260     } else {
2261       return false;
2262     }
2263   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2264     if (Flags.isByVal())
2265       // ByVal argument is passed in as a pointer but it's now being
2266       // dereferenced. e.g.
2267       // define @foo(%struct.X* %A) {
2268       //   tail call @bar(%struct.X* byval %A)
2269       // }
2270       return false;
2271     SDValue Ptr = Ld->getBasePtr();
2272     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2273     if (!FINode)
2274       return false;
2275     FI = FINode->getIndex();
2276   } else
2277     return false;
2278 
2279   assert(FI != INT_MAX);
2280   if (!MFI.isFixedObjectIndex(FI))
2281     return false;
2282   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2283 }
2284 
2285 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2286 /// for tail call optimization. Targets which want to do tail call
2287 /// optimization should implement this function.
2288 bool
2289 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2290                                                      CallingConv::ID CalleeCC,
2291                                                      bool isVarArg,
2292                                                      bool isCalleeStructRet,
2293                                                      bool isCallerStructRet,
2294                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2295                                     const SmallVectorImpl<SDValue> &OutVals,
2296                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2297                                                      SelectionDAG& DAG) const {
2298   MachineFunction &MF = DAG.getMachineFunction();
2299   const Function *CallerF = MF.getFunction();
2300   CallingConv::ID CallerCC = CallerF->getCallingConv();
2301 
2302   assert(Subtarget->supportsTailCall());
2303 
2304   // Look for obvious safe cases to perform tail call optimization that do not
2305   // require ABI changes. This is what gcc calls sibcall.
2306 
2307   // Do not sibcall optimize vararg calls unless the call site is not passing
2308   // any arguments.
2309   if (isVarArg && !Outs.empty())
2310     return false;
2311 
2312   // Exception-handling functions need a special set of instructions to indicate
2313   // a return to the hardware. Tail-calling another function would probably
2314   // break this.
2315   if (CallerF->hasFnAttribute("interrupt"))
2316     return false;
2317 
2318   // Also avoid sibcall optimization if either caller or callee uses struct
2319   // return semantics.
2320   if (isCalleeStructRet || isCallerStructRet)
2321     return false;
2322 
2323   // Externally-defined functions with weak linkage should not be
2324   // tail-called on ARM when the OS does not support dynamic
2325   // pre-emption of symbols, as the AAELF spec requires normal calls
2326   // to undefined weak functions to be replaced with a NOP or jump to the
2327   // next instruction. The behaviour of branch instructions in this
2328   // situation (as used for tail calls) is implementation-defined, so we
2329   // cannot rely on the linker replacing the tail call with a return.
2330   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2331     const GlobalValue *GV = G->getGlobal();
2332     const Triple &TT = getTargetMachine().getTargetTriple();
2333     if (GV->hasExternalWeakLinkage() &&
2334         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2335       return false;
2336   }
2337 
2338   // Check that the call results are passed in the same way.
2339   LLVMContext &C = *DAG.getContext();
2340   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2341                                   CCAssignFnForNode(CalleeCC, true, isVarArg),
2342                                   CCAssignFnForNode(CallerCC, true, isVarArg)))
2343     return false;
2344   // The callee has to preserve all registers the caller needs to preserve.
2345   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2346   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2347   if (CalleeCC != CallerCC) {
2348     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2349     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2350       return false;
2351   }
2352 
2353   // If Caller's vararg or byval argument has been split between registers and
2354   // stack, do not perform tail call, since part of the argument is in caller's
2355   // local frame.
2356   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2357   if (AFI_Caller->getArgRegsSaveSize())
2358     return false;
2359 
2360   // If the callee takes no arguments then go on to check the results of the
2361   // call.
2362   if (!Outs.empty()) {
2363     // Check if stack adjustment is needed. For now, do not do this if any
2364     // argument is passed on the stack.
2365     SmallVector<CCValAssign, 16> ArgLocs;
2366     ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call);
2367     CCInfo.AnalyzeCallOperands(Outs,
2368                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2369     if (CCInfo.getNextStackOffset()) {
2370       // Check if the arguments are already laid out in the right way as
2371       // the caller's fixed stack objects.
2372       MachineFrameInfo &MFI = MF.getFrameInfo();
2373       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2374       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2375       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2376            i != e;
2377            ++i, ++realArgIdx) {
2378         CCValAssign &VA = ArgLocs[i];
2379         EVT RegVT = VA.getLocVT();
2380         SDValue Arg = OutVals[realArgIdx];
2381         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2382         if (VA.getLocInfo() == CCValAssign::Indirect)
2383           return false;
2384         if (VA.needsCustom()) {
2385           // f64 and vector types are split into multiple registers or
2386           // register/stack-slot combinations.  The types will not match
2387           // the registers; give up on memory f64 refs until we figure
2388           // out what to do about this.
2389           if (!VA.isRegLoc())
2390             return false;
2391           if (!ArgLocs[++i].isRegLoc())
2392             return false;
2393           if (RegVT == MVT::v2f64) {
2394             if (!ArgLocs[++i].isRegLoc())
2395               return false;
2396             if (!ArgLocs[++i].isRegLoc())
2397               return false;
2398           }
2399         } else if (!VA.isRegLoc()) {
2400           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2401                                    MFI, MRI, TII))
2402             return false;
2403         }
2404       }
2405     }
2406 
2407     const MachineRegisterInfo &MRI = MF.getRegInfo();
2408     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2409       return false;
2410   }
2411 
2412   return true;
2413 }
2414 
2415 bool
2416 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2417                                   MachineFunction &MF, bool isVarArg,
2418                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2419                                   LLVMContext &Context) const {
2420   SmallVector<CCValAssign, 16> RVLocs;
2421   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2422   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2423                                                     isVarArg));
2424 }
2425 
2426 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2427                                     const SDLoc &DL, SelectionDAG &DAG) {
2428   const MachineFunction &MF = DAG.getMachineFunction();
2429   const Function *F = MF.getFunction();
2430 
2431   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2432 
2433   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2434   // version of the "preferred return address". These offsets affect the return
2435   // instruction if this is a return from PL1 without hypervisor extensions.
2436   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2437   //    SWI:     0      "subs pc, lr, #0"
2438   //    ABORT:   +4     "subs pc, lr, #4"
2439   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2440   // UNDEF varies depending on where the exception came from ARM or Thumb
2441   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2442 
2443   int64_t LROffset;
2444   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2445       IntKind == "ABORT")
2446     LROffset = 4;
2447   else if (IntKind == "SWI" || IntKind == "UNDEF")
2448     LROffset = 0;
2449   else
2450     report_fatal_error("Unsupported interrupt attribute. If present, value "
2451                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2452 
2453   RetOps.insert(RetOps.begin() + 1,
2454                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2455 
2456   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2457 }
2458 
2459 SDValue
2460 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2461                                bool isVarArg,
2462                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2463                                const SmallVectorImpl<SDValue> &OutVals,
2464                                const SDLoc &dl, SelectionDAG &DAG) const {
2465 
2466   // CCValAssign - represent the assignment of the return value to a location.
2467   SmallVector<CCValAssign, 16> RVLocs;
2468 
2469   // CCState - Info about the registers and stack slots.
2470   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2471                     *DAG.getContext(), Call);
2472 
2473   // Analyze outgoing return values.
2474   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2475                                                isVarArg));
2476 
2477   SDValue Flag;
2478   SmallVector<SDValue, 4> RetOps;
2479   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2480   bool isLittleEndian = Subtarget->isLittle();
2481 
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484   AFI->setReturnRegsCount(RVLocs.size());
2485 
2486   // Copy the result values into the output registers.
2487   for (unsigned i = 0, realRVLocIdx = 0;
2488        i != RVLocs.size();
2489        ++i, ++realRVLocIdx) {
2490     CCValAssign &VA = RVLocs[i];
2491     assert(VA.isRegLoc() && "Can only return in registers!");
2492 
2493     SDValue Arg = OutVals[realRVLocIdx];
2494 
2495     switch (VA.getLocInfo()) {
2496     default: llvm_unreachable("Unknown loc info!");
2497     case CCValAssign::Full: break;
2498     case CCValAssign::BCvt:
2499       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2500       break;
2501     }
2502 
2503     if (VA.needsCustom()) {
2504       if (VA.getLocVT() == MVT::v2f64) {
2505         // Extract the first half and return it in two registers.
2506         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2507                                    DAG.getConstant(0, dl, MVT::i32));
2508         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2509                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2510 
2511         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2512                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2513                                  Flag);
2514         Flag = Chain.getValue(1);
2515         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2516         VA = RVLocs[++i]; // skip ahead to next loc
2517         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2518                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2519                                  Flag);
2520         Flag = Chain.getValue(1);
2521         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2522         VA = RVLocs[++i]; // skip ahead to next loc
2523 
2524         // Extract the 2nd half and fall through to handle it as an f64 value.
2525         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2526                           DAG.getConstant(1, dl, MVT::i32));
2527       }
2528       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2529       // available.
2530       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2531                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2532       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2533                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2534                                Flag);
2535       Flag = Chain.getValue(1);
2536       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2537       VA = RVLocs[++i]; // skip ahead to next loc
2538       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2539                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2540                                Flag);
2541     } else
2542       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2543 
2544     // Guarantee that all emitted copies are
2545     // stuck together, avoiding something bad.
2546     Flag = Chain.getValue(1);
2547     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2548   }
2549   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2550   const MCPhysReg *I =
2551       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2552   if (I) {
2553     for (; *I; ++I) {
2554       if (ARM::GPRRegClass.contains(*I))
2555         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2556       else if (ARM::DPRRegClass.contains(*I))
2557         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2558       else
2559         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2560     }
2561   }
2562 
2563   // Update chain and glue.
2564   RetOps[0] = Chain;
2565   if (Flag.getNode())
2566     RetOps.push_back(Flag);
2567 
2568   // CPUs which aren't M-class use a special sequence to return from
2569   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2570   // though we use "subs pc, lr, #N").
2571   //
2572   // M-class CPUs actually use a normal return sequence with a special
2573   // (hardware-provided) value in LR, so the normal code path works.
2574   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2575       !Subtarget->isMClass()) {
2576     if (Subtarget->isThumb1Only())
2577       report_fatal_error("interrupt attribute is not supported in Thumb1");
2578     return LowerInterruptReturn(RetOps, dl, DAG);
2579   }
2580 
2581   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2582 }
2583 
2584 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2585   if (N->getNumValues() != 1)
2586     return false;
2587   if (!N->hasNUsesOfValue(1, 0))
2588     return false;
2589 
2590   SDValue TCChain = Chain;
2591   SDNode *Copy = *N->use_begin();
2592   if (Copy->getOpcode() == ISD::CopyToReg) {
2593     // If the copy has a glue operand, we conservatively assume it isn't safe to
2594     // perform a tail call.
2595     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2596       return false;
2597     TCChain = Copy->getOperand(0);
2598   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2599     SDNode *VMov = Copy;
2600     // f64 returned in a pair of GPRs.
2601     SmallPtrSet<SDNode*, 2> Copies;
2602     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2603          UI != UE; ++UI) {
2604       if (UI->getOpcode() != ISD::CopyToReg)
2605         return false;
2606       Copies.insert(*UI);
2607     }
2608     if (Copies.size() > 2)
2609       return false;
2610 
2611     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2612          UI != UE; ++UI) {
2613       SDValue UseChain = UI->getOperand(0);
2614       if (Copies.count(UseChain.getNode()))
2615         // Second CopyToReg
2616         Copy = *UI;
2617       else {
2618         // We are at the top of this chain.
2619         // If the copy has a glue operand, we conservatively assume it
2620         // isn't safe to perform a tail call.
2621         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2622           return false;
2623         // First CopyToReg
2624         TCChain = UseChain;
2625       }
2626     }
2627   } else if (Copy->getOpcode() == ISD::BITCAST) {
2628     // f32 returned in a single GPR.
2629     if (!Copy->hasOneUse())
2630       return false;
2631     Copy = *Copy->use_begin();
2632     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2633       return false;
2634     // If the copy has a glue operand, we conservatively assume it isn't safe to
2635     // perform a tail call.
2636     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2637       return false;
2638     TCChain = Copy->getOperand(0);
2639   } else {
2640     return false;
2641   }
2642 
2643   bool HasRet = false;
2644   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2645        UI != UE; ++UI) {
2646     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2647         UI->getOpcode() != ARMISD::INTRET_FLAG)
2648       return false;
2649     HasRet = true;
2650   }
2651 
2652   if (!HasRet)
2653     return false;
2654 
2655   Chain = TCChain;
2656   return true;
2657 }
2658 
2659 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2660   if (!Subtarget->supportsTailCall())
2661     return false;
2662 
2663   auto Attr =
2664       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2665   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2666     return false;
2667 
2668   return true;
2669 }
2670 
2671 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2672 // and pass the lower and high parts through.
2673 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2674   SDLoc DL(Op);
2675   SDValue WriteValue = Op->getOperand(2);
2676 
2677   // This function is only supposed to be called for i64 type argument.
2678   assert(WriteValue.getValueType() == MVT::i64
2679           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2680 
2681   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2682                            DAG.getConstant(0, DL, MVT::i32));
2683   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2684                            DAG.getConstant(1, DL, MVT::i32));
2685   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2686   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2687 }
2688 
2689 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2690 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2691 // one of the above mentioned nodes. It has to be wrapped because otherwise
2692 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2693 // be used to form addressing mode. These wrapped nodes will be selected
2694 // into MOVi.
2695 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2696   EVT PtrVT = Op.getValueType();
2697   // FIXME there is no actual debug info here
2698   SDLoc dl(Op);
2699   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2700   SDValue Res;
2701   if (CP->isMachineConstantPoolEntry())
2702     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2703                                     CP->getAlignment());
2704   else
2705     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2706                                     CP->getAlignment());
2707   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2708 }
2709 
2710 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2711   return MachineJumpTableInfo::EK_Inline;
2712 }
2713 
2714 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2715                                              SelectionDAG &DAG) const {
2716   MachineFunction &MF = DAG.getMachineFunction();
2717   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718   unsigned ARMPCLabelIndex = 0;
2719   SDLoc DL(Op);
2720   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2722   SDValue CPAddr;
2723   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2724   if (!IsPositionIndependent) {
2725     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2726   } else {
2727     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2728     ARMPCLabelIndex = AFI->createPICLabelUId();
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2731                                       ARMCP::CPBlockAddress, PCAdj);
2732     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2733   }
2734   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2735   SDValue Result = DAG.getLoad(
2736       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2737       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2738   if (!IsPositionIndependent)
2739     return Result;
2740   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2741   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2742 }
2743 
2744 /// \brief Convert a TLS address reference into the correct sequence of loads
2745 /// and calls to compute the variable's address for Darwin, and return an
2746 /// SDValue containing the final node.
2747 
2748 /// Darwin only has one TLS scheme which must be capable of dealing with the
2749 /// fully general situation, in the worst case. This means:
2750 ///     + "extern __thread" declaration.
2751 ///     + Defined in a possibly unknown dynamic library.
2752 ///
2753 /// The general system is that each __thread variable has a [3 x i32] descriptor
2754 /// which contains information used by the runtime to calculate the address. The
2755 /// only part of this the compiler needs to know about is the first word, which
2756 /// contains a function pointer that must be called with the address of the
2757 /// entire descriptor in "r0".
2758 ///
2759 /// Since this descriptor may be in a different unit, in general access must
2760 /// proceed along the usual ARM rules. A common sequence to produce is:
2761 ///
2762 ///     movw rT1, :lower16:_var$non_lazy_ptr
2763 ///     movt rT1, :upper16:_var$non_lazy_ptr
2764 ///     ldr r0, [rT1]
2765 ///     ldr rT2, [r0]
2766 ///     blx rT2
2767 ///     [...address now in r0...]
2768 SDValue
2769 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2770                                                SelectionDAG &DAG) const {
2771   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2772   SDLoc DL(Op);
2773 
2774   // First step is to get the address of the actua global symbol. This is where
2775   // the TLS descriptor lives.
2776   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2777 
2778   // The first entry in the descriptor is a function pointer that we must call
2779   // to obtain the address of the variable.
2780   SDValue Chain = DAG.getEntryNode();
2781   SDValue FuncTLVGet = DAG.getLoad(
2782       MVT::i32, DL, Chain, DescAddr,
2783       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2784       /* Alignment = */ 4,
2785       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2786           MachineMemOperand::MOInvariant);
2787   Chain = FuncTLVGet.getValue(1);
2788 
2789   MachineFunction &F = DAG.getMachineFunction();
2790   MachineFrameInfo &MFI = F.getFrameInfo();
2791   MFI.setAdjustsStack(true);
2792 
2793   // TLS calls preserve all registers except those that absolutely must be
2794   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2795   // silly).
2796   auto TRI =
2797       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2798   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2799   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2800 
2801   // Finally, we can make the call. This is just a degenerate version of a
2802   // normal AArch64 call node: r0 takes the address of the descriptor, and
2803   // returns the address of the variable in this thread.
2804   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2805   Chain =
2806       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2807                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2808                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2809   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2810 }
2811 
2812 SDValue
2813 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2814                                                 SelectionDAG &DAG) const {
2815   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2816 
2817   SDValue Chain = DAG.getEntryNode();
2818   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2819   SDLoc DL(Op);
2820 
2821   // Load the current TEB (thread environment block)
2822   SDValue Ops[] = {Chain,
2823                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2824                    DAG.getConstant(15, DL, MVT::i32),
2825                    DAG.getConstant(0, DL, MVT::i32),
2826                    DAG.getConstant(13, DL, MVT::i32),
2827                    DAG.getConstant(0, DL, MVT::i32),
2828                    DAG.getConstant(2, DL, MVT::i32)};
2829   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2830                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2831 
2832   SDValue TEB = CurrentTEB.getValue(0);
2833   Chain = CurrentTEB.getValue(1);
2834 
2835   // Load the ThreadLocalStoragePointer from the TEB
2836   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2837   SDValue TLSArray =
2838       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2839   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2840 
2841   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2842   // offset into the TLSArray.
2843 
2844   // Load the TLS index from the C runtime
2845   SDValue TLSIndex =
2846       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2847   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2848   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2849 
2850   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2851                               DAG.getConstant(2, DL, MVT::i32));
2852   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2853                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2854                             MachinePointerInfo());
2855 
2856   // Get the offset of the start of the .tls section (section base)
2857   const auto *GA = cast<GlobalAddressSDNode>(Op);
2858   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2859   SDValue Offset = DAG.getLoad(
2860       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2861                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2862       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2863 
2864   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2865 }
2866 
2867 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2868 SDValue
2869 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2870                                                  SelectionDAG &DAG) const {
2871   SDLoc dl(GA);
2872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2876   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2877   ARMConstantPoolValue *CPV =
2878     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2879                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2880   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2881   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2882   Argument = DAG.getLoad(
2883       PtrVT, dl, DAG.getEntryNode(), Argument,
2884       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2885   SDValue Chain = Argument.getValue(1);
2886 
2887   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2888   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2889 
2890   // call __tls_get_addr.
2891   ArgListTy Args;
2892   ArgListEntry Entry;
2893   Entry.Node = Argument;
2894   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2895   Args.push_back(Entry);
2896 
2897   // FIXME: is there useful debug info available here?
2898   TargetLowering::CallLoweringInfo CLI(DAG);
2899   CLI.setDebugLoc(dl).setChain(Chain)
2900     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2901                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2902 
2903   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2904   return CallResult.first;
2905 }
2906 
2907 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2908 // "local exec" model.
2909 SDValue
2910 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2911                                         SelectionDAG &DAG,
2912                                         TLSModel::Model model) const {
2913   const GlobalValue *GV = GA->getGlobal();
2914   SDLoc dl(GA);
2915   SDValue Offset;
2916   SDValue Chain = DAG.getEntryNode();
2917   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2918   // Get the Thread Pointer
2919   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2920 
2921   if (model == TLSModel::InitialExec) {
2922     MachineFunction &MF = DAG.getMachineFunction();
2923     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2924     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2925     // Initial exec model.
2926     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2927     ARMConstantPoolValue *CPV =
2928       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2929                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2930                                       true);
2931     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2932     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2933     Offset = DAG.getLoad(
2934         PtrVT, dl, Chain, Offset,
2935         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2936     Chain = Offset.getValue(1);
2937 
2938     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2939     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2940 
2941     Offset = DAG.getLoad(
2942         PtrVT, dl, Chain, Offset,
2943         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2944   } else {
2945     // local exec model
2946     assert(model == TLSModel::LocalExec);
2947     ARMConstantPoolValue *CPV =
2948       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2949     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2951     Offset = DAG.getLoad(
2952         PtrVT, dl, Chain, Offset,
2953         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2954   }
2955 
2956   // The address of the thread local variable is the add of the thread
2957   // pointer with the offset of the variable.
2958   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2959 }
2960 
2961 SDValue
2962 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2963   if (Subtarget->isTargetDarwin())
2964     return LowerGlobalTLSAddressDarwin(Op, DAG);
2965 
2966   if (Subtarget->isTargetWindows())
2967     return LowerGlobalTLSAddressWindows(Op, DAG);
2968 
2969   // TODO: implement the "local dynamic" model
2970   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2971   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2972   if (DAG.getTarget().Options.EmulatedTLS)
2973     return LowerToTLSEmulatedModel(GA, DAG);
2974 
2975   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2976 
2977   switch (model) {
2978     case TLSModel::GeneralDynamic:
2979     case TLSModel::LocalDynamic:
2980       return LowerToTLSGeneralDynamicModel(GA, DAG);
2981     case TLSModel::InitialExec:
2982     case TLSModel::LocalExec:
2983       return LowerToTLSExecModels(GA, DAG, model);
2984   }
2985   llvm_unreachable("bogus TLS model");
2986 }
2987 
2988 /// Return true if all users of V are within function F, looking through
2989 /// ConstantExprs.
2990 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2991   SmallVector<const User*,4> Worklist;
2992   for (auto *U : V->users())
2993     Worklist.push_back(U);
2994   while (!Worklist.empty()) {
2995     auto *U = Worklist.pop_back_val();
2996     if (isa<ConstantExpr>(U)) {
2997       for (auto *UU : U->users())
2998         Worklist.push_back(UU);
2999       continue;
3000     }
3001 
3002     auto *I = dyn_cast<Instruction>(U);
3003     if (!I || I->getParent()->getParent() != F)
3004       return false;
3005   }
3006   return true;
3007 }
3008 
3009 /// Return true if all users of V are within some (any) function, looking through
3010 /// ConstantExprs. In other words, are there any global constant users?
3011 static bool allUsersAreInFunctions(const Value *V) {
3012   SmallVector<const User*,4> Worklist;
3013   for (auto *U : V->users())
3014     Worklist.push_back(U);
3015   while (!Worklist.empty()) {
3016     auto *U = Worklist.pop_back_val();
3017     if (isa<ConstantExpr>(U)) {
3018       for (auto *UU : U->users())
3019         Worklist.push_back(UU);
3020       continue;
3021     }
3022 
3023     if (!isa<Instruction>(U))
3024       return false;
3025   }
3026   return true;
3027 }
3028 
3029 // Return true if T is an integer, float or an array/vector of either.
3030 static bool isSimpleType(Type *T) {
3031   if (T->isIntegerTy() || T->isFloatingPointTy())
3032     return true;
3033   Type *SubT = nullptr;
3034   if (T->isArrayTy())
3035     SubT = T->getArrayElementType();
3036   else if (T->isVectorTy())
3037     SubT = T->getVectorElementType();
3038   else
3039     return false;
3040   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3041 }
3042 
3043 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3044                                      EVT PtrVT, SDLoc dl) {
3045   // If we're creating a pool entry for a constant global with unnamed address,
3046   // and the global is small enough, we can emit it inline into the constant pool
3047   // to save ourselves an indirection.
3048   //
3049   // This is a win if the constant is only used in one function (so it doesn't
3050   // need to be duplicated) or duplicating the constant wouldn't increase code
3051   // size (implying the constant is no larger than 4 bytes).
3052   const Function *F = DAG.getMachineFunction().getFunction();
3053 
3054   // We rely on this decision to inline being idemopotent and unrelated to the
3055   // use-site. We know that if we inline a variable at one use site, we'll
3056   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3057   // doesn't know about this optimization, so bail out if it's enabled else
3058   // we could decide to inline here (and thus never emit the GV) but require
3059   // the GV from fast-isel generated code.
3060   if (!EnableConstpoolPromotion ||
3061       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3062       return SDValue();
3063 
3064   auto *GVar = dyn_cast<GlobalVariable>(GV);
3065   if (!GVar || !GVar->hasInitializer() ||
3066       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3067       !GVar->hasLocalLinkage())
3068     return SDValue();
3069 
3070   // Ensure that we don't try and inline any type that contains pointers. If
3071   // we inline a value that contains relocations, we move the relocations from
3072   // .data to .text which is not ideal.
3073   auto *Init = GVar->getInitializer();
3074   if (!isSimpleType(Init->getType()))
3075     return SDValue();
3076 
3077   // The constant islands pass can only really deal with alignment requests
3078   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3079   // any type wanting greater alignment requirements than 4 bytes. We also
3080   // can only promote constants that are multiples of 4 bytes in size or
3081   // are paddable to a multiple of 4. Currently we only try and pad constants
3082   // that are strings for simplicity.
3083   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3084   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3085   unsigned Align = GVar->getAlignment();
3086   unsigned RequiredPadding = 4 - (Size % 4);
3087   bool PaddingPossible =
3088     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3089   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize)
3090     return SDValue();
3091 
3092   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3093   MachineFunction &MF = DAG.getMachineFunction();
3094   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3095 
3096   // We can't bloat the constant pool too much, else the ConstantIslands pass
3097   // may fail to converge. If we haven't promoted this global yet (it may have
3098   // multiple uses), and promoting it would increase the constant pool size (Sz
3099   // > 4), ensure we have space to do so up to MaxTotal.
3100   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3101     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3102         ConstpoolPromotionMaxTotal)
3103       return SDValue();
3104 
3105   // This is only valid if all users are in a single function OR it has users
3106   // in multiple functions but it no larger than a pointer. We also check if
3107   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3108   // address taken.
3109   if (!allUsersAreInFunction(GVar, F) &&
3110       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3111     return SDValue();
3112 
3113   // We're going to inline this global. Pad it out if needed.
3114   if (RequiredPadding != 4) {
3115     StringRef S = CDAInit->getAsString();
3116 
3117     SmallVector<uint8_t,16> V(S.size());
3118     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3119     while (RequiredPadding--)
3120       V.push_back(0);
3121     Init = ConstantDataArray::get(*DAG.getContext(), V);
3122   }
3123 
3124   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3125   SDValue CPAddr =
3126     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3127   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3128     AFI->markGlobalAsPromotedToConstantPool(GVar);
3129     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3130                                       PaddedSize - 4);
3131   }
3132   ++NumConstpoolPromoted;
3133   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3134 }
3135 
3136 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3137                                                  SelectionDAG &DAG) const {
3138   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3139   SDLoc dl(Op);
3140   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3141   const TargetMachine &TM = getTargetMachine();
3142   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3143     GV = GA->getBaseObject();
3144   bool IsRO =
3145       (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3146       isa<Function>(GV);
3147 
3148   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3149     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3150       return V;
3151 
3152   if (isPositionIndependent()) {
3153     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3154 
3155     MachineFunction &MF = DAG.getMachineFunction();
3156     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3157     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3158     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3159     SDLoc dl(Op);
3160     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3161     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3162         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3163         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3164         /*AddCurrentAddress=*/UseGOT_PREL);
3165     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3166     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3167     SDValue Result = DAG.getLoad(
3168         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3169         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3170     SDValue Chain = Result.getValue(1);
3171     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3172     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3173     if (UseGOT_PREL)
3174       Result =
3175           DAG.getLoad(PtrVT, dl, Chain, Result,
3176                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3177     return Result;
3178   } else if (Subtarget->isROPI() && IsRO) {
3179     // PC-relative.
3180     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3181     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3182     return Result;
3183   } else if (Subtarget->isRWPI() && !IsRO) {
3184     // SB-relative.
3185     ARMConstantPoolValue *CPV =
3186       ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3187     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3188     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3189     SDValue G = DAG.getLoad(
3190         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3191         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3192     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3193     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G);
3194     return Result;
3195   }
3196 
3197   // If we have T2 ops, we can materialize the address directly via movt/movw
3198   // pair. This is always cheaper.
3199   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3200     ++NumMovwMovt;
3201     // FIXME: Once remat is capable of dealing with instructions with register
3202     // operands, expand this into two nodes.
3203     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3204                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3205   } else {
3206     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3207     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3208     return DAG.getLoad(
3209         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3210         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3211   }
3212 }
3213 
3214 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3215                                                     SelectionDAG &DAG) const {
3216   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3217          "ROPI/RWPI not currently supported for Darwin");
3218   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3219   SDLoc dl(Op);
3220   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3221 
3222   if (Subtarget->useMovt(DAG.getMachineFunction()))
3223     ++NumMovwMovt;
3224 
3225   // FIXME: Once remat is capable of dealing with instructions with register
3226   // operands, expand this into multiple nodes
3227   unsigned Wrapper =
3228       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3229 
3230   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3231   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3232 
3233   if (Subtarget->isGVIndirectSymbol(GV))
3234     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3235                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3236   return Result;
3237 }
3238 
3239 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3240                                                      SelectionDAG &DAG) const {
3241   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3242   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3243          "Windows on ARM expects to use movw/movt");
3244   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3245          "ROPI/RWPI not currently supported for Windows");
3246 
3247   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3248   const ARMII::TOF TargetFlags =
3249     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3250   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3251   SDValue Result;
3252   SDLoc DL(Op);
3253 
3254   ++NumMovwMovt;
3255 
3256   // FIXME: Once remat is capable of dealing with instructions with register
3257   // operands, expand this into two nodes.
3258   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3259                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3260                                                   TargetFlags));
3261   if (GV->hasDLLImportStorageClass())
3262     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3263                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3264   return Result;
3265 }
3266 
3267 SDValue
3268 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3269   SDLoc dl(Op);
3270   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3271   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3272                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3273                      Op.getOperand(1), Val);
3274 }
3275 
3276 SDValue
3277 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3278   SDLoc dl(Op);
3279   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3280                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3281 }
3282 
3283 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3284                                                       SelectionDAG &DAG) const {
3285   SDLoc dl(Op);
3286   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3287                      Op.getOperand(0));
3288 }
3289 
3290 SDValue
3291 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3292                                           const ARMSubtarget *Subtarget) const {
3293   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3294   SDLoc dl(Op);
3295   switch (IntNo) {
3296   default: return SDValue();    // Don't custom lower most intrinsics.
3297   case Intrinsic::arm_rbit: {
3298     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
3299            "RBIT intrinsic must have i32 type!");
3300     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
3301   }
3302   case Intrinsic::thread_pointer: {
3303     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3304     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3305   }
3306   case Intrinsic::eh_sjlj_lsda: {
3307     MachineFunction &MF = DAG.getMachineFunction();
3308     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3309     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3310     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3311     SDValue CPAddr;
3312     bool IsPositionIndependent = isPositionIndependent();
3313     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3314     ARMConstantPoolValue *CPV =
3315       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3316                                       ARMCP::CPLSDA, PCAdj);
3317     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3318     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3319     SDValue Result = DAG.getLoad(
3320         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3321         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3322 
3323     if (IsPositionIndependent) {
3324       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3325       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3326     }
3327     return Result;
3328   }
3329   case Intrinsic::arm_neon_vmulls:
3330   case Intrinsic::arm_neon_vmullu: {
3331     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3332       ? ARMISD::VMULLs : ARMISD::VMULLu;
3333     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3334                        Op.getOperand(1), Op.getOperand(2));
3335   }
3336   case Intrinsic::arm_neon_vminnm:
3337   case Intrinsic::arm_neon_vmaxnm: {
3338     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3339       ? ISD::FMINNUM : ISD::FMAXNUM;
3340     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3341                        Op.getOperand(1), Op.getOperand(2));
3342   }
3343   case Intrinsic::arm_neon_vminu:
3344   case Intrinsic::arm_neon_vmaxu: {
3345     if (Op.getValueType().isFloatingPoint())
3346       return SDValue();
3347     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3348       ? ISD::UMIN : ISD::UMAX;
3349     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3350                          Op.getOperand(1), Op.getOperand(2));
3351   }
3352   case Intrinsic::arm_neon_vmins:
3353   case Intrinsic::arm_neon_vmaxs: {
3354     // v{min,max}s is overloaded between signed integers and floats.
3355     if (!Op.getValueType().isFloatingPoint()) {
3356       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3357         ? ISD::SMIN : ISD::SMAX;
3358       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3359                          Op.getOperand(1), Op.getOperand(2));
3360     }
3361     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3362       ? ISD::FMINNAN : ISD::FMAXNAN;
3363     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3364                        Op.getOperand(1), Op.getOperand(2));
3365   }
3366   }
3367 }
3368 
3369 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3370                                  const ARMSubtarget *Subtarget) {
3371   // FIXME: handle "fence singlethread" more efficiently.
3372   SDLoc dl(Op);
3373   if (!Subtarget->hasDataBarrier()) {
3374     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3375     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3376     // here.
3377     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3378            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3379     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3380                        DAG.getConstant(0, dl, MVT::i32));
3381   }
3382 
3383   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3384   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3385   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3386   if (Subtarget->isMClass()) {
3387     // Only a full system barrier exists in the M-class architectures.
3388     Domain = ARM_MB::SY;
3389   } else if (Subtarget->preferISHSTBarriers() &&
3390              Ord == AtomicOrdering::Release) {
3391     // Swift happens to implement ISHST barriers in a way that's compatible with
3392     // Release semantics but weaker than ISH so we'd be fools not to use
3393     // it. Beware: other processors probably don't!
3394     Domain = ARM_MB::ISHST;
3395   }
3396 
3397   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3398                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3399                      DAG.getConstant(Domain, dl, MVT::i32));
3400 }
3401 
3402 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3403                              const ARMSubtarget *Subtarget) {
3404   // ARM pre v5TE and Thumb1 does not have preload instructions.
3405   if (!(Subtarget->isThumb2() ||
3406         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3407     // Just preserve the chain.
3408     return Op.getOperand(0);
3409 
3410   SDLoc dl(Op);
3411   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3412   if (!isRead &&
3413       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3414     // ARMv7 with MP extension has PLDW.
3415     return Op.getOperand(0);
3416 
3417   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3418   if (Subtarget->isThumb()) {
3419     // Invert the bits.
3420     isRead = ~isRead & 1;
3421     isData = ~isData & 1;
3422   }
3423 
3424   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3425                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3426                      DAG.getConstant(isData, dl, MVT::i32));
3427 }
3428 
3429 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3430   MachineFunction &MF = DAG.getMachineFunction();
3431   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3432 
3433   // vastart just stores the address of the VarArgsFrameIndex slot into the
3434   // memory location argument.
3435   SDLoc dl(Op);
3436   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3437   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3438   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3439   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3440                       MachinePointerInfo(SV));
3441 }
3442 
3443 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3444                                                 CCValAssign &NextVA,
3445                                                 SDValue &Root,
3446                                                 SelectionDAG &DAG,
3447                                                 const SDLoc &dl) const {
3448   MachineFunction &MF = DAG.getMachineFunction();
3449   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3450 
3451   const TargetRegisterClass *RC;
3452   if (AFI->isThumb1OnlyFunction())
3453     RC = &ARM::tGPRRegClass;
3454   else
3455     RC = &ARM::GPRRegClass;
3456 
3457   // Transform the arguments stored in physical registers into virtual ones.
3458   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3459   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3460 
3461   SDValue ArgValue2;
3462   if (NextVA.isMemLoc()) {
3463     MachineFrameInfo &MFI = MF.getFrameInfo();
3464     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3465 
3466     // Create load node to retrieve arguments from the stack.
3467     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3468     ArgValue2 = DAG.getLoad(
3469         MVT::i32, dl, Root, FIN,
3470         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3471   } else {
3472     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3473     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3474   }
3475   if (!Subtarget->isLittle())
3476     std::swap (ArgValue, ArgValue2);
3477   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3478 }
3479 
3480 // The remaining GPRs hold either the beginning of variable-argument
3481 // data, or the beginning of an aggregate passed by value (usually
3482 // byval).  Either way, we allocate stack slots adjacent to the data
3483 // provided by our caller, and store the unallocated registers there.
3484 // If this is a variadic function, the va_list pointer will begin with
3485 // these values; otherwise, this reassembles a (byval) structure that
3486 // was split between registers and memory.
3487 // Return: The frame index registers were stored into.
3488 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3489                                       const SDLoc &dl, SDValue &Chain,
3490                                       const Value *OrigArg,
3491                                       unsigned InRegsParamRecordIdx,
3492                                       int ArgOffset, unsigned ArgSize) const {
3493   // Currently, two use-cases possible:
3494   // Case #1. Non-var-args function, and we meet first byval parameter.
3495   //          Setup first unallocated register as first byval register;
3496   //          eat all remained registers
3497   //          (these two actions are performed by HandleByVal method).
3498   //          Then, here, we initialize stack frame with
3499   //          "store-reg" instructions.
3500   // Case #2. Var-args function, that doesn't contain byval parameters.
3501   //          The same: eat all remained unallocated registers,
3502   //          initialize stack frame.
3503 
3504   MachineFunction &MF = DAG.getMachineFunction();
3505   MachineFrameInfo &MFI = MF.getFrameInfo();
3506   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3507   unsigned RBegin, REnd;
3508   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3509     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3510   } else {
3511     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3512     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3513     REnd = ARM::R4;
3514   }
3515 
3516   if (REnd != RBegin)
3517     ArgOffset = -4 * (ARM::R4 - RBegin);
3518 
3519   auto PtrVT = getPointerTy(DAG.getDataLayout());
3520   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3521   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3522 
3523   SmallVector<SDValue, 4> MemOps;
3524   const TargetRegisterClass *RC =
3525       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3526 
3527   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3528     unsigned VReg = MF.addLiveIn(Reg, RC);
3529     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3530     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3531                                  MachinePointerInfo(OrigArg, 4 * i));
3532     MemOps.push_back(Store);
3533     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3534   }
3535 
3536   if (!MemOps.empty())
3537     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3538   return FrameIndex;
3539 }
3540 
3541 // Setup stack frame, the va_list pointer will start from.
3542 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3543                                              const SDLoc &dl, SDValue &Chain,
3544                                              unsigned ArgOffset,
3545                                              unsigned TotalArgRegsSaveSize,
3546                                              bool ForceMutable) const {
3547   MachineFunction &MF = DAG.getMachineFunction();
3548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3549 
3550   // Try to store any remaining integer argument regs
3551   // to their spots on the stack so that they may be loaded by dereferencing
3552   // the result of va_next.
3553   // If there is no regs to be stored, just point address after last
3554   // argument passed via stack.
3555   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3556                                   CCInfo.getInRegsParamsCount(),
3557                                   CCInfo.getNextStackOffset(), 4);
3558   AFI->setVarArgsFrameIndex(FrameIndex);
3559 }
3560 
3561 SDValue ARMTargetLowering::LowerFormalArguments(
3562     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3563     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3564     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3565   MachineFunction &MF = DAG.getMachineFunction();
3566   MachineFrameInfo &MFI = MF.getFrameInfo();
3567 
3568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3569 
3570   // Assign locations to all of the incoming arguments.
3571   SmallVector<CCValAssign, 16> ArgLocs;
3572   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3573                     *DAG.getContext(), Prologue);
3574   CCInfo.AnalyzeFormalArguments(Ins,
3575                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3576                                                   isVarArg));
3577 
3578   SmallVector<SDValue, 16> ArgValues;
3579   SDValue ArgValue;
3580   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3581   unsigned CurArgIdx = 0;
3582 
3583   // Initially ArgRegsSaveSize is zero.
3584   // Then we increase this value each time we meet byval parameter.
3585   // We also increase this value in case of varargs function.
3586   AFI->setArgRegsSaveSize(0);
3587 
3588   // Calculate the amount of stack space that we need to allocate to store
3589   // byval and variadic arguments that are passed in registers.
3590   // We need to know this before we allocate the first byval or variadic
3591   // argument, as they will be allocated a stack slot below the CFA (Canonical
3592   // Frame Address, the stack pointer at entry to the function).
3593   unsigned ArgRegBegin = ARM::R4;
3594   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3595     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3596       break;
3597 
3598     CCValAssign &VA = ArgLocs[i];
3599     unsigned Index = VA.getValNo();
3600     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3601     if (!Flags.isByVal())
3602       continue;
3603 
3604     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3605     unsigned RBegin, REnd;
3606     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3607     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3608 
3609     CCInfo.nextInRegsParam();
3610   }
3611   CCInfo.rewindByValRegsInfo();
3612 
3613   int lastInsIndex = -1;
3614   if (isVarArg && MFI.hasVAStart()) {
3615     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3616     if (RegIdx != array_lengthof(GPRArgRegs))
3617       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3618   }
3619 
3620   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3621   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3622   auto PtrVT = getPointerTy(DAG.getDataLayout());
3623 
3624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3625     CCValAssign &VA = ArgLocs[i];
3626     if (Ins[VA.getValNo()].isOrigArg()) {
3627       std::advance(CurOrigArg,
3628                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3629       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3630     }
3631     // Arguments stored in registers.
3632     if (VA.isRegLoc()) {
3633       EVT RegVT = VA.getLocVT();
3634 
3635       if (VA.needsCustom()) {
3636         // f64 and vector types are split up into multiple registers or
3637         // combinations of registers and stack slots.
3638         if (VA.getLocVT() == MVT::v2f64) {
3639           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3640                                                    Chain, DAG, dl);
3641           VA = ArgLocs[++i]; // skip ahead to next loc
3642           SDValue ArgValue2;
3643           if (VA.isMemLoc()) {
3644             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3645             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3646             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3647                                     MachinePointerInfo::getFixedStack(
3648                                         DAG.getMachineFunction(), FI));
3649           } else {
3650             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3651                                              Chain, DAG, dl);
3652           }
3653           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3654           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3655                                  ArgValue, ArgValue1,
3656                                  DAG.getIntPtrConstant(0, dl));
3657           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3658                                  ArgValue, ArgValue2,
3659                                  DAG.getIntPtrConstant(1, dl));
3660         } else
3661           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3662 
3663       } else {
3664         const TargetRegisterClass *RC;
3665 
3666         if (RegVT == MVT::f32)
3667           RC = &ARM::SPRRegClass;
3668         else if (RegVT == MVT::f64)
3669           RC = &ARM::DPRRegClass;
3670         else if (RegVT == MVT::v2f64)
3671           RC = &ARM::QPRRegClass;
3672         else if (RegVT == MVT::i32)
3673           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3674                                            : &ARM::GPRRegClass;
3675         else
3676           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3677 
3678         // Transform the arguments in physical registers into virtual ones.
3679         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3680         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3681       }
3682 
3683       // If this is an 8 or 16-bit value, it is really passed promoted
3684       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3685       // truncate to the right size.
3686       switch (VA.getLocInfo()) {
3687       default: llvm_unreachable("Unknown loc info!");
3688       case CCValAssign::Full: break;
3689       case CCValAssign::BCvt:
3690         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3691         break;
3692       case CCValAssign::SExt:
3693         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3694                                DAG.getValueType(VA.getValVT()));
3695         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3696         break;
3697       case CCValAssign::ZExt:
3698         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3699                                DAG.getValueType(VA.getValVT()));
3700         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3701         break;
3702       }
3703 
3704       InVals.push_back(ArgValue);
3705 
3706     } else { // VA.isRegLoc()
3707 
3708       // sanity check
3709       assert(VA.isMemLoc());
3710       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3711 
3712       int index = VA.getValNo();
3713 
3714       // Some Ins[] entries become multiple ArgLoc[] entries.
3715       // Process them only once.
3716       if (index != lastInsIndex)
3717         {
3718           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3719           // FIXME: For now, all byval parameter objects are marked mutable.
3720           // This can be changed with more analysis.
3721           // In case of tail call optimization mark all arguments mutable.
3722           // Since they could be overwritten by lowering of arguments in case of
3723           // a tail call.
3724           if (Flags.isByVal()) {
3725             assert(Ins[index].isOrigArg() &&
3726                    "Byval arguments cannot be implicit");
3727             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3728 
3729             int FrameIndex = StoreByValRegs(
3730                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3731                 VA.getLocMemOffset(), Flags.getByValSize());
3732             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3733             CCInfo.nextInRegsParam();
3734           } else {
3735             unsigned FIOffset = VA.getLocMemOffset();
3736             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3737                                            FIOffset, true);
3738 
3739             // Create load nodes to retrieve arguments from the stack.
3740             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3741             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3742                                          MachinePointerInfo::getFixedStack(
3743                                              DAG.getMachineFunction(), FI)));
3744           }
3745           lastInsIndex = index;
3746         }
3747     }
3748   }
3749 
3750   // varargs
3751   if (isVarArg && MFI.hasVAStart())
3752     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3753                          CCInfo.getNextStackOffset(),
3754                          TotalArgRegsSaveSize);
3755 
3756   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3757 
3758   return Chain;
3759 }
3760 
3761 /// isFloatingPointZero - Return true if this is +0.0.
3762 static bool isFloatingPointZero(SDValue Op) {
3763   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3764     return CFP->getValueAPF().isPosZero();
3765   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3766     // Maybe this has already been legalized into the constant pool?
3767     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3768       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3769       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3770         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3771           return CFP->getValueAPF().isPosZero();
3772     }
3773   } else if (Op->getOpcode() == ISD::BITCAST &&
3774              Op->getValueType(0) == MVT::f64) {
3775     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3776     // created by LowerConstantFP().
3777     SDValue BitcastOp = Op->getOperand(0);
3778     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3779         isNullConstant(BitcastOp->getOperand(0)))
3780       return true;
3781   }
3782   return false;
3783 }
3784 
3785 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3786 /// the given operands.
3787 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3788                                      SDValue &ARMcc, SelectionDAG &DAG,
3789                                      const SDLoc &dl) const {
3790   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3791     unsigned C = RHSC->getZExtValue();
3792     if (!isLegalICmpImmediate(C)) {
3793       // Constant does not fit, try adjusting it by one?
3794       switch (CC) {
3795       default: break;
3796       case ISD::SETLT:
3797       case ISD::SETGE:
3798         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3799           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3800           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3801         }
3802         break;
3803       case ISD::SETULT:
3804       case ISD::SETUGE:
3805         if (C != 0 && isLegalICmpImmediate(C-1)) {
3806           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3807           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3808         }
3809         break;
3810       case ISD::SETLE:
3811       case ISD::SETGT:
3812         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3813           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3814           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3815         }
3816         break;
3817       case ISD::SETULE:
3818       case ISD::SETUGT:
3819         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3820           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3821           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3822         }
3823         break;
3824       }
3825     }
3826   }
3827 
3828   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3829   ARMISD::NodeType CompareType;
3830   switch (CondCode) {
3831   default:
3832     CompareType = ARMISD::CMP;
3833     break;
3834   case ARMCC::EQ:
3835   case ARMCC::NE:
3836     // Uses only Z Flag
3837     CompareType = ARMISD::CMPZ;
3838     break;
3839   }
3840   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3841   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3842 }
3843 
3844 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3845 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3846                                      SelectionDAG &DAG, const SDLoc &dl) const {
3847   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3848   SDValue Cmp;
3849   if (!isFloatingPointZero(RHS))
3850     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3851   else
3852     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3853   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3854 }
3855 
3856 /// duplicateCmp - Glue values can have only one use, so this function
3857 /// duplicates a comparison node.
3858 SDValue
3859 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3860   unsigned Opc = Cmp.getOpcode();
3861   SDLoc DL(Cmp);
3862   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3863     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3864 
3865   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3866   Cmp = Cmp.getOperand(0);
3867   Opc = Cmp.getOpcode();
3868   if (Opc == ARMISD::CMPFP)
3869     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3870   else {
3871     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3872     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3873   }
3874   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3875 }
3876 
3877 std::pair<SDValue, SDValue>
3878 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3879                                  SDValue &ARMcc) const {
3880   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3881 
3882   SDValue Value, OverflowCmp;
3883   SDValue LHS = Op.getOperand(0);
3884   SDValue RHS = Op.getOperand(1);
3885   SDLoc dl(Op);
3886 
3887   // FIXME: We are currently always generating CMPs because we don't support
3888   // generating CMN through the backend. This is not as good as the natural
3889   // CMP case because it causes a register dependency and cannot be folded
3890   // later.
3891 
3892   switch (Op.getOpcode()) {
3893   default:
3894     llvm_unreachable("Unknown overflow instruction!");
3895   case ISD::SADDO:
3896     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3897     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3898     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3899     break;
3900   case ISD::UADDO:
3901     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3902     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3903     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3904     break;
3905   case ISD::SSUBO:
3906     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3907     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3908     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3909     break;
3910   case ISD::USUBO:
3911     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3912     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3913     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3914     break;
3915   } // switch (...)
3916 
3917   return std::make_pair(Value, OverflowCmp);
3918 }
3919 
3920 
3921 SDValue
3922 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3923   // Let legalize expand this if it isn't a legal type yet.
3924   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3925     return SDValue();
3926 
3927   SDValue Value, OverflowCmp;
3928   SDValue ARMcc;
3929   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3930   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3931   SDLoc dl(Op);
3932   // We use 0 and 1 as false and true values.
3933   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3934   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3935   EVT VT = Op.getValueType();
3936 
3937   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3938                                  ARMcc, CCR, OverflowCmp);
3939 
3940   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3941   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3942 }
3943 
3944 
3945 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3946   SDValue Cond = Op.getOperand(0);
3947   SDValue SelectTrue = Op.getOperand(1);
3948   SDValue SelectFalse = Op.getOperand(2);
3949   SDLoc dl(Op);
3950   unsigned Opc = Cond.getOpcode();
3951 
3952   if (Cond.getResNo() == 1 &&
3953       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3954        Opc == ISD::USUBO)) {
3955     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3956       return SDValue();
3957 
3958     SDValue Value, OverflowCmp;
3959     SDValue ARMcc;
3960     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3961     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3962     EVT VT = Op.getValueType();
3963 
3964     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3965                    OverflowCmp, DAG);
3966   }
3967 
3968   // Convert:
3969   //
3970   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3971   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3972   //
3973   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3974     const ConstantSDNode *CMOVTrue =
3975       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3976     const ConstantSDNode *CMOVFalse =
3977       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3978 
3979     if (CMOVTrue && CMOVFalse) {
3980       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3981       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3982 
3983       SDValue True;
3984       SDValue False;
3985       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3986         True = SelectTrue;
3987         False = SelectFalse;
3988       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3989         True = SelectFalse;
3990         False = SelectTrue;
3991       }
3992 
3993       if (True.getNode() && False.getNode()) {
3994         EVT VT = Op.getValueType();
3995         SDValue ARMcc = Cond.getOperand(2);
3996         SDValue CCR = Cond.getOperand(3);
3997         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3998         assert(True.getValueType() == VT);
3999         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4000       }
4001     }
4002   }
4003 
4004   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4005   // undefined bits before doing a full-word comparison with zero.
4006   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4007                      DAG.getConstant(1, dl, Cond.getValueType()));
4008 
4009   return DAG.getSelectCC(dl, Cond,
4010                          DAG.getConstant(0, dl, Cond.getValueType()),
4011                          SelectTrue, SelectFalse, ISD::SETNE);
4012 }
4013 
4014 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4015                                  bool &swpCmpOps, bool &swpVselOps) {
4016   // Start by selecting the GE condition code for opcodes that return true for
4017   // 'equality'
4018   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4019       CC == ISD::SETULE)
4020     CondCode = ARMCC::GE;
4021 
4022   // and GT for opcodes that return false for 'equality'.
4023   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4024            CC == ISD::SETULT)
4025     CondCode = ARMCC::GT;
4026 
4027   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4028   // to swap the compare operands.
4029   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4030       CC == ISD::SETULT)
4031     swpCmpOps = true;
4032 
4033   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4034   // If we have an unordered opcode, we need to swap the operands to the VSEL
4035   // instruction (effectively negating the condition).
4036   //
4037   // This also has the effect of swapping which one of 'less' or 'greater'
4038   // returns true, so we also swap the compare operands. It also switches
4039   // whether we return true for 'equality', so we compensate by picking the
4040   // opposite condition code to our original choice.
4041   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4042       CC == ISD::SETUGT) {
4043     swpCmpOps = !swpCmpOps;
4044     swpVselOps = !swpVselOps;
4045     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4046   }
4047 
4048   // 'ordered' is 'anything but unordered', so use the VS condition code and
4049   // swap the VSEL operands.
4050   if (CC == ISD::SETO) {
4051     CondCode = ARMCC::VS;
4052     swpVselOps = true;
4053   }
4054 
4055   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4056   // code and swap the VSEL operands.
4057   if (CC == ISD::SETUNE) {
4058     CondCode = ARMCC::EQ;
4059     swpVselOps = true;
4060   }
4061 }
4062 
4063 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4064                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4065                                    SDValue Cmp, SelectionDAG &DAG) const {
4066   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4067     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4068                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4069     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4070                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4071 
4072     SDValue TrueLow = TrueVal.getValue(0);
4073     SDValue TrueHigh = TrueVal.getValue(1);
4074     SDValue FalseLow = FalseVal.getValue(0);
4075     SDValue FalseHigh = FalseVal.getValue(1);
4076 
4077     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4078                               ARMcc, CCR, Cmp);
4079     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4080                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4081 
4082     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4083   } else {
4084     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4085                        Cmp);
4086   }
4087 }
4088 
4089 static bool isGTorGE(ISD::CondCode CC) {
4090   return CC == ISD::SETGT || CC == ISD::SETGE;
4091 }
4092 
4093 static bool isLTorLE(ISD::CondCode CC) {
4094   return CC == ISD::SETLT || CC == ISD::SETLE;
4095 }
4096 
4097 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4098 // All of these conditions (and their <= and >= counterparts) will do:
4099 //          x < k ? k : x
4100 //          x > k ? x : k
4101 //          k < x ? x : k
4102 //          k > x ? k : x
4103 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4104                             const SDValue TrueVal, const SDValue FalseVal,
4105                             const ISD::CondCode CC, const SDValue K) {
4106   return (isGTorGE(CC) &&
4107           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4108          (isLTorLE(CC) &&
4109           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4110 }
4111 
4112 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4113 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4114                             const SDValue TrueVal, const SDValue FalseVal,
4115                             const ISD::CondCode CC, const SDValue K) {
4116   return (isGTorGE(CC) &&
4117           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4118          (isLTorLE(CC) &&
4119           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4120 }
4121 
4122 // Check if two chained conditionals could be converted into SSAT.
4123 //
4124 // SSAT can replace a set of two conditional selectors that bound a number to an
4125 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4126 //
4127 //     x < -k ? -k : (x > k ? k : x)
4128 //     x < -k ? -k : (x < k ? x : k)
4129 //     x > -k ? (x > k ? k : x) : -k
4130 //     x < k ? (x < -k ? -k : x) : k
4131 //     etc.
4132 //
4133 // It returns true if the conversion can be done, false otherwise.
4134 // Additionally, the variable is returned in parameter V and the constant in K.
4135 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4136                                     uint64_t &K) {
4137 
4138   SDValue LHS1 = Op.getOperand(0);
4139   SDValue RHS1 = Op.getOperand(1);
4140   SDValue TrueVal1 = Op.getOperand(2);
4141   SDValue FalseVal1 = Op.getOperand(3);
4142   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4143 
4144   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4145   if (Op2.getOpcode() != ISD::SELECT_CC)
4146     return false;
4147 
4148   SDValue LHS2 = Op2.getOperand(0);
4149   SDValue RHS2 = Op2.getOperand(1);
4150   SDValue TrueVal2 = Op2.getOperand(2);
4151   SDValue FalseVal2 = Op2.getOperand(3);
4152   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4153 
4154   // Find out which are the constants and which are the variables
4155   // in each conditional
4156   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4157                                                         ? &RHS1
4158                                                         : NULL;
4159   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4160                                                         ? &RHS2
4161                                                         : NULL;
4162   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4163   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4164   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4165   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4166 
4167   // We must detect cases where the original operations worked with 16- or
4168   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4169   // must work with sign-extended values but the select operations return
4170   // the original non-extended value.
4171   SDValue V2TmpReg = V2Tmp;
4172   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4173     V2TmpReg = V2Tmp->getOperand(0);
4174 
4175   // Check that the registers and the constants have the correct values
4176   // in both conditionals
4177   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4178       V2TmpReg != V2)
4179     return false;
4180 
4181   // Figure out which conditional is saturating the lower/upper bound.
4182   const SDValue *LowerCheckOp =
4183       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4184           ? &Op
4185           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
4186                                                                        : NULL;
4187   const SDValue *UpperCheckOp =
4188       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4189           ? &Op
4190           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
4191                                                                        : NULL;
4192 
4193   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4194     return false;
4195 
4196   // Check that the constant in the lower-bound check is
4197   // the opposite of the constant in the upper-bound check
4198   // in 1's complement.
4199   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4200   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4201   int64_t PosVal = std::max(Val1, Val2);
4202 
4203   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4204        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4205       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4206 
4207     V = V2;
4208     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4209     return true;
4210   }
4211 
4212   return false;
4213 }
4214 
4215 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4216 
4217   EVT VT = Op.getValueType();
4218   SDLoc dl(Op);
4219 
4220   // Try to convert two saturating conditional selects into a single SSAT
4221   SDValue SatValue;
4222   uint64_t SatConstant;
4223   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4224       isSaturatingConditional(Op, SatValue, SatConstant))
4225     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4226                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4227 
4228   SDValue LHS = Op.getOperand(0);
4229   SDValue RHS = Op.getOperand(1);
4230   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4231   SDValue TrueVal = Op.getOperand(2);
4232   SDValue FalseVal = Op.getOperand(3);
4233 
4234   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4235     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4236                                                     dl);
4237 
4238     // If softenSetCCOperands only returned one value, we should compare it to
4239     // zero.
4240     if (!RHS.getNode()) {
4241       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4242       CC = ISD::SETNE;
4243     }
4244   }
4245 
4246   if (LHS.getValueType() == MVT::i32) {
4247     // Try to generate VSEL on ARMv8.
4248     // The VSEL instruction can't use all the usual ARM condition
4249     // codes: it only has two bits to select the condition code, so it's
4250     // constrained to use only GE, GT, VS and EQ.
4251     //
4252     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4253     // swap the operands of the previous compare instruction (effectively
4254     // inverting the compare condition, swapping 'less' and 'greater') and
4255     // sometimes need to swap the operands to the VSEL (which inverts the
4256     // condition in the sense of firing whenever the previous condition didn't)
4257     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4258                                     TrueVal.getValueType() == MVT::f64)) {
4259       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4260       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4261           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4262         CC = ISD::getSetCCInverse(CC, true);
4263         std::swap(TrueVal, FalseVal);
4264       }
4265     }
4266 
4267     SDValue ARMcc;
4268     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4269     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4270     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4271   }
4272 
4273   ARMCC::CondCodes CondCode, CondCode2;
4274   FPCCToARMCC(CC, CondCode, CondCode2);
4275 
4276   // Try to generate VMAXNM/VMINNM on ARMv8.
4277   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4278                                   TrueVal.getValueType() == MVT::f64)) {
4279     bool swpCmpOps = false;
4280     bool swpVselOps = false;
4281     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4282 
4283     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4284         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4285       if (swpCmpOps)
4286         std::swap(LHS, RHS);
4287       if (swpVselOps)
4288         std::swap(TrueVal, FalseVal);
4289     }
4290   }
4291 
4292   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4293   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4294   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4295   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4296   if (CondCode2 != ARMCC::AL) {
4297     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4298     // FIXME: Needs another CMP because flag can have but one use.
4299     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
4300     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4301   }
4302   return Result;
4303 }
4304 
4305 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4306 /// to morph to an integer compare sequence.
4307 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4308                            const ARMSubtarget *Subtarget) {
4309   SDNode *N = Op.getNode();
4310   if (!N->hasOneUse())
4311     // Otherwise it requires moving the value from fp to integer registers.
4312     return false;
4313   if (!N->getNumValues())
4314     return false;
4315   EVT VT = Op.getValueType();
4316   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4317     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4318     // vmrs are very slow, e.g. cortex-a8.
4319     return false;
4320 
4321   if (isFloatingPointZero(Op)) {
4322     SeenZero = true;
4323     return true;
4324   }
4325   return ISD::isNormalLoad(N);
4326 }
4327 
4328 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4329   if (isFloatingPointZero(Op))
4330     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4331 
4332   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4333     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4334                        Ld->getPointerInfo(), Ld->getAlignment(),
4335                        Ld->getMemOperand()->getFlags());
4336 
4337   llvm_unreachable("Unknown VFP cmp argument!");
4338 }
4339 
4340 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4341                            SDValue &RetVal1, SDValue &RetVal2) {
4342   SDLoc dl(Op);
4343 
4344   if (isFloatingPointZero(Op)) {
4345     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4346     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4347     return;
4348   }
4349 
4350   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4351     SDValue Ptr = Ld->getBasePtr();
4352     RetVal1 =
4353         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4354                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4355 
4356     EVT PtrType = Ptr.getValueType();
4357     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4358     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4359                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4360     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4361                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4362                           Ld->getMemOperand()->getFlags());
4363     return;
4364   }
4365 
4366   llvm_unreachable("Unknown VFP cmp argument!");
4367 }
4368 
4369 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4370 /// f32 and even f64 comparisons to integer ones.
4371 SDValue
4372 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4373   SDValue Chain = Op.getOperand(0);
4374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4375   SDValue LHS = Op.getOperand(2);
4376   SDValue RHS = Op.getOperand(3);
4377   SDValue Dest = Op.getOperand(4);
4378   SDLoc dl(Op);
4379 
4380   bool LHSSeenZero = false;
4381   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4382   bool RHSSeenZero = false;
4383   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4384   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4385     // If unsafe fp math optimization is enabled and there are no other uses of
4386     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4387     // to an integer comparison.
4388     if (CC == ISD::SETOEQ)
4389       CC = ISD::SETEQ;
4390     else if (CC == ISD::SETUNE)
4391       CC = ISD::SETNE;
4392 
4393     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4394     SDValue ARMcc;
4395     if (LHS.getValueType() == MVT::f32) {
4396       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4397                         bitcastf32Toi32(LHS, DAG), Mask);
4398       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4399                         bitcastf32Toi32(RHS, DAG), Mask);
4400       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4401       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4402       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4403                          Chain, Dest, ARMcc, CCR, Cmp);
4404     }
4405 
4406     SDValue LHS1, LHS2;
4407     SDValue RHS1, RHS2;
4408     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4409     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4410     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4411     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4412     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4413     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4414     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4415     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4416     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4417   }
4418 
4419   return SDValue();
4420 }
4421 
4422 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4423   SDValue Chain = Op.getOperand(0);
4424   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4425   SDValue LHS = Op.getOperand(2);
4426   SDValue RHS = Op.getOperand(3);
4427   SDValue Dest = Op.getOperand(4);
4428   SDLoc dl(Op);
4429 
4430   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4431     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4432                                                     dl);
4433 
4434     // If softenSetCCOperands only returned one value, we should compare it to
4435     // zero.
4436     if (!RHS.getNode()) {
4437       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4438       CC = ISD::SETNE;
4439     }
4440   }
4441 
4442   if (LHS.getValueType() == MVT::i32) {
4443     SDValue ARMcc;
4444     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4445     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4446     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4447                        Chain, Dest, ARMcc, CCR, Cmp);
4448   }
4449 
4450   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4451 
4452   if (getTargetMachine().Options.UnsafeFPMath &&
4453       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4454        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4455     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4456       return Result;
4457   }
4458 
4459   ARMCC::CondCodes CondCode, CondCode2;
4460   FPCCToARMCC(CC, CondCode, CondCode2);
4461 
4462   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4463   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4464   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4465   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4466   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4467   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4468   if (CondCode2 != ARMCC::AL) {
4469     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4470     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4471     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4472   }
4473   return Res;
4474 }
4475 
4476 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4477   SDValue Chain = Op.getOperand(0);
4478   SDValue Table = Op.getOperand(1);
4479   SDValue Index = Op.getOperand(2);
4480   SDLoc dl(Op);
4481 
4482   EVT PTy = getPointerTy(DAG.getDataLayout());
4483   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4484   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4485   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4486   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4487   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4488   if (Subtarget->isThumb2()) {
4489     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4490     // which does another jump to the destination. This also makes it easier
4491     // to translate it to TBB / TBH later.
4492     // FIXME: This might not work if the function is extremely large.
4493     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4494                        Addr, Op.getOperand(2), JTI);
4495   }
4496   if (isPositionIndependent() || Subtarget->isROPI()) {
4497     Addr =
4498         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4499                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4500     Chain = Addr.getValue(1);
4501     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4502     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4503   } else {
4504     Addr =
4505         DAG.getLoad(PTy, dl, Chain, Addr,
4506                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4507     Chain = Addr.getValue(1);
4508     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4509   }
4510 }
4511 
4512 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4513   EVT VT = Op.getValueType();
4514   SDLoc dl(Op);
4515 
4516   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4517     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4518       return Op;
4519     return DAG.UnrollVectorOp(Op.getNode());
4520   }
4521 
4522   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4523          "Invalid type for custom lowering!");
4524   if (VT != MVT::v4i16)
4525     return DAG.UnrollVectorOp(Op.getNode());
4526 
4527   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4528   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4529 }
4530 
4531 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4532   EVT VT = Op.getValueType();
4533   if (VT.isVector())
4534     return LowerVectorFP_TO_INT(Op, DAG);
4535   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4536     RTLIB::Libcall LC;
4537     if (Op.getOpcode() == ISD::FP_TO_SINT)
4538       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4539                               Op.getValueType());
4540     else
4541       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4542                               Op.getValueType());
4543     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4544                        /*isSigned*/ false, SDLoc(Op)).first;
4545   }
4546 
4547   return Op;
4548 }
4549 
4550 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4551   EVT VT = Op.getValueType();
4552   SDLoc dl(Op);
4553 
4554   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4555     if (VT.getVectorElementType() == MVT::f32)
4556       return Op;
4557     return DAG.UnrollVectorOp(Op.getNode());
4558   }
4559 
4560   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4561          "Invalid type for custom lowering!");
4562   if (VT != MVT::v4f32)
4563     return DAG.UnrollVectorOp(Op.getNode());
4564 
4565   unsigned CastOpc;
4566   unsigned Opc;
4567   switch (Op.getOpcode()) {
4568   default: llvm_unreachable("Invalid opcode!");
4569   case ISD::SINT_TO_FP:
4570     CastOpc = ISD::SIGN_EXTEND;
4571     Opc = ISD::SINT_TO_FP;
4572     break;
4573   case ISD::UINT_TO_FP:
4574     CastOpc = ISD::ZERO_EXTEND;
4575     Opc = ISD::UINT_TO_FP;
4576     break;
4577   }
4578 
4579   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4580   return DAG.getNode(Opc, dl, VT, Op);
4581 }
4582 
4583 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4584   EVT VT = Op.getValueType();
4585   if (VT.isVector())
4586     return LowerVectorINT_TO_FP(Op, DAG);
4587   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4588     RTLIB::Libcall LC;
4589     if (Op.getOpcode() == ISD::SINT_TO_FP)
4590       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4591                               Op.getValueType());
4592     else
4593       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4594                               Op.getValueType());
4595     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4596                        /*isSigned*/ false, SDLoc(Op)).first;
4597   }
4598 
4599   return Op;
4600 }
4601 
4602 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4603   // Implement fcopysign with a fabs and a conditional fneg.
4604   SDValue Tmp0 = Op.getOperand(0);
4605   SDValue Tmp1 = Op.getOperand(1);
4606   SDLoc dl(Op);
4607   EVT VT = Op.getValueType();
4608   EVT SrcVT = Tmp1.getValueType();
4609   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4610     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4611   bool UseNEON = !InGPR && Subtarget->hasNEON();
4612 
4613   if (UseNEON) {
4614     // Use VBSL to copy the sign bit.
4615     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4616     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4617                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4618     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4619     if (VT == MVT::f64)
4620       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4621                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4622                          DAG.getConstant(32, dl, MVT::i32));
4623     else /*if (VT == MVT::f32)*/
4624       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4625     if (SrcVT == MVT::f32) {
4626       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4627       if (VT == MVT::f64)
4628         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4629                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4630                            DAG.getConstant(32, dl, MVT::i32));
4631     } else if (VT == MVT::f32)
4632       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4633                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4634                          DAG.getConstant(32, dl, MVT::i32));
4635     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4636     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4637 
4638     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4639                                             dl, MVT::i32);
4640     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4641     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4642                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4643 
4644     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4645                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4646                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4647     if (VT == MVT::f32) {
4648       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4649       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4650                         DAG.getConstant(0, dl, MVT::i32));
4651     } else {
4652       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4653     }
4654 
4655     return Res;
4656   }
4657 
4658   // Bitcast operand 1 to i32.
4659   if (SrcVT == MVT::f64)
4660     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4661                        Tmp1).getValue(1);
4662   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4663 
4664   // Or in the signbit with integer operations.
4665   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4666   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4667   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4668   if (VT == MVT::f32) {
4669     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4670                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4671     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4672                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4673   }
4674 
4675   // f64: Or the high part with signbit and then combine two parts.
4676   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4677                      Tmp0);
4678   SDValue Lo = Tmp0.getValue(0);
4679   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4680   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4681   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4682 }
4683 
4684 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4685   MachineFunction &MF = DAG.getMachineFunction();
4686   MachineFrameInfo &MFI = MF.getFrameInfo();
4687   MFI.setReturnAddressIsTaken(true);
4688 
4689   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4690     return SDValue();
4691 
4692   EVT VT = Op.getValueType();
4693   SDLoc dl(Op);
4694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4695   if (Depth) {
4696     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4697     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4698     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4699                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4700                        MachinePointerInfo());
4701   }
4702 
4703   // Return LR, which contains the return address. Mark it an implicit live-in.
4704   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4705   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4706 }
4707 
4708 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4709   const ARMBaseRegisterInfo &ARI =
4710     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4711   MachineFunction &MF = DAG.getMachineFunction();
4712   MachineFrameInfo &MFI = MF.getFrameInfo();
4713   MFI.setFrameAddressIsTaken(true);
4714 
4715   EVT VT = Op.getValueType();
4716   SDLoc dl(Op);  // FIXME probably not meaningful
4717   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4718   unsigned FrameReg = ARI.getFrameRegister(MF);
4719   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4720   while (Depth--)
4721     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4722                             MachinePointerInfo());
4723   return FrameAddr;
4724 }
4725 
4726 // FIXME? Maybe this could be a TableGen attribute on some registers and
4727 // this table could be generated automatically from RegInfo.
4728 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4729                                               SelectionDAG &DAG) const {
4730   unsigned Reg = StringSwitch<unsigned>(RegName)
4731                        .Case("sp", ARM::SP)
4732                        .Default(0);
4733   if (Reg)
4734     return Reg;
4735   report_fatal_error(Twine("Invalid register name \""
4736                               + StringRef(RegName)  + "\"."));
4737 }
4738 
4739 // Result is 64 bit value so split into two 32 bit values and return as a
4740 // pair of values.
4741 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4742                                 SelectionDAG &DAG) {
4743   SDLoc DL(N);
4744 
4745   // This function is only supposed to be called for i64 type destination.
4746   assert(N->getValueType(0) == MVT::i64
4747           && "ExpandREAD_REGISTER called for non-i64 type result.");
4748 
4749   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4750                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4751                              N->getOperand(0),
4752                              N->getOperand(1));
4753 
4754   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4755                     Read.getValue(1)));
4756   Results.push_back(Read.getOperand(0));
4757 }
4758 
4759 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4760 /// When \p DstVT, the destination type of \p BC, is on the vector
4761 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4762 /// it might be possible to combine them, such that everything stays on the
4763 /// vector register bank.
4764 /// \p return The node that would replace \p BT, if the combine
4765 /// is possible.
4766 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4767                                                 SelectionDAG &DAG) {
4768   SDValue Op = BC->getOperand(0);
4769   EVT DstVT = BC->getValueType(0);
4770 
4771   // The only vector instruction that can produce a scalar (remember,
4772   // since the bitcast was about to be turned into VMOVDRR, the source
4773   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4774   // Moreover, we can do this combine only if there is one use.
4775   // Finally, if the destination type is not a vector, there is not
4776   // much point on forcing everything on the vector bank.
4777   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778       !Op.hasOneUse())
4779     return SDValue();
4780 
4781   // If the index is not constant, we will introduce an additional
4782   // multiply that will stick.
4783   // Give up in that case.
4784   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4785   if (!Index)
4786     return SDValue();
4787   unsigned DstNumElt = DstVT.getVectorNumElements();
4788 
4789   // Compute the new index.
4790   const APInt &APIntIndex = Index->getAPIntValue();
4791   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4792   NewIndex *= APIntIndex;
4793   // Check if the new constant index fits into i32.
4794   if (NewIndex.getBitWidth() > 32)
4795     return SDValue();
4796 
4797   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4798   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4799   SDLoc dl(Op);
4800   SDValue ExtractSrc = Op.getOperand(0);
4801   EVT VecVT = EVT::getVectorVT(
4802       *DAG.getContext(), DstVT.getScalarType(),
4803       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4804   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4805   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4806                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4807 }
4808 
4809 /// ExpandBITCAST - If the target supports VFP, this function is called to
4810 /// expand a bit convert where either the source or destination type is i64 to
4811 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4812 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4813 /// vectors), since the legalizer won't know what to do with that.
4814 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4816   SDLoc dl(N);
4817   SDValue Op = N->getOperand(0);
4818 
4819   // This function is only supposed to be called for i64 types, either as the
4820   // source or destination of the bit convert.
4821   EVT SrcVT = Op.getValueType();
4822   EVT DstVT = N->getValueType(0);
4823   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4824          "ExpandBITCAST called for non-i64 type");
4825 
4826   // Turn i64->f64 into VMOVDRR.
4827   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4828     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4829     // if we can combine the bitcast with its source.
4830     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4831       return Val;
4832 
4833     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4834                              DAG.getConstant(0, dl, MVT::i32));
4835     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4836                              DAG.getConstant(1, dl, MVT::i32));
4837     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4838                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4839   }
4840 
4841   // Turn f64->i64 into VMOVRRD.
4842   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4843     SDValue Cvt;
4844     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4845         SrcVT.getVectorNumElements() > 1)
4846       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4847                         DAG.getVTList(MVT::i32, MVT::i32),
4848                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4849     else
4850       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4851                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4852     // Merge the pieces into a single i64 value.
4853     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4854   }
4855 
4856   return SDValue();
4857 }
4858 
4859 /// getZeroVector - Returns a vector of specified type with all zero elements.
4860 /// Zero vectors are used to represent vector negation and in those cases
4861 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4862 /// not support i64 elements, so sometimes the zero vectors will need to be
4863 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4864 /// zero vector.
4865 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4866   assert(VT.isVector() && "Expected a vector type");
4867   // The canonical modified immediate encoding of a zero vector is....0!
4868   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4869   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4870   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4871   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4872 }
4873 
4874 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4875 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4876 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4877                                                 SelectionDAG &DAG) const {
4878   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4879   EVT VT = Op.getValueType();
4880   unsigned VTBits = VT.getSizeInBits();
4881   SDLoc dl(Op);
4882   SDValue ShOpLo = Op.getOperand(0);
4883   SDValue ShOpHi = Op.getOperand(1);
4884   SDValue ShAmt  = Op.getOperand(2);
4885   SDValue ARMcc;
4886   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4887 
4888   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4889 
4890   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4891                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4892   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4893   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4894                                    DAG.getConstant(VTBits, dl, MVT::i32));
4895   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4896   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4897   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4898 
4899   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4900   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4901                           ISD::SETGE, ARMcc, DAG, dl);
4902   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4903   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4904                            CCR, Cmp);
4905 
4906   SDValue Ops[2] = { Lo, Hi };
4907   return DAG.getMergeValues(Ops, dl);
4908 }
4909 
4910 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4911 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4912 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4913                                                SelectionDAG &DAG) const {
4914   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4915   EVT VT = Op.getValueType();
4916   unsigned VTBits = VT.getSizeInBits();
4917   SDLoc dl(Op);
4918   SDValue ShOpLo = Op.getOperand(0);
4919   SDValue ShOpHi = Op.getOperand(1);
4920   SDValue ShAmt  = Op.getOperand(2);
4921   SDValue ARMcc;
4922 
4923   assert(Op.getOpcode() == ISD::SHL_PARTS);
4924   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4925                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4926   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4927   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4928                                    DAG.getConstant(VTBits, dl, MVT::i32));
4929   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4930   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4931 
4932   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4933   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4934   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4935                           ISD::SETGE, ARMcc, DAG, dl);
4936   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4937   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4938                            CCR, Cmp);
4939 
4940   SDValue Ops[2] = { Lo, Hi };
4941   return DAG.getMergeValues(Ops, dl);
4942 }
4943 
4944 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4945                                             SelectionDAG &DAG) const {
4946   // The rounding mode is in bits 23:22 of the FPSCR.
4947   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4948   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4949   // so that the shift + and get folded into a bitfield extract.
4950   SDLoc dl(Op);
4951   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4952                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4953                                               MVT::i32));
4954   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4955                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4956   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4957                               DAG.getConstant(22, dl, MVT::i32));
4958   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4959                      DAG.getConstant(3, dl, MVT::i32));
4960 }
4961 
4962 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4963                          const ARMSubtarget *ST) {
4964   SDLoc dl(N);
4965   EVT VT = N->getValueType(0);
4966   if (VT.isVector()) {
4967     assert(ST->hasNEON());
4968 
4969     // Compute the least significant set bit: LSB = X & -X
4970     SDValue X = N->getOperand(0);
4971     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4972     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4973 
4974     EVT ElemTy = VT.getVectorElementType();
4975 
4976     if (ElemTy == MVT::i8) {
4977       // Compute with: cttz(x) = ctpop(lsb - 1)
4978       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4979                                 DAG.getTargetConstant(1, dl, ElemTy));
4980       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4981       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4982     }
4983 
4984     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4985         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4986       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4987       unsigned NumBits = ElemTy.getSizeInBits();
4988       SDValue WidthMinus1 =
4989           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4990                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4991       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4992       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4993     }
4994 
4995     // Compute with: cttz(x) = ctpop(lsb - 1)
4996 
4997     // Since we can only compute the number of bits in a byte with vcnt.8, we
4998     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4999     // and i64.
5000 
5001     // Compute LSB - 1.
5002     SDValue Bits;
5003     if (ElemTy == MVT::i64) {
5004       // Load constant 0xffff'ffff'ffff'ffff to register.
5005       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5006                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5007       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5008     } else {
5009       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5010                                 DAG.getTargetConstant(1, dl, ElemTy));
5011       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5012     }
5013 
5014     // Count #bits with vcnt.8.
5015     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5016     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5017     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5018 
5019     // Gather the #bits with vpaddl (pairwise add.)
5020     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5021     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5022         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5023         Cnt8);
5024     if (ElemTy == MVT::i16)
5025       return Cnt16;
5026 
5027     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5028     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5029         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5030         Cnt16);
5031     if (ElemTy == MVT::i32)
5032       return Cnt32;
5033 
5034     assert(ElemTy == MVT::i64);
5035     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5036         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5037         Cnt32);
5038     return Cnt64;
5039   }
5040 
5041   if (!ST->hasV6T2Ops())
5042     return SDValue();
5043 
5044   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5045   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5046 }
5047 
5048 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5049 /// for each 16-bit element from operand, repeated.  The basic idea is to
5050 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5051 ///
5052 /// Trace for v4i16:
5053 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5054 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5055 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5056 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5057 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5058 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5059 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5060 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5061 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5062   EVT VT = N->getValueType(0);
5063   SDLoc DL(N);
5064 
5065   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5066   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5067   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5068   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5069   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5070   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5071 }
5072 
5073 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5074 /// bit-count for each 16-bit element from the operand.  We need slightly
5075 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5076 /// 64/128-bit registers.
5077 ///
5078 /// Trace for v4i16:
5079 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5080 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5081 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5082 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5083 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5084   EVT VT = N->getValueType(0);
5085   SDLoc DL(N);
5086 
5087   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5088   if (VT.is64BitVector()) {
5089     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5090     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5091                        DAG.getIntPtrConstant(0, DL));
5092   } else {
5093     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5094                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5095     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5096   }
5097 }
5098 
5099 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5100 /// bit-count for each 32-bit element from the operand.  The idea here is
5101 /// to split the vector into 16-bit elements, leverage the 16-bit count
5102 /// routine, and then combine the results.
5103 ///
5104 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5105 /// input    = [v0    v1    ] (vi: 32-bit elements)
5106 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5107 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5108 /// vrev: N0 = [k1 k0 k3 k2 ]
5109 ///            [k0 k1 k2 k3 ]
5110 ///       N1 =+[k1 k0 k3 k2 ]
5111 ///            [k0 k2 k1 k3 ]
5112 ///       N2 =+[k1 k3 k0 k2 ]
5113 ///            [k0    k2    k1    k3    ]
5114 /// Extended =+[k1    k3    k0    k2    ]
5115 ///            [k0    k2    ]
5116 /// Extracted=+[k1    k3    ]
5117 ///
5118 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5119   EVT VT = N->getValueType(0);
5120   SDLoc DL(N);
5121 
5122   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5123 
5124   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5125   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5126   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5127   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5128   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5129 
5130   if (VT.is64BitVector()) {
5131     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5132     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5133                        DAG.getIntPtrConstant(0, DL));
5134   } else {
5135     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5136                                     DAG.getIntPtrConstant(0, DL));
5137     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5138   }
5139 }
5140 
5141 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5142                           const ARMSubtarget *ST) {
5143   EVT VT = N->getValueType(0);
5144 
5145   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5146   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5147           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5148          "Unexpected type for custom ctpop lowering");
5149 
5150   if (VT.getVectorElementType() == MVT::i32)
5151     return lowerCTPOP32BitElements(N, DAG);
5152   else
5153     return lowerCTPOP16BitElements(N, DAG);
5154 }
5155 
5156 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5157                           const ARMSubtarget *ST) {
5158   EVT VT = N->getValueType(0);
5159   SDLoc dl(N);
5160 
5161   if (!VT.isVector())
5162     return SDValue();
5163 
5164   // Lower vector shifts on NEON to use VSHL.
5165   assert(ST->hasNEON() && "unexpected vector shift");
5166 
5167   // Left shifts translate directly to the vshiftu intrinsic.
5168   if (N->getOpcode() == ISD::SHL)
5169     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5170                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5171                                        MVT::i32),
5172                        N->getOperand(0), N->getOperand(1));
5173 
5174   assert((N->getOpcode() == ISD::SRA ||
5175           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5176 
5177   // NEON uses the same intrinsics for both left and right shifts.  For
5178   // right shifts, the shift amounts are negative, so negate the vector of
5179   // shift amounts.
5180   EVT ShiftVT = N->getOperand(1).getValueType();
5181   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5182                                      getZeroVector(ShiftVT, DAG, dl),
5183                                      N->getOperand(1));
5184   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5185                              Intrinsic::arm_neon_vshifts :
5186                              Intrinsic::arm_neon_vshiftu);
5187   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5188                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5189                      N->getOperand(0), NegatedCount);
5190 }
5191 
5192 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5193                                 const ARMSubtarget *ST) {
5194   EVT VT = N->getValueType(0);
5195   SDLoc dl(N);
5196 
5197   // We can get here for a node like i32 = ISD::SHL i32, i64
5198   if (VT != MVT::i64)
5199     return SDValue();
5200 
5201   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5202          "Unknown shift to lower!");
5203 
5204   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5205   if (!isOneConstant(N->getOperand(1)))
5206     return SDValue();
5207 
5208   // If we are in thumb mode, we don't have RRX.
5209   if (ST->isThumb1Only()) return SDValue();
5210 
5211   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5212   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5213                            DAG.getConstant(0, dl, MVT::i32));
5214   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5215                            DAG.getConstant(1, dl, MVT::i32));
5216 
5217   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5218   // captures the result into a carry flag.
5219   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5220   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5221 
5222   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5223   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5224 
5225   // Merge the pieces into a single i64 value.
5226  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5227 }
5228 
5229 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5230   SDValue TmpOp0, TmpOp1;
5231   bool Invert = false;
5232   bool Swap = false;
5233   unsigned Opc = 0;
5234 
5235   SDValue Op0 = Op.getOperand(0);
5236   SDValue Op1 = Op.getOperand(1);
5237   SDValue CC = Op.getOperand(2);
5238   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5239   EVT VT = Op.getValueType();
5240   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5241   SDLoc dl(Op);
5242 
5243   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5244       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5245     // Special-case integer 64-bit equality comparisons. They aren't legal,
5246     // but they can be lowered with a few vector instructions.
5247     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5248     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5249     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5250     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5251     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5252                               DAG.getCondCode(ISD::SETEQ));
5253     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5254     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5255     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5256     if (SetCCOpcode == ISD::SETNE)
5257       Merged = DAG.getNOT(dl, Merged, CmpVT);
5258     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5259     return Merged;
5260   }
5261 
5262   if (CmpVT.getVectorElementType() == MVT::i64)
5263     // 64-bit comparisons are not legal in general.
5264     return SDValue();
5265 
5266   if (Op1.getValueType().isFloatingPoint()) {
5267     switch (SetCCOpcode) {
5268     default: llvm_unreachable("Illegal FP comparison");
5269     case ISD::SETUNE:
5270     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5271     case ISD::SETOEQ:
5272     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5273     case ISD::SETOLT:
5274     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5275     case ISD::SETOGT:
5276     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5277     case ISD::SETOLE:
5278     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5279     case ISD::SETOGE:
5280     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5281     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5282     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5283     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5284     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5285     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5286     case ISD::SETONE:
5287       // Expand this to (OLT | OGT).
5288       TmpOp0 = Op0;
5289       TmpOp1 = Op1;
5290       Opc = ISD::OR;
5291       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5292       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5293       break;
5294     case ISD::SETUO:
5295       Invert = true;
5296       LLVM_FALLTHROUGH;
5297     case ISD::SETO:
5298       // Expand this to (OLT | OGE).
5299       TmpOp0 = Op0;
5300       TmpOp1 = Op1;
5301       Opc = ISD::OR;
5302       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5303       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5304       break;
5305     }
5306   } else {
5307     // Integer comparisons.
5308     switch (SetCCOpcode) {
5309     default: llvm_unreachable("Illegal integer comparison");
5310     case ISD::SETNE:  Invert = true;
5311     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5312     case ISD::SETLT:  Swap = true;
5313     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5314     case ISD::SETLE:  Swap = true;
5315     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5316     case ISD::SETULT: Swap = true;
5317     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5318     case ISD::SETULE: Swap = true;
5319     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5320     }
5321 
5322     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5323     if (Opc == ARMISD::VCEQ) {
5324 
5325       SDValue AndOp;
5326       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5327         AndOp = Op0;
5328       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5329         AndOp = Op1;
5330 
5331       // Ignore bitconvert.
5332       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5333         AndOp = AndOp.getOperand(0);
5334 
5335       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5336         Opc = ARMISD::VTST;
5337         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5338         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5339         Invert = !Invert;
5340       }
5341     }
5342   }
5343 
5344   if (Swap)
5345     std::swap(Op0, Op1);
5346 
5347   // If one of the operands is a constant vector zero, attempt to fold the
5348   // comparison to a specialized compare-against-zero form.
5349   SDValue SingleOp;
5350   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5351     SingleOp = Op0;
5352   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5353     if (Opc == ARMISD::VCGE)
5354       Opc = ARMISD::VCLEZ;
5355     else if (Opc == ARMISD::VCGT)
5356       Opc = ARMISD::VCLTZ;
5357     SingleOp = Op1;
5358   }
5359 
5360   SDValue Result;
5361   if (SingleOp.getNode()) {
5362     switch (Opc) {
5363     case ARMISD::VCEQ:
5364       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5365     case ARMISD::VCGE:
5366       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5367     case ARMISD::VCLEZ:
5368       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5369     case ARMISD::VCGT:
5370       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5371     case ARMISD::VCLTZ:
5372       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5373     default:
5374       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5375     }
5376   } else {
5377      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5378   }
5379 
5380   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5381 
5382   if (Invert)
5383     Result = DAG.getNOT(dl, Result, VT);
5384 
5385   return Result;
5386 }
5387 
5388 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5389   SDValue LHS = Op.getOperand(0);
5390   SDValue RHS = Op.getOperand(1);
5391   SDValue Carry = Op.getOperand(2);
5392   SDValue Cond = Op.getOperand(3);
5393   SDLoc DL(Op);
5394 
5395   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5396 
5397   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5398   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5399   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5400 
5401   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5402   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5403   SDValue ARMcc = DAG.getConstant(
5404       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5405   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5406   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5407                                    Cmp.getValue(1), SDValue());
5408   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5409                      CCR, Chain.getValue(1));
5410 }
5411 
5412 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5413 /// valid vector constant for a NEON instruction with a "modified immediate"
5414 /// operand (e.g., VMOV).  If so, return the encoded value.
5415 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5416                                  unsigned SplatBitSize, SelectionDAG &DAG,
5417                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5418                                  NEONModImmType type) {
5419   unsigned OpCmode, Imm;
5420 
5421   // SplatBitSize is set to the smallest size that splats the vector, so a
5422   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5423   // immediate instructions others than VMOV do not support the 8-bit encoding
5424   // of a zero vector, and the default encoding of zero is supposed to be the
5425   // 32-bit version.
5426   if (SplatBits == 0)
5427     SplatBitSize = 32;
5428 
5429   switch (SplatBitSize) {
5430   case 8:
5431     if (type != VMOVModImm)
5432       return SDValue();
5433     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5434     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5435     OpCmode = 0xe;
5436     Imm = SplatBits;
5437     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5438     break;
5439 
5440   case 16:
5441     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5442     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5443     if ((SplatBits & ~0xff) == 0) {
5444       // Value = 0x00nn: Op=x, Cmode=100x.
5445       OpCmode = 0x8;
5446       Imm = SplatBits;
5447       break;
5448     }
5449     if ((SplatBits & ~0xff00) == 0) {
5450       // Value = 0xnn00: Op=x, Cmode=101x.
5451       OpCmode = 0xa;
5452       Imm = SplatBits >> 8;
5453       break;
5454     }
5455     return SDValue();
5456 
5457   case 32:
5458     // NEON's 32-bit VMOV supports splat values where:
5459     // * only one byte is nonzero, or
5460     // * the least significant byte is 0xff and the second byte is nonzero, or
5461     // * the least significant 2 bytes are 0xff and the third is nonzero.
5462     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5463     if ((SplatBits & ~0xff) == 0) {
5464       // Value = 0x000000nn: Op=x, Cmode=000x.
5465       OpCmode = 0;
5466       Imm = SplatBits;
5467       break;
5468     }
5469     if ((SplatBits & ~0xff00) == 0) {
5470       // Value = 0x0000nn00: Op=x, Cmode=001x.
5471       OpCmode = 0x2;
5472       Imm = SplatBits >> 8;
5473       break;
5474     }
5475     if ((SplatBits & ~0xff0000) == 0) {
5476       // Value = 0x00nn0000: Op=x, Cmode=010x.
5477       OpCmode = 0x4;
5478       Imm = SplatBits >> 16;
5479       break;
5480     }
5481     if ((SplatBits & ~0xff000000) == 0) {
5482       // Value = 0xnn000000: Op=x, Cmode=011x.
5483       OpCmode = 0x6;
5484       Imm = SplatBits >> 24;
5485       break;
5486     }
5487 
5488     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5489     if (type == OtherModImm) return SDValue();
5490 
5491     if ((SplatBits & ~0xffff) == 0 &&
5492         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5493       // Value = 0x0000nnff: Op=x, Cmode=1100.
5494       OpCmode = 0xc;
5495       Imm = SplatBits >> 8;
5496       break;
5497     }
5498 
5499     if ((SplatBits & ~0xffffff) == 0 &&
5500         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5501       // Value = 0x00nnffff: Op=x, Cmode=1101.
5502       OpCmode = 0xd;
5503       Imm = SplatBits >> 16;
5504       break;
5505     }
5506 
5507     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5508     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5509     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5510     // and fall through here to test for a valid 64-bit splat.  But, then the
5511     // caller would also need to check and handle the change in size.
5512     return SDValue();
5513 
5514   case 64: {
5515     if (type != VMOVModImm)
5516       return SDValue();
5517     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5518     uint64_t BitMask = 0xff;
5519     uint64_t Val = 0;
5520     unsigned ImmMask = 1;
5521     Imm = 0;
5522     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5523       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5524         Val |= BitMask;
5525         Imm |= ImmMask;
5526       } else if ((SplatBits & BitMask) != 0) {
5527         return SDValue();
5528       }
5529       BitMask <<= 8;
5530       ImmMask <<= 1;
5531     }
5532 
5533     if (DAG.getDataLayout().isBigEndian())
5534       // swap higher and lower 32 bit word
5535       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5536 
5537     // Op=1, Cmode=1110.
5538     OpCmode = 0x1e;
5539     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5540     break;
5541   }
5542 
5543   default:
5544     llvm_unreachable("unexpected size for isNEONModifiedImm");
5545   }
5546 
5547   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5548   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5549 }
5550 
5551 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5552                                            const ARMSubtarget *ST) const {
5553   if (!ST->hasVFP3())
5554     return SDValue();
5555 
5556   bool IsDouble = Op.getValueType() == MVT::f64;
5557   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5558 
5559   // Use the default (constant pool) lowering for double constants when we have
5560   // an SP-only FPU
5561   if (IsDouble && Subtarget->isFPOnlySP())
5562     return SDValue();
5563 
5564   // Try splatting with a VMOV.f32...
5565   const APFloat &FPVal = CFP->getValueAPF();
5566   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5567 
5568   if (ImmVal != -1) {
5569     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5570       // We have code in place to select a valid ConstantFP already, no need to
5571       // do any mangling.
5572       return Op;
5573     }
5574 
5575     // It's a float and we are trying to use NEON operations where
5576     // possible. Lower it to a splat followed by an extract.
5577     SDLoc DL(Op);
5578     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5579     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5580                                       NewVal);
5581     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5582                        DAG.getConstant(0, DL, MVT::i32));
5583   }
5584 
5585   // The rest of our options are NEON only, make sure that's allowed before
5586   // proceeding..
5587   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5588     return SDValue();
5589 
5590   EVT VMovVT;
5591   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5592 
5593   // It wouldn't really be worth bothering for doubles except for one very
5594   // important value, which does happen to match: 0.0. So make sure we don't do
5595   // anything stupid.
5596   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5597     return SDValue();
5598 
5599   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5600   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5601                                      VMovVT, false, VMOVModImm);
5602   if (NewVal != SDValue()) {
5603     SDLoc DL(Op);
5604     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5605                                       NewVal);
5606     if (IsDouble)
5607       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5608 
5609     // It's a float: cast and extract a vector element.
5610     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5611                                        VecConstant);
5612     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5613                        DAG.getConstant(0, DL, MVT::i32));
5614   }
5615 
5616   // Finally, try a VMVN.i32
5617   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5618                              false, VMVNModImm);
5619   if (NewVal != SDValue()) {
5620     SDLoc DL(Op);
5621     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5622 
5623     if (IsDouble)
5624       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5625 
5626     // It's a float: cast and extract a vector element.
5627     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5628                                        VecConstant);
5629     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5630                        DAG.getConstant(0, DL, MVT::i32));
5631   }
5632 
5633   return SDValue();
5634 }
5635 
5636 // check if an VEXT instruction can handle the shuffle mask when the
5637 // vector sources of the shuffle are the same.
5638 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5639   unsigned NumElts = VT.getVectorNumElements();
5640 
5641   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5642   if (M[0] < 0)
5643     return false;
5644 
5645   Imm = M[0];
5646 
5647   // If this is a VEXT shuffle, the immediate value is the index of the first
5648   // element.  The other shuffle indices must be the successive elements after
5649   // the first one.
5650   unsigned ExpectedElt = Imm;
5651   for (unsigned i = 1; i < NumElts; ++i) {
5652     // Increment the expected index.  If it wraps around, just follow it
5653     // back to index zero and keep going.
5654     ++ExpectedElt;
5655     if (ExpectedElt == NumElts)
5656       ExpectedElt = 0;
5657 
5658     if (M[i] < 0) continue; // ignore UNDEF indices
5659     if (ExpectedElt != static_cast<unsigned>(M[i]))
5660       return false;
5661   }
5662 
5663   return true;
5664 }
5665 
5666 
5667 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5668                        bool &ReverseVEXT, unsigned &Imm) {
5669   unsigned NumElts = VT.getVectorNumElements();
5670   ReverseVEXT = false;
5671 
5672   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5673   if (M[0] < 0)
5674     return false;
5675 
5676   Imm = M[0];
5677 
5678   // If this is a VEXT shuffle, the immediate value is the index of the first
5679   // element.  The other shuffle indices must be the successive elements after
5680   // the first one.
5681   unsigned ExpectedElt = Imm;
5682   for (unsigned i = 1; i < NumElts; ++i) {
5683     // Increment the expected index.  If it wraps around, it may still be
5684     // a VEXT but the source vectors must be swapped.
5685     ExpectedElt += 1;
5686     if (ExpectedElt == NumElts * 2) {
5687       ExpectedElt = 0;
5688       ReverseVEXT = true;
5689     }
5690 
5691     if (M[i] < 0) continue; // ignore UNDEF indices
5692     if (ExpectedElt != static_cast<unsigned>(M[i]))
5693       return false;
5694   }
5695 
5696   // Adjust the index value if the source operands will be swapped.
5697   if (ReverseVEXT)
5698     Imm -= NumElts;
5699 
5700   return true;
5701 }
5702 
5703 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5704 /// instruction with the specified blocksize.  (The order of the elements
5705 /// within each block of the vector is reversed.)
5706 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5707   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5708          "Only possible block sizes for VREV are: 16, 32, 64");
5709 
5710   unsigned EltSz = VT.getScalarSizeInBits();
5711   if (EltSz == 64)
5712     return false;
5713 
5714   unsigned NumElts = VT.getVectorNumElements();
5715   unsigned BlockElts = M[0] + 1;
5716   // If the first shuffle index is UNDEF, be optimistic.
5717   if (M[0] < 0)
5718     BlockElts = BlockSize / EltSz;
5719 
5720   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5721     return false;
5722 
5723   for (unsigned i = 0; i < NumElts; ++i) {
5724     if (M[i] < 0) continue; // ignore UNDEF indices
5725     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5726       return false;
5727   }
5728 
5729   return true;
5730 }
5731 
5732 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5733   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5734   // range, then 0 is placed into the resulting vector. So pretty much any mask
5735   // of 8 elements can work here.
5736   return VT == MVT::v8i8 && M.size() == 8;
5737 }
5738 
5739 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5740 // checking that pairs of elements in the shuffle mask represent the same index
5741 // in each vector, incrementing the expected index by 2 at each step.
5742 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5743 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5744 //  v2={e,f,g,h}
5745 // WhichResult gives the offset for each element in the mask based on which
5746 // of the two results it belongs to.
5747 //
5748 // The transpose can be represented either as:
5749 // result1 = shufflevector v1, v2, result1_shuffle_mask
5750 // result2 = shufflevector v1, v2, result2_shuffle_mask
5751 // where v1/v2 and the shuffle masks have the same number of elements
5752 // (here WhichResult (see below) indicates which result is being checked)
5753 //
5754 // or as:
5755 // results = shufflevector v1, v2, shuffle_mask
5756 // where both results are returned in one vector and the shuffle mask has twice
5757 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5758 // want to check the low half and high half of the shuffle mask as if it were
5759 // the other case
5760 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5761   unsigned EltSz = VT.getScalarSizeInBits();
5762   if (EltSz == 64)
5763     return false;
5764 
5765   unsigned NumElts = VT.getVectorNumElements();
5766   if (M.size() != NumElts && M.size() != NumElts*2)
5767     return false;
5768 
5769   // If the mask is twice as long as the input vector then we need to check the
5770   // upper and lower parts of the mask with a matching value for WhichResult
5771   // FIXME: A mask with only even values will be rejected in case the first
5772   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5773   // M[0] is used to determine WhichResult
5774   for (unsigned i = 0; i < M.size(); i += NumElts) {
5775     if (M.size() == NumElts * 2)
5776       WhichResult = i / NumElts;
5777     else
5778       WhichResult = M[i] == 0 ? 0 : 1;
5779     for (unsigned j = 0; j < NumElts; j += 2) {
5780       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5781           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5782         return false;
5783     }
5784   }
5785 
5786   if (M.size() == NumElts*2)
5787     WhichResult = 0;
5788 
5789   return true;
5790 }
5791 
5792 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5793 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5794 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5795 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5796   unsigned EltSz = VT.getScalarSizeInBits();
5797   if (EltSz == 64)
5798     return false;
5799 
5800   unsigned NumElts = VT.getVectorNumElements();
5801   if (M.size() != NumElts && M.size() != NumElts*2)
5802     return false;
5803 
5804   for (unsigned i = 0; i < M.size(); i += NumElts) {
5805     if (M.size() == NumElts * 2)
5806       WhichResult = i / NumElts;
5807     else
5808       WhichResult = M[i] == 0 ? 0 : 1;
5809     for (unsigned j = 0; j < NumElts; j += 2) {
5810       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5811           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5812         return false;
5813     }
5814   }
5815 
5816   if (M.size() == NumElts*2)
5817     WhichResult = 0;
5818 
5819   return true;
5820 }
5821 
5822 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5823 // that the mask elements are either all even and in steps of size 2 or all odd
5824 // and in steps of size 2.
5825 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5826 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5827 //  v2={e,f,g,h}
5828 // Requires similar checks to that of isVTRNMask with
5829 // respect the how results are returned.
5830 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5831   unsigned EltSz = VT.getScalarSizeInBits();
5832   if (EltSz == 64)
5833     return false;
5834 
5835   unsigned NumElts = VT.getVectorNumElements();
5836   if (M.size() != NumElts && M.size() != NumElts*2)
5837     return false;
5838 
5839   for (unsigned i = 0; i < M.size(); i += NumElts) {
5840     WhichResult = M[i] == 0 ? 0 : 1;
5841     for (unsigned j = 0; j < NumElts; ++j) {
5842       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5843         return false;
5844     }
5845   }
5846 
5847   if (M.size() == NumElts*2)
5848     WhichResult = 0;
5849 
5850   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5851   if (VT.is64BitVector() && EltSz == 32)
5852     return false;
5853 
5854   return true;
5855 }
5856 
5857 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5858 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5859 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5860 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5861   unsigned EltSz = VT.getScalarSizeInBits();
5862   if (EltSz == 64)
5863     return false;
5864 
5865   unsigned NumElts = VT.getVectorNumElements();
5866   if (M.size() != NumElts && M.size() != NumElts*2)
5867     return false;
5868 
5869   unsigned Half = NumElts / 2;
5870   for (unsigned i = 0; i < M.size(); i += NumElts) {
5871     WhichResult = M[i] == 0 ? 0 : 1;
5872     for (unsigned j = 0; j < NumElts; j += Half) {
5873       unsigned Idx = WhichResult;
5874       for (unsigned k = 0; k < Half; ++k) {
5875         int MIdx = M[i + j + k];
5876         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5877           return false;
5878         Idx += 2;
5879       }
5880     }
5881   }
5882 
5883   if (M.size() == NumElts*2)
5884     WhichResult = 0;
5885 
5886   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5887   if (VT.is64BitVector() && EltSz == 32)
5888     return false;
5889 
5890   return true;
5891 }
5892 
5893 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5894 // that pairs of elements of the shufflemask represent the same index in each
5895 // vector incrementing sequentially through the vectors.
5896 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5897 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5898 //  v2={e,f,g,h}
5899 // Requires similar checks to that of isVTRNMask with respect the how results
5900 // are returned.
5901 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5902   unsigned EltSz = VT.getScalarSizeInBits();
5903   if (EltSz == 64)
5904     return false;
5905 
5906   unsigned NumElts = VT.getVectorNumElements();
5907   if (M.size() != NumElts && M.size() != NumElts*2)
5908     return false;
5909 
5910   for (unsigned i = 0; i < M.size(); i += NumElts) {
5911     WhichResult = M[i] == 0 ? 0 : 1;
5912     unsigned Idx = WhichResult * NumElts / 2;
5913     for (unsigned j = 0; j < NumElts; j += 2) {
5914       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5915           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5916         return false;
5917       Idx += 1;
5918     }
5919   }
5920 
5921   if (M.size() == NumElts*2)
5922     WhichResult = 0;
5923 
5924   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5925   if (VT.is64BitVector() && EltSz == 32)
5926     return false;
5927 
5928   return true;
5929 }
5930 
5931 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5932 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5933 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5934 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5935   unsigned EltSz = VT.getScalarSizeInBits();
5936   if (EltSz == 64)
5937     return false;
5938 
5939   unsigned NumElts = VT.getVectorNumElements();
5940   if (M.size() != NumElts && M.size() != NumElts*2)
5941     return false;
5942 
5943   for (unsigned i = 0; i < M.size(); i += NumElts) {
5944     WhichResult = M[i] == 0 ? 0 : 1;
5945     unsigned Idx = WhichResult * NumElts / 2;
5946     for (unsigned j = 0; j < NumElts; j += 2) {
5947       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5948           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5949         return false;
5950       Idx += 1;
5951     }
5952   }
5953 
5954   if (M.size() == NumElts*2)
5955     WhichResult = 0;
5956 
5957   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5958   if (VT.is64BitVector() && EltSz == 32)
5959     return false;
5960 
5961   return true;
5962 }
5963 
5964 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5965 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5966 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5967                                            unsigned &WhichResult,
5968                                            bool &isV_UNDEF) {
5969   isV_UNDEF = false;
5970   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5971     return ARMISD::VTRN;
5972   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5973     return ARMISD::VUZP;
5974   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5975     return ARMISD::VZIP;
5976 
5977   isV_UNDEF = true;
5978   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5979     return ARMISD::VTRN;
5980   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5981     return ARMISD::VUZP;
5982   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5983     return ARMISD::VZIP;
5984 
5985   return 0;
5986 }
5987 
5988 /// \return true if this is a reverse operation on an vector.
5989 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5990   unsigned NumElts = VT.getVectorNumElements();
5991   // Make sure the mask has the right size.
5992   if (NumElts != M.size())
5993       return false;
5994 
5995   // Look for <15, ..., 3, -1, 1, 0>.
5996   for (unsigned i = 0; i != NumElts; ++i)
5997     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5998       return false;
5999 
6000   return true;
6001 }
6002 
6003 // If N is an integer constant that can be moved into a register in one
6004 // instruction, return an SDValue of such a constant (will become a MOV
6005 // instruction).  Otherwise return null.
6006 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6007                                      const ARMSubtarget *ST, const SDLoc &dl) {
6008   uint64_t Val;
6009   if (!isa<ConstantSDNode>(N))
6010     return SDValue();
6011   Val = cast<ConstantSDNode>(N)->getZExtValue();
6012 
6013   if (ST->isThumb1Only()) {
6014     if (Val <= 255 || ~Val <= 255)
6015       return DAG.getConstant(Val, dl, MVT::i32);
6016   } else {
6017     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6018       return DAG.getConstant(Val, dl, MVT::i32);
6019   }
6020   return SDValue();
6021 }
6022 
6023 // If this is a case we can't handle, return null and let the default
6024 // expansion code take care of it.
6025 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6026                                              const ARMSubtarget *ST) const {
6027   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6028   SDLoc dl(Op);
6029   EVT VT = Op.getValueType();
6030 
6031   APInt SplatBits, SplatUndef;
6032   unsigned SplatBitSize;
6033   bool HasAnyUndefs;
6034   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6035     if (SplatBitSize <= 64) {
6036       // Check if an immediate VMOV works.
6037       EVT VmovVT;
6038       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6039                                       SplatUndef.getZExtValue(), SplatBitSize,
6040                                       DAG, dl, VmovVT, VT.is128BitVector(),
6041                                       VMOVModImm);
6042       if (Val.getNode()) {
6043         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6044         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6045       }
6046 
6047       // Try an immediate VMVN.
6048       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6049       Val = isNEONModifiedImm(NegatedImm,
6050                                       SplatUndef.getZExtValue(), SplatBitSize,
6051                                       DAG, dl, VmovVT, VT.is128BitVector(),
6052                                       VMVNModImm);
6053       if (Val.getNode()) {
6054         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6055         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6056       }
6057 
6058       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6059       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6060         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6061         if (ImmVal != -1) {
6062           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6063           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6064         }
6065       }
6066     }
6067   }
6068 
6069   // Scan through the operands to see if only one value is used.
6070   //
6071   // As an optimisation, even if more than one value is used it may be more
6072   // profitable to splat with one value then change some lanes.
6073   //
6074   // Heuristically we decide to do this if the vector has a "dominant" value,
6075   // defined as splatted to more than half of the lanes.
6076   unsigned NumElts = VT.getVectorNumElements();
6077   bool isOnlyLowElement = true;
6078   bool usesOnlyOneValue = true;
6079   bool hasDominantValue = false;
6080   bool isConstant = true;
6081 
6082   // Map of the number of times a particular SDValue appears in the
6083   // element list.
6084   DenseMap<SDValue, unsigned> ValueCounts;
6085   SDValue Value;
6086   for (unsigned i = 0; i < NumElts; ++i) {
6087     SDValue V = Op.getOperand(i);
6088     if (V.isUndef())
6089       continue;
6090     if (i > 0)
6091       isOnlyLowElement = false;
6092     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6093       isConstant = false;
6094 
6095     ValueCounts.insert(std::make_pair(V, 0));
6096     unsigned &Count = ValueCounts[V];
6097 
6098     // Is this value dominant? (takes up more than half of the lanes)
6099     if (++Count > (NumElts / 2)) {
6100       hasDominantValue = true;
6101       Value = V;
6102     }
6103   }
6104   if (ValueCounts.size() != 1)
6105     usesOnlyOneValue = false;
6106   if (!Value.getNode() && ValueCounts.size() > 0)
6107     Value = ValueCounts.begin()->first;
6108 
6109   if (ValueCounts.size() == 0)
6110     return DAG.getUNDEF(VT);
6111 
6112   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6113   // Keep going if we are hitting this case.
6114   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6115     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6116 
6117   unsigned EltSize = VT.getScalarSizeInBits();
6118 
6119   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6120   // i32 and try again.
6121   if (hasDominantValue && EltSize <= 32) {
6122     if (!isConstant) {
6123       SDValue N;
6124 
6125       // If we are VDUPing a value that comes directly from a vector, that will
6126       // cause an unnecessary move to and from a GPR, where instead we could
6127       // just use VDUPLANE. We can only do this if the lane being extracted
6128       // is at a constant index, as the VDUP from lane instructions only have
6129       // constant-index forms.
6130       ConstantSDNode *constIndex;
6131       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6132           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6133         // We need to create a new undef vector to use for the VDUPLANE if the
6134         // size of the vector from which we get the value is different than the
6135         // size of the vector that we need to create. We will insert the element
6136         // such that the register coalescer will remove unnecessary copies.
6137         if (VT != Value->getOperand(0).getValueType()) {
6138           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6139                              VT.getVectorNumElements();
6140           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6141                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6142                         Value, DAG.getConstant(index, dl, MVT::i32)),
6143                            DAG.getConstant(index, dl, MVT::i32));
6144         } else
6145           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6146                         Value->getOperand(0), Value->getOperand(1));
6147       } else
6148         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6149 
6150       if (!usesOnlyOneValue) {
6151         // The dominant value was splatted as 'N', but we now have to insert
6152         // all differing elements.
6153         for (unsigned I = 0; I < NumElts; ++I) {
6154           if (Op.getOperand(I) == Value)
6155             continue;
6156           SmallVector<SDValue, 3> Ops;
6157           Ops.push_back(N);
6158           Ops.push_back(Op.getOperand(I));
6159           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6160           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6161         }
6162       }
6163       return N;
6164     }
6165     if (VT.getVectorElementType().isFloatingPoint()) {
6166       SmallVector<SDValue, 8> Ops;
6167       for (unsigned i = 0; i < NumElts; ++i)
6168         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6169                                   Op.getOperand(i)));
6170       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6171       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6172       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6173       if (Val.getNode())
6174         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6175     }
6176     if (usesOnlyOneValue) {
6177       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6178       if (isConstant && Val.getNode())
6179         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6180     }
6181   }
6182 
6183   // If all elements are constants and the case above didn't get hit, fall back
6184   // to the default expansion, which will generate a load from the constant
6185   // pool.
6186   if (isConstant)
6187     return SDValue();
6188 
6189   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6190   if (NumElts >= 4) {
6191     SDValue shuffle = ReconstructShuffle(Op, DAG);
6192     if (shuffle != SDValue())
6193       return shuffle;
6194   }
6195 
6196   // Vectors with 32- or 64-bit elements can be built by directly assigning
6197   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6198   // will be legalized.
6199   if (EltSize >= 32) {
6200     // Do the expansion with floating-point types, since that is what the VFP
6201     // registers are defined to use, and since i64 is not legal.
6202     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6203     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6204     SmallVector<SDValue, 8> Ops;
6205     for (unsigned i = 0; i < NumElts; ++i)
6206       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6207     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6208     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6209   }
6210 
6211   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6212   // know the default expansion would otherwise fall back on something even
6213   // worse. For a vector with one or two non-undef values, that's
6214   // scalar_to_vector for the elements followed by a shuffle (provided the
6215   // shuffle is valid for the target) and materialization element by element
6216   // on the stack followed by a load for everything else.
6217   if (!isConstant && !usesOnlyOneValue) {
6218     SDValue Vec = DAG.getUNDEF(VT);
6219     for (unsigned i = 0 ; i < NumElts; ++i) {
6220       SDValue V = Op.getOperand(i);
6221       if (V.isUndef())
6222         continue;
6223       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6224       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6225     }
6226     return Vec;
6227   }
6228 
6229   return SDValue();
6230 }
6231 
6232 // Gather data to see if the operation can be modelled as a
6233 // shuffle in combination with VEXTs.
6234 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6235                                               SelectionDAG &DAG) const {
6236   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6237   SDLoc dl(Op);
6238   EVT VT = Op.getValueType();
6239   unsigned NumElts = VT.getVectorNumElements();
6240 
6241   struct ShuffleSourceInfo {
6242     SDValue Vec;
6243     unsigned MinElt;
6244     unsigned MaxElt;
6245 
6246     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6247     // be compatible with the shuffle we intend to construct. As a result
6248     // ShuffleVec will be some sliding window into the original Vec.
6249     SDValue ShuffleVec;
6250 
6251     // Code should guarantee that element i in Vec starts at element "WindowBase
6252     // + i * WindowScale in ShuffleVec".
6253     int WindowBase;
6254     int WindowScale;
6255 
6256     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6257     ShuffleSourceInfo(SDValue Vec)
6258         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
6259           WindowScale(1) {}
6260   };
6261 
6262   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6263   // node.
6264   SmallVector<ShuffleSourceInfo, 2> Sources;
6265   for (unsigned i = 0; i < NumElts; ++i) {
6266     SDValue V = Op.getOperand(i);
6267     if (V.isUndef())
6268       continue;
6269     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6270       // A shuffle can only come from building a vector from various
6271       // elements of other vectors.
6272       return SDValue();
6273     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6274       // Furthermore, shuffles require a constant mask, whereas extractelts
6275       // accept variable indices.
6276       return SDValue();
6277     }
6278 
6279     // Add this element source to the list if it's not already there.
6280     SDValue SourceVec = V.getOperand(0);
6281     auto Source = find(Sources, SourceVec);
6282     if (Source == Sources.end())
6283       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6284 
6285     // Update the minimum and maximum lane number seen.
6286     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6287     Source->MinElt = std::min(Source->MinElt, EltNo);
6288     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6289   }
6290 
6291   // Currently only do something sane when at most two source vectors
6292   // are involved.
6293   if (Sources.size() > 2)
6294     return SDValue();
6295 
6296   // Find out the smallest element size among result and two sources, and use
6297   // it as element size to build the shuffle_vector.
6298   EVT SmallestEltTy = VT.getVectorElementType();
6299   for (auto &Source : Sources) {
6300     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6301     if (SrcEltTy.bitsLT(SmallestEltTy))
6302       SmallestEltTy = SrcEltTy;
6303   }
6304   unsigned ResMultiplier =
6305       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6306   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6307   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6308 
6309   // If the source vector is too wide or too narrow, we may nevertheless be able
6310   // to construct a compatible shuffle either by concatenating it with UNDEF or
6311   // extracting a suitable range of elements.
6312   for (auto &Src : Sources) {
6313     EVT SrcVT = Src.ShuffleVec.getValueType();
6314 
6315     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6316       continue;
6317 
6318     // This stage of the search produces a source with the same element type as
6319     // the original, but with a total width matching the BUILD_VECTOR output.
6320     EVT EltVT = SrcVT.getVectorElementType();
6321     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6322     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6323 
6324     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6325       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6326         return SDValue();
6327       // We can pad out the smaller vector for free, so if it's part of a
6328       // shuffle...
6329       Src.ShuffleVec =
6330           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6331                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6332       continue;
6333     }
6334 
6335     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6336       return SDValue();
6337 
6338     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6339       // Span too large for a VEXT to cope
6340       return SDValue();
6341     }
6342 
6343     if (Src.MinElt >= NumSrcElts) {
6344       // The extraction can just take the second half
6345       Src.ShuffleVec =
6346           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6347                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6348       Src.WindowBase = -NumSrcElts;
6349     } else if (Src.MaxElt < NumSrcElts) {
6350       // The extraction can just take the first half
6351       Src.ShuffleVec =
6352           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6353                       DAG.getConstant(0, dl, MVT::i32));
6354     } else {
6355       // An actual VEXT is needed
6356       SDValue VEXTSrc1 =
6357           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6358                       DAG.getConstant(0, dl, MVT::i32));
6359       SDValue VEXTSrc2 =
6360           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6361                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6362 
6363       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6364                                    VEXTSrc2,
6365                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6366       Src.WindowBase = -Src.MinElt;
6367     }
6368   }
6369 
6370   // Another possible incompatibility occurs from the vector element types. We
6371   // can fix this by bitcasting the source vectors to the same type we intend
6372   // for the shuffle.
6373   for (auto &Src : Sources) {
6374     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6375     if (SrcEltTy == SmallestEltTy)
6376       continue;
6377     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6378     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6379     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6380     Src.WindowBase *= Src.WindowScale;
6381   }
6382 
6383   // Final sanity check before we try to actually produce a shuffle.
6384   DEBUG(
6385     for (auto Src : Sources)
6386       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6387   );
6388 
6389   // The stars all align, our next step is to produce the mask for the shuffle.
6390   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6391   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6392   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6393     SDValue Entry = Op.getOperand(i);
6394     if (Entry.isUndef())
6395       continue;
6396 
6397     auto Src = find(Sources, Entry.getOperand(0));
6398     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6399 
6400     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6401     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6402     // segment.
6403     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6404     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6405                                VT.getScalarSizeInBits());
6406     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6407 
6408     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6409     // starting at the appropriate offset.
6410     int *LaneMask = &Mask[i * ResMultiplier];
6411 
6412     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6413     ExtractBase += NumElts * (Src - Sources.begin());
6414     for (int j = 0; j < LanesDefined; ++j)
6415       LaneMask[j] = ExtractBase + j;
6416   }
6417 
6418   // Final check before we try to produce nonsense...
6419   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6420     return SDValue();
6421 
6422   // We can't handle more than two sources. This should have already
6423   // been checked before this point.
6424   assert(Sources.size() <= 2 && "Too many sources!");
6425 
6426   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6427   for (unsigned i = 0; i < Sources.size(); ++i)
6428     ShuffleOps[i] = Sources[i].ShuffleVec;
6429 
6430   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6431                                          ShuffleOps[1], Mask);
6432   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6433 }
6434 
6435 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6436 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6437 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6438 /// are assumed to be legal.
6439 bool
6440 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6441                                       EVT VT) const {
6442   if (VT.getVectorNumElements() == 4 &&
6443       (VT.is128BitVector() || VT.is64BitVector())) {
6444     unsigned PFIndexes[4];
6445     for (unsigned i = 0; i != 4; ++i) {
6446       if (M[i] < 0)
6447         PFIndexes[i] = 8;
6448       else
6449         PFIndexes[i] = M[i];
6450     }
6451 
6452     // Compute the index in the perfect shuffle table.
6453     unsigned PFTableIndex =
6454       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6455     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6456     unsigned Cost = (PFEntry >> 30);
6457 
6458     if (Cost <= 4)
6459       return true;
6460   }
6461 
6462   bool ReverseVEXT, isV_UNDEF;
6463   unsigned Imm, WhichResult;
6464 
6465   unsigned EltSize = VT.getScalarSizeInBits();
6466   return (EltSize >= 32 ||
6467           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6468           isVREVMask(M, VT, 64) ||
6469           isVREVMask(M, VT, 32) ||
6470           isVREVMask(M, VT, 16) ||
6471           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6472           isVTBLMask(M, VT) ||
6473           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6474           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6475 }
6476 
6477 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6478 /// the specified operations to build the shuffle.
6479 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6480                                       SDValue RHS, SelectionDAG &DAG,
6481                                       const SDLoc &dl) {
6482   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6483   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6484   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6485 
6486   enum {
6487     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6488     OP_VREV,
6489     OP_VDUP0,
6490     OP_VDUP1,
6491     OP_VDUP2,
6492     OP_VDUP3,
6493     OP_VEXT1,
6494     OP_VEXT2,
6495     OP_VEXT3,
6496     OP_VUZPL, // VUZP, left result
6497     OP_VUZPR, // VUZP, right result
6498     OP_VZIPL, // VZIP, left result
6499     OP_VZIPR, // VZIP, right result
6500     OP_VTRNL, // VTRN, left result
6501     OP_VTRNR  // VTRN, right result
6502   };
6503 
6504   if (OpNum == OP_COPY) {
6505     if (LHSID == (1*9+2)*9+3) return LHS;
6506     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6507     return RHS;
6508   }
6509 
6510   SDValue OpLHS, OpRHS;
6511   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6512   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6513   EVT VT = OpLHS.getValueType();
6514 
6515   switch (OpNum) {
6516   default: llvm_unreachable("Unknown shuffle opcode!");
6517   case OP_VREV:
6518     // VREV divides the vector in half and swaps within the half.
6519     if (VT.getVectorElementType() == MVT::i32 ||
6520         VT.getVectorElementType() == MVT::f32)
6521       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6522     // vrev <4 x i16> -> VREV32
6523     if (VT.getVectorElementType() == MVT::i16)
6524       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6525     // vrev <4 x i8> -> VREV16
6526     assert(VT.getVectorElementType() == MVT::i8);
6527     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6528   case OP_VDUP0:
6529   case OP_VDUP1:
6530   case OP_VDUP2:
6531   case OP_VDUP3:
6532     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6533                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6534   case OP_VEXT1:
6535   case OP_VEXT2:
6536   case OP_VEXT3:
6537     return DAG.getNode(ARMISD::VEXT, dl, VT,
6538                        OpLHS, OpRHS,
6539                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6540   case OP_VUZPL:
6541   case OP_VUZPR:
6542     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6543                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6544   case OP_VZIPL:
6545   case OP_VZIPR:
6546     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6547                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6548   case OP_VTRNL:
6549   case OP_VTRNR:
6550     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6551                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6552   }
6553 }
6554 
6555 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6556                                        ArrayRef<int> ShuffleMask,
6557                                        SelectionDAG &DAG) {
6558   // Check to see if we can use the VTBL instruction.
6559   SDValue V1 = Op.getOperand(0);
6560   SDValue V2 = Op.getOperand(1);
6561   SDLoc DL(Op);
6562 
6563   SmallVector<SDValue, 8> VTBLMask;
6564   for (ArrayRef<int>::iterator
6565          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6566     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6567 
6568   if (V2.getNode()->isUndef())
6569     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6570                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6571 
6572   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6573                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6574 }
6575 
6576 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6577                                                       SelectionDAG &DAG) {
6578   SDLoc DL(Op);
6579   SDValue OpLHS = Op.getOperand(0);
6580   EVT VT = OpLHS.getValueType();
6581 
6582   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6583          "Expect an v8i16/v16i8 type");
6584   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6585   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6586   // extract the first 8 bytes into the top double word and the last 8 bytes
6587   // into the bottom double word. The v8i16 case is similar.
6588   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6589   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6590                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6591 }
6592 
6593 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6594   SDValue V1 = Op.getOperand(0);
6595   SDValue V2 = Op.getOperand(1);
6596   SDLoc dl(Op);
6597   EVT VT = Op.getValueType();
6598   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6599 
6600   // Convert shuffles that are directly supported on NEON to target-specific
6601   // DAG nodes, instead of keeping them as shuffles and matching them again
6602   // during code selection.  This is more efficient and avoids the possibility
6603   // of inconsistencies between legalization and selection.
6604   // FIXME: floating-point vectors should be canonicalized to integer vectors
6605   // of the same time so that they get CSEd properly.
6606   ArrayRef<int> ShuffleMask = SVN->getMask();
6607 
6608   unsigned EltSize = VT.getScalarSizeInBits();
6609   if (EltSize <= 32) {
6610     if (SVN->isSplat()) {
6611       int Lane = SVN->getSplatIndex();
6612       // If this is undef splat, generate it via "just" vdup, if possible.
6613       if (Lane == -1) Lane = 0;
6614 
6615       // Test if V1 is a SCALAR_TO_VECTOR.
6616       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6617         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6618       }
6619       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6620       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6621       // reaches it).
6622       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6623           !isa<ConstantSDNode>(V1.getOperand(0))) {
6624         bool IsScalarToVector = true;
6625         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6626           if (!V1.getOperand(i).isUndef()) {
6627             IsScalarToVector = false;
6628             break;
6629           }
6630         if (IsScalarToVector)
6631           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6632       }
6633       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6634                          DAG.getConstant(Lane, dl, MVT::i32));
6635     }
6636 
6637     bool ReverseVEXT;
6638     unsigned Imm;
6639     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6640       if (ReverseVEXT)
6641         std::swap(V1, V2);
6642       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6643                          DAG.getConstant(Imm, dl, MVT::i32));
6644     }
6645 
6646     if (isVREVMask(ShuffleMask, VT, 64))
6647       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6648     if (isVREVMask(ShuffleMask, VT, 32))
6649       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6650     if (isVREVMask(ShuffleMask, VT, 16))
6651       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6652 
6653     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6654       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6655                          DAG.getConstant(Imm, dl, MVT::i32));
6656     }
6657 
6658     // Check for Neon shuffles that modify both input vectors in place.
6659     // If both results are used, i.e., if there are two shuffles with the same
6660     // source operands and with masks corresponding to both results of one of
6661     // these operations, DAG memoization will ensure that a single node is
6662     // used for both shuffles.
6663     unsigned WhichResult;
6664     bool isV_UNDEF;
6665     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6666             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6667       if (isV_UNDEF)
6668         V2 = V1;
6669       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6670           .getValue(WhichResult);
6671     }
6672 
6673     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6674     // shuffles that produce a result larger than their operands with:
6675     //   shuffle(concat(v1, undef), concat(v2, undef))
6676     // ->
6677     //   shuffle(concat(v1, v2), undef)
6678     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6679     //
6680     // This is useful in the general case, but there are special cases where
6681     // native shuffles produce larger results: the two-result ops.
6682     //
6683     // Look through the concat when lowering them:
6684     //   shuffle(concat(v1, v2), undef)
6685     // ->
6686     //   concat(VZIP(v1, v2):0, :1)
6687     //
6688     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6689       SDValue SubV1 = V1->getOperand(0);
6690       SDValue SubV2 = V1->getOperand(1);
6691       EVT SubVT = SubV1.getValueType();
6692 
6693       // We expect these to have been canonicalized to -1.
6694       assert(all_of(ShuffleMask, [&](int i) {
6695         return i < (int)VT.getVectorNumElements();
6696       }) && "Unexpected shuffle index into UNDEF operand!");
6697 
6698       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6699               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6700         if (isV_UNDEF)
6701           SubV2 = SubV1;
6702         assert((WhichResult == 0) &&
6703                "In-place shuffle of concat can only have one result!");
6704         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6705                                   SubV1, SubV2);
6706         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6707                            Res.getValue(1));
6708       }
6709     }
6710   }
6711 
6712   // If the shuffle is not directly supported and it has 4 elements, use
6713   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6714   unsigned NumElts = VT.getVectorNumElements();
6715   if (NumElts == 4) {
6716     unsigned PFIndexes[4];
6717     for (unsigned i = 0; i != 4; ++i) {
6718       if (ShuffleMask[i] < 0)
6719         PFIndexes[i] = 8;
6720       else
6721         PFIndexes[i] = ShuffleMask[i];
6722     }
6723 
6724     // Compute the index in the perfect shuffle table.
6725     unsigned PFTableIndex =
6726       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6727     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6728     unsigned Cost = (PFEntry >> 30);
6729 
6730     if (Cost <= 4)
6731       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6732   }
6733 
6734   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6735   if (EltSize >= 32) {
6736     // Do the expansion with floating-point types, since that is what the VFP
6737     // registers are defined to use, and since i64 is not legal.
6738     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6739     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6740     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6741     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6742     SmallVector<SDValue, 8> Ops;
6743     for (unsigned i = 0; i < NumElts; ++i) {
6744       if (ShuffleMask[i] < 0)
6745         Ops.push_back(DAG.getUNDEF(EltVT));
6746       else
6747         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6748                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6749                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6750                                                   dl, MVT::i32)));
6751     }
6752     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6753     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6754   }
6755 
6756   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6757     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6758 
6759   if (VT == MVT::v8i8)
6760     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6761       return NewOp;
6762 
6763   return SDValue();
6764 }
6765 
6766 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6767   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6768   SDValue Lane = Op.getOperand(2);
6769   if (!isa<ConstantSDNode>(Lane))
6770     return SDValue();
6771 
6772   return Op;
6773 }
6774 
6775 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6776   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6777   SDValue Lane = Op.getOperand(1);
6778   if (!isa<ConstantSDNode>(Lane))
6779     return SDValue();
6780 
6781   SDValue Vec = Op.getOperand(0);
6782   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6783     SDLoc dl(Op);
6784     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6785   }
6786 
6787   return Op;
6788 }
6789 
6790 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6791   // The only time a CONCAT_VECTORS operation can have legal types is when
6792   // two 64-bit vectors are concatenated to a 128-bit vector.
6793   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6794          "unexpected CONCAT_VECTORS");
6795   SDLoc dl(Op);
6796   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6797   SDValue Op0 = Op.getOperand(0);
6798   SDValue Op1 = Op.getOperand(1);
6799   if (!Op0.isUndef())
6800     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6801                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6802                       DAG.getIntPtrConstant(0, dl));
6803   if (!Op1.isUndef())
6804     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6805                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6806                       DAG.getIntPtrConstant(1, dl));
6807   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6808 }
6809 
6810 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6811 /// element has been zero/sign-extended, depending on the isSigned parameter,
6812 /// from an integer type half its size.
6813 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6814                                    bool isSigned) {
6815   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6816   EVT VT = N->getValueType(0);
6817   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6818     SDNode *BVN = N->getOperand(0).getNode();
6819     if (BVN->getValueType(0) != MVT::v4i32 ||
6820         BVN->getOpcode() != ISD::BUILD_VECTOR)
6821       return false;
6822     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6823     unsigned HiElt = 1 - LoElt;
6824     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6825     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6826     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6827     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6828     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6829       return false;
6830     if (isSigned) {
6831       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6832           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6833         return true;
6834     } else {
6835       if (Hi0->isNullValue() && Hi1->isNullValue())
6836         return true;
6837     }
6838     return false;
6839   }
6840 
6841   if (N->getOpcode() != ISD::BUILD_VECTOR)
6842     return false;
6843 
6844   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6845     SDNode *Elt = N->getOperand(i).getNode();
6846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6847       unsigned EltSize = VT.getScalarSizeInBits();
6848       unsigned HalfSize = EltSize / 2;
6849       if (isSigned) {
6850         if (!isIntN(HalfSize, C->getSExtValue()))
6851           return false;
6852       } else {
6853         if (!isUIntN(HalfSize, C->getZExtValue()))
6854           return false;
6855       }
6856       continue;
6857     }
6858     return false;
6859   }
6860 
6861   return true;
6862 }
6863 
6864 /// isSignExtended - Check if a node is a vector value that is sign-extended
6865 /// or a constant BUILD_VECTOR with sign-extended elements.
6866 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6867   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6868     return true;
6869   if (isExtendedBUILD_VECTOR(N, DAG, true))
6870     return true;
6871   return false;
6872 }
6873 
6874 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6875 /// or a constant BUILD_VECTOR with zero-extended elements.
6876 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6877   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6878     return true;
6879   if (isExtendedBUILD_VECTOR(N, DAG, false))
6880     return true;
6881   return false;
6882 }
6883 
6884 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6885   if (OrigVT.getSizeInBits() >= 64)
6886     return OrigVT;
6887 
6888   assert(OrigVT.isSimple() && "Expecting a simple value type");
6889 
6890   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6891   switch (OrigSimpleTy) {
6892   default: llvm_unreachable("Unexpected Vector Type");
6893   case MVT::v2i8:
6894   case MVT::v2i16:
6895      return MVT::v2i32;
6896   case MVT::v4i8:
6897     return  MVT::v4i16;
6898   }
6899 }
6900 
6901 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6902 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6903 /// We insert the required extension here to get the vector to fill a D register.
6904 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6905                                             const EVT &OrigTy,
6906                                             const EVT &ExtTy,
6907                                             unsigned ExtOpcode) {
6908   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6909   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6910   // 64-bits we need to insert a new extension so that it will be 64-bits.
6911   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6912   if (OrigTy.getSizeInBits() >= 64)
6913     return N;
6914 
6915   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6916   EVT NewVT = getExtensionTo64Bits(OrigTy);
6917 
6918   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6919 }
6920 
6921 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6922 /// does not do any sign/zero extension. If the original vector is less
6923 /// than 64 bits, an appropriate extension will be added after the load to
6924 /// reach a total size of 64 bits. We have to add the extension separately
6925 /// because ARM does not have a sign/zero extending load for vectors.
6926 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6927   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6928 
6929   // The load already has the right type.
6930   if (ExtendedTy == LD->getMemoryVT())
6931     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6932                        LD->getBasePtr(), LD->getPointerInfo(),
6933                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6934 
6935   // We need to create a zextload/sextload. We cannot just create a load
6936   // followed by a zext/zext node because LowerMUL is also run during normal
6937   // operation legalization where we can't create illegal types.
6938   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6939                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6940                         LD->getMemoryVT(), LD->getAlignment(),
6941                         LD->getMemOperand()->getFlags());
6942 }
6943 
6944 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6945 /// extending load, or BUILD_VECTOR with extended elements, return the
6946 /// unextended value. The unextended vector should be 64 bits so that it can
6947 /// be used as an operand to a VMULL instruction. If the original vector size
6948 /// before extension is less than 64 bits we add a an extension to resize
6949 /// the vector to 64 bits.
6950 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6951   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6952     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6953                                         N->getOperand(0)->getValueType(0),
6954                                         N->getValueType(0),
6955                                         N->getOpcode());
6956 
6957   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6958     return SkipLoadExtensionForVMULL(LD, DAG);
6959 
6960   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6961   // have been legalized as a BITCAST from v4i32.
6962   if (N->getOpcode() == ISD::BITCAST) {
6963     SDNode *BVN = N->getOperand(0).getNode();
6964     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6965            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6966     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6967     return DAG.getBuildVector(
6968         MVT::v2i32, SDLoc(N),
6969         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6970   }
6971   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6972   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6973   EVT VT = N->getValueType(0);
6974   unsigned EltSize = VT.getScalarSizeInBits() / 2;
6975   unsigned NumElts = VT.getVectorNumElements();
6976   MVT TruncVT = MVT::getIntegerVT(EltSize);
6977   SmallVector<SDValue, 8> Ops;
6978   SDLoc dl(N);
6979   for (unsigned i = 0; i != NumElts; ++i) {
6980     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6981     const APInt &CInt = C->getAPIntValue();
6982     // Element types smaller than 32 bits are not legal, so use i32 elements.
6983     // The values are implicitly truncated so sext vs. zext doesn't matter.
6984     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6985   }
6986   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6987 }
6988 
6989 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6990   unsigned Opcode = N->getOpcode();
6991   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6992     SDNode *N0 = N->getOperand(0).getNode();
6993     SDNode *N1 = N->getOperand(1).getNode();
6994     return N0->hasOneUse() && N1->hasOneUse() &&
6995       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6996   }
6997   return false;
6998 }
6999 
7000 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7001   unsigned Opcode = N->getOpcode();
7002   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7003     SDNode *N0 = N->getOperand(0).getNode();
7004     SDNode *N1 = N->getOperand(1).getNode();
7005     return N0->hasOneUse() && N1->hasOneUse() &&
7006       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7007   }
7008   return false;
7009 }
7010 
7011 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7012   // Multiplications are only custom-lowered for 128-bit vectors so that
7013   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7014   EVT VT = Op.getValueType();
7015   assert(VT.is128BitVector() && VT.isInteger() &&
7016          "unexpected type for custom-lowering ISD::MUL");
7017   SDNode *N0 = Op.getOperand(0).getNode();
7018   SDNode *N1 = Op.getOperand(1).getNode();
7019   unsigned NewOpc = 0;
7020   bool isMLA = false;
7021   bool isN0SExt = isSignExtended(N0, DAG);
7022   bool isN1SExt = isSignExtended(N1, DAG);
7023   if (isN0SExt && isN1SExt)
7024     NewOpc = ARMISD::VMULLs;
7025   else {
7026     bool isN0ZExt = isZeroExtended(N0, DAG);
7027     bool isN1ZExt = isZeroExtended(N1, DAG);
7028     if (isN0ZExt && isN1ZExt)
7029       NewOpc = ARMISD::VMULLu;
7030     else if (isN1SExt || isN1ZExt) {
7031       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7032       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7033       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7034         NewOpc = ARMISD::VMULLs;
7035         isMLA = true;
7036       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7037         NewOpc = ARMISD::VMULLu;
7038         isMLA = true;
7039       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7040         std::swap(N0, N1);
7041         NewOpc = ARMISD::VMULLu;
7042         isMLA = true;
7043       }
7044     }
7045 
7046     if (!NewOpc) {
7047       if (VT == MVT::v2i64)
7048         // Fall through to expand this.  It is not legal.
7049         return SDValue();
7050       else
7051         // Other vector multiplications are legal.
7052         return Op;
7053     }
7054   }
7055 
7056   // Legalize to a VMULL instruction.
7057   SDLoc DL(Op);
7058   SDValue Op0;
7059   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7060   if (!isMLA) {
7061     Op0 = SkipExtensionForVMULL(N0, DAG);
7062     assert(Op0.getValueType().is64BitVector() &&
7063            Op1.getValueType().is64BitVector() &&
7064            "unexpected types for extended operands to VMULL");
7065     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7066   }
7067 
7068   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7069   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7070   //   vmull q0, d4, d6
7071   //   vmlal q0, d5, d6
7072   // is faster than
7073   //   vaddl q0, d4, d5
7074   //   vmovl q1, d6
7075   //   vmul  q0, q0, q1
7076   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7077   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7078   EVT Op1VT = Op1.getValueType();
7079   return DAG.getNode(N0->getOpcode(), DL, VT,
7080                      DAG.getNode(NewOpc, DL, VT,
7081                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7082                      DAG.getNode(NewOpc, DL, VT,
7083                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7084 }
7085 
7086 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7087                               SelectionDAG &DAG) {
7088   // TODO: Should this propagate fast-math-flags?
7089 
7090   // Convert to float
7091   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7092   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7093   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7094   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7095   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7096   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7097   // Get reciprocal estimate.
7098   // float4 recip = vrecpeq_f32(yf);
7099   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7100                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7101                    Y);
7102   // Because char has a smaller range than uchar, we can actually get away
7103   // without any newton steps.  This requires that we use a weird bias
7104   // of 0xb000, however (again, this has been exhaustively tested).
7105   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7106   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7107   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7108   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7109   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7110   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7111   // Convert back to short.
7112   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7113   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7114   return X;
7115 }
7116 
7117 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7118                                SelectionDAG &DAG) {
7119   // TODO: Should this propagate fast-math-flags?
7120 
7121   SDValue N2;
7122   // Convert to float.
7123   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7124   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7125   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7126   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7127   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7128   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7129 
7130   // Use reciprocal estimate and one refinement step.
7131   // float4 recip = vrecpeq_f32(yf);
7132   // recip *= vrecpsq_f32(yf, recip);
7133   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7134                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7135                    N1);
7136   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7137                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7138                    N1, N2);
7139   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7140   // Because short has a smaller range than ushort, we can actually get away
7141   // with only a single newton step.  This requires that we use a weird bias
7142   // of 89, however (again, this has been exhaustively tested).
7143   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7144   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7145   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7146   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7147   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7148   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7149   // Convert back to integer and return.
7150   // return vmovn_s32(vcvt_s32_f32(result));
7151   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7152   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7153   return N0;
7154 }
7155 
7156 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7157   EVT VT = Op.getValueType();
7158   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7159          "unexpected type for custom-lowering ISD::SDIV");
7160 
7161   SDLoc dl(Op);
7162   SDValue N0 = Op.getOperand(0);
7163   SDValue N1 = Op.getOperand(1);
7164   SDValue N2, N3;
7165 
7166   if (VT == MVT::v8i8) {
7167     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7168     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7169 
7170     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7171                      DAG.getIntPtrConstant(4, dl));
7172     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7173                      DAG.getIntPtrConstant(4, dl));
7174     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7175                      DAG.getIntPtrConstant(0, dl));
7176     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7177                      DAG.getIntPtrConstant(0, dl));
7178 
7179     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7180     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7181 
7182     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7183     N0 = LowerCONCAT_VECTORS(N0, DAG);
7184 
7185     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7186     return N0;
7187   }
7188   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7189 }
7190 
7191 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7192   // TODO: Should this propagate fast-math-flags?
7193   EVT VT = Op.getValueType();
7194   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7195          "unexpected type for custom-lowering ISD::UDIV");
7196 
7197   SDLoc dl(Op);
7198   SDValue N0 = Op.getOperand(0);
7199   SDValue N1 = Op.getOperand(1);
7200   SDValue N2, N3;
7201 
7202   if (VT == MVT::v8i8) {
7203     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7204     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7205 
7206     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7207                      DAG.getIntPtrConstant(4, dl));
7208     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7209                      DAG.getIntPtrConstant(4, dl));
7210     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7211                      DAG.getIntPtrConstant(0, dl));
7212     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7213                      DAG.getIntPtrConstant(0, dl));
7214 
7215     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7216     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7217 
7218     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7219     N0 = LowerCONCAT_VECTORS(N0, DAG);
7220 
7221     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7222                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7223                                      MVT::i32),
7224                      N0);
7225     return N0;
7226   }
7227 
7228   // v4i16 sdiv ... Convert to float.
7229   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7230   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7231   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7232   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7233   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7234   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7235 
7236   // Use reciprocal estimate and two refinement steps.
7237   // float4 recip = vrecpeq_f32(yf);
7238   // recip *= vrecpsq_f32(yf, recip);
7239   // recip *= vrecpsq_f32(yf, recip);
7240   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7241                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7242                    BN1);
7243   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7244                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7245                    BN1, N2);
7246   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7247   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7248                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7249                    BN1, N2);
7250   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7251   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7252   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7253   // and that it will never cause us to return an answer too large).
7254   // float4 result = as_float4(as_int4(xf*recip) + 2);
7255   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7256   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7257   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7258   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7259   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7260   // Convert back to integer and return.
7261   // return vmovn_u32(vcvt_s32_f32(result));
7262   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7263   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7264   return N0;
7265 }
7266 
7267 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7268   EVT VT = Op.getNode()->getValueType(0);
7269   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7270 
7271   unsigned Opc;
7272   bool ExtraOp = false;
7273   switch (Op.getOpcode()) {
7274   default: llvm_unreachable("Invalid code");
7275   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7276   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7277   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7278   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7279   }
7280 
7281   if (!ExtraOp)
7282     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7283                        Op.getOperand(1));
7284   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7285                      Op.getOperand(1), Op.getOperand(2));
7286 }
7287 
7288 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7289   assert(Subtarget->isTargetDarwin());
7290 
7291   // For iOS, we want to call an alternative entry point: __sincos_stret,
7292   // return values are passed via sret.
7293   SDLoc dl(Op);
7294   SDValue Arg = Op.getOperand(0);
7295   EVT ArgVT = Arg.getValueType();
7296   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7297   auto PtrVT = getPointerTy(DAG.getDataLayout());
7298 
7299   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7301 
7302   // Pair of floats / doubles used to pass the result.
7303   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7304   auto &DL = DAG.getDataLayout();
7305 
7306   ArgListTy Args;
7307   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7308   SDValue SRet;
7309   if (ShouldUseSRet) {
7310     // Create stack object for sret.
7311     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7312     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7313     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7314     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7315 
7316     ArgListEntry Entry;
7317     Entry.Node = SRet;
7318     Entry.Ty = RetTy->getPointerTo();
7319     Entry.isSExt = false;
7320     Entry.isZExt = false;
7321     Entry.isSRet = true;
7322     Args.push_back(Entry);
7323     RetTy = Type::getVoidTy(*DAG.getContext());
7324   }
7325 
7326   ArgListEntry Entry;
7327   Entry.Node = Arg;
7328   Entry.Ty = ArgTy;
7329   Entry.isSExt = false;
7330   Entry.isZExt = false;
7331   Args.push_back(Entry);
7332 
7333   const char *LibcallName =
7334       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7335   RTLIB::Libcall LC =
7336       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7337   CallingConv::ID CC = getLibcallCallingConv(LC);
7338   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7339 
7340   TargetLowering::CallLoweringInfo CLI(DAG);
7341   CLI.setDebugLoc(dl)
7342       .setChain(DAG.getEntryNode())
7343       .setCallee(CC, RetTy, Callee, std::move(Args))
7344       .setDiscardResult(ShouldUseSRet);
7345   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7346 
7347   if (!ShouldUseSRet)
7348     return CallResult.first;
7349 
7350   SDValue LoadSin =
7351       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7352 
7353   // Address of cos field.
7354   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7355                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7356   SDValue LoadCos =
7357       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7358 
7359   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7360   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7361                      LoadSin.getValue(0), LoadCos.getValue(0));
7362 }
7363 
7364 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7365                                                   bool Signed,
7366                                                   SDValue &Chain) const {
7367   EVT VT = Op.getValueType();
7368   assert((VT == MVT::i32 || VT == MVT::i64) &&
7369          "unexpected type for custom lowering DIV");
7370   SDLoc dl(Op);
7371 
7372   const auto &DL = DAG.getDataLayout();
7373   const auto &TLI = DAG.getTargetLoweringInfo();
7374 
7375   const char *Name = nullptr;
7376   if (Signed)
7377     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7378   else
7379     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7380 
7381   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7382 
7383   ARMTargetLowering::ArgListTy Args;
7384 
7385   for (auto AI : {1, 0}) {
7386     ArgListEntry Arg;
7387     Arg.Node = Op.getOperand(AI);
7388     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7389     Args.push_back(Arg);
7390   }
7391 
7392   CallLoweringInfo CLI(DAG);
7393   CLI.setDebugLoc(dl)
7394     .setChain(Chain)
7395     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7396                ES, std::move(Args));
7397 
7398   return LowerCallTo(CLI).first;
7399 }
7400 
7401 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7402                                             bool Signed) const {
7403   assert(Op.getValueType() == MVT::i32 &&
7404          "unexpected type for custom lowering DIV");
7405   SDLoc dl(Op);
7406 
7407   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7408                                DAG.getEntryNode(), Op.getOperand(1));
7409 
7410   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7411 }
7412 
7413 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7414   SDLoc DL(N);
7415   SDValue Op = N->getOperand(1);
7416   if (N->getValueType(0) == MVT::i32)
7417     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7418   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7419                            DAG.getConstant(0, DL, MVT::i32));
7420   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7421                            DAG.getConstant(1, DL, MVT::i32));
7422   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7423                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7424 }
7425 
7426 void ARMTargetLowering::ExpandDIV_Windows(
7427     SDValue Op, SelectionDAG &DAG, bool Signed,
7428     SmallVectorImpl<SDValue> &Results) const {
7429   const auto &DL = DAG.getDataLayout();
7430   const auto &TLI = DAG.getTargetLoweringInfo();
7431 
7432   assert(Op.getValueType() == MVT::i64 &&
7433          "unexpected type for custom lowering DIV");
7434   SDLoc dl(Op);
7435 
7436   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7437 
7438   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7439 
7440   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7441   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7442                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7443   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7444 
7445   Results.push_back(Lower);
7446   Results.push_back(Upper);
7447 }
7448 
7449 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7450   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7451     // Acquire/Release load/store is not legal for targets without a dmb or
7452     // equivalent available.
7453     return SDValue();
7454 
7455   // Monotonic load/store is legal for all targets.
7456   return Op;
7457 }
7458 
7459 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7460                                     SmallVectorImpl<SDValue> &Results,
7461                                     SelectionDAG &DAG,
7462                                     const ARMSubtarget *Subtarget) {
7463   SDLoc DL(N);
7464   // Under Power Management extensions, the cycle-count is:
7465   //    mrc p15, #0, <Rt>, c9, c13, #0
7466   SDValue Ops[] = { N->getOperand(0), // Chain
7467                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7468                     DAG.getConstant(15, DL, MVT::i32),
7469                     DAG.getConstant(0, DL, MVT::i32),
7470                     DAG.getConstant(9, DL, MVT::i32),
7471                     DAG.getConstant(13, DL, MVT::i32),
7472                     DAG.getConstant(0, DL, MVT::i32)
7473   };
7474 
7475   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7476                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7477   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7478                                 DAG.getConstant(0, DL, MVT::i32)));
7479   Results.push_back(Cycles32.getValue(1));
7480 }
7481 
7482 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7483   SDLoc dl(V.getNode());
7484   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7485   SDValue VHi = DAG.getAnyExtOrTrunc(
7486       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7487       dl, MVT::i32);
7488   SDValue RegClass =
7489       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7490   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7491   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7492   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7493   return SDValue(
7494       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7495 }
7496 
7497 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7498                                        SmallVectorImpl<SDValue> & Results,
7499                                        SelectionDAG &DAG) {
7500   assert(N->getValueType(0) == MVT::i64 &&
7501          "AtomicCmpSwap on types less than 64 should be legal");
7502   SDValue Ops[] = {N->getOperand(1),
7503                    createGPRPairNode(DAG, N->getOperand(2)),
7504                    createGPRPairNode(DAG, N->getOperand(3)),
7505                    N->getOperand(0)};
7506   SDNode *CmpSwap = DAG.getMachineNode(
7507       ARM::CMP_SWAP_64, SDLoc(N),
7508       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7509 
7510   MachineFunction &MF = DAG.getMachineFunction();
7511   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7512   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7513   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7514 
7515   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7516                                                SDValue(CmpSwap, 0)));
7517   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7518                                                SDValue(CmpSwap, 0)));
7519   Results.push_back(SDValue(CmpSwap, 2));
7520 }
7521 
7522 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7523   switch (Op.getOpcode()) {
7524   default: llvm_unreachable("Don't know how to custom lower this!");
7525   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7526   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
7527   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7528   case ISD::GlobalAddress:
7529     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7530     default: llvm_unreachable("unknown object format");
7531     case Triple::COFF:
7532       return LowerGlobalAddressWindows(Op, DAG);
7533     case Triple::ELF:
7534       return LowerGlobalAddressELF(Op, DAG);
7535     case Triple::MachO:
7536       return LowerGlobalAddressDarwin(Op, DAG);
7537     }
7538   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7539   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7540   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7541   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7542   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7543   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7544   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7545   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7546   case ISD::SINT_TO_FP:
7547   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7548   case ISD::FP_TO_SINT:
7549   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7550   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7551   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7552   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7553   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7554   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7555   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7556   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7557                                                                Subtarget);
7558   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7559   case ISD::SHL:
7560   case ISD::SRL:
7561   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7562   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7563   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7564   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7565   case ISD::SRL_PARTS:
7566   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7567   case ISD::CTTZ:
7568   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7569   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7570   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7571   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7572   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7573   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7574   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7575   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7576   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7577   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7578   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7579   case ISD::MUL:           return LowerMUL(Op, DAG);
7580   case ISD::SDIV:
7581     if (Subtarget->isTargetWindows())
7582       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7583     return LowerSDIV(Op, DAG);
7584   case ISD::UDIV:
7585     if (Subtarget->isTargetWindows())
7586       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7587     return LowerUDIV(Op, DAG);
7588   case ISD::ADDC:
7589   case ISD::ADDE:
7590   case ISD::SUBC:
7591   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7592   case ISD::SADDO:
7593   case ISD::UADDO:
7594   case ISD::SSUBO:
7595   case ISD::USUBO:
7596     return LowerXALUO(Op, DAG);
7597   case ISD::ATOMIC_LOAD:
7598   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7599   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7600   case ISD::SDIVREM:
7601   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7602   case ISD::DYNAMIC_STACKALLOC:
7603     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7604       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7605     llvm_unreachable("Don't know how to custom lower this!");
7606   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7607   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7608   case ARMISD::WIN__DBZCHK: return SDValue();
7609   }
7610 }
7611 
7612 /// ReplaceNodeResults - Replace the results of node with an illegal result
7613 /// type with new values built out of custom code.
7614 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7615                                            SmallVectorImpl<SDValue> &Results,
7616                                            SelectionDAG &DAG) const {
7617   SDValue Res;
7618   switch (N->getOpcode()) {
7619   default:
7620     llvm_unreachable("Don't know how to custom expand this!");
7621   case ISD::READ_REGISTER:
7622     ExpandREAD_REGISTER(N, Results, DAG);
7623     break;
7624   case ISD::BITCAST:
7625     Res = ExpandBITCAST(N, DAG);
7626     break;
7627   case ISD::SRL:
7628   case ISD::SRA:
7629     Res = Expand64BitShift(N, DAG, Subtarget);
7630     break;
7631   case ISD::SREM:
7632   case ISD::UREM:
7633     Res = LowerREM(N, DAG);
7634     break;
7635   case ISD::SDIVREM:
7636   case ISD::UDIVREM:
7637     Res = LowerDivRem(SDValue(N, 0), DAG);
7638     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7639     Results.push_back(Res.getValue(0));
7640     Results.push_back(Res.getValue(1));
7641     return;
7642   case ISD::READCYCLECOUNTER:
7643     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7644     return;
7645   case ISD::UDIV:
7646   case ISD::SDIV:
7647     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7648     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7649                              Results);
7650   case ISD::ATOMIC_CMP_SWAP:
7651     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7652     return;
7653   }
7654   if (Res.getNode())
7655     Results.push_back(Res);
7656 }
7657 
7658 //===----------------------------------------------------------------------===//
7659 //                           ARM Scheduler Hooks
7660 //===----------------------------------------------------------------------===//
7661 
7662 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7663 /// registers the function context.
7664 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7665                                                MachineBasicBlock *MBB,
7666                                                MachineBasicBlock *DispatchBB,
7667                                                int FI) const {
7668   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7669          "ROPI/RWPI not currently supported with SjLj");
7670   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7671   DebugLoc dl = MI.getDebugLoc();
7672   MachineFunction *MF = MBB->getParent();
7673   MachineRegisterInfo *MRI = &MF->getRegInfo();
7674   MachineConstantPool *MCP = MF->getConstantPool();
7675   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7676   const Function *F = MF->getFunction();
7677 
7678   bool isThumb = Subtarget->isThumb();
7679   bool isThumb2 = Subtarget->isThumb2();
7680 
7681   unsigned PCLabelId = AFI->createPICLabelUId();
7682   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7683   ARMConstantPoolValue *CPV =
7684     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7685   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7686 
7687   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7688                                            : &ARM::GPRRegClass;
7689 
7690   // Grab constant pool and fixed stack memory operands.
7691   MachineMemOperand *CPMMO =
7692       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7693                                MachineMemOperand::MOLoad, 4, 4);
7694 
7695   MachineMemOperand *FIMMOSt =
7696       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7697                                MachineMemOperand::MOStore, 4, 4);
7698 
7699   // Load the address of the dispatch MBB into the jump buffer.
7700   if (isThumb2) {
7701     // Incoming value: jbuf
7702     //   ldr.n  r5, LCPI1_1
7703     //   orr    r5, r5, #1
7704     //   add    r5, pc
7705     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7706     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7707     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7708                    .addConstantPoolIndex(CPI)
7709                    .addMemOperand(CPMMO));
7710     // Set the low bit because of thumb mode.
7711     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7712     AddDefaultCC(
7713       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7714                      .addReg(NewVReg1, RegState::Kill)
7715                      .addImm(0x01)));
7716     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7717     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7718       .addReg(NewVReg2, RegState::Kill)
7719       .addImm(PCLabelId);
7720     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7721                    .addReg(NewVReg3, RegState::Kill)
7722                    .addFrameIndex(FI)
7723                    .addImm(36)  // &jbuf[1] :: pc
7724                    .addMemOperand(FIMMOSt));
7725   } else if (isThumb) {
7726     // Incoming value: jbuf
7727     //   ldr.n  r1, LCPI1_4
7728     //   add    r1, pc
7729     //   mov    r2, #1
7730     //   orrs   r1, r2
7731     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7732     //   str    r1, [r2]
7733     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7734     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7735                    .addConstantPoolIndex(CPI)
7736                    .addMemOperand(CPMMO));
7737     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7738     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7739       .addReg(NewVReg1, RegState::Kill)
7740       .addImm(PCLabelId);
7741     // Set the low bit because of thumb mode.
7742     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7743     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7744                    .addReg(ARM::CPSR, RegState::Define)
7745                    .addImm(1));
7746     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7747     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7748                    .addReg(ARM::CPSR, RegState::Define)
7749                    .addReg(NewVReg2, RegState::Kill)
7750                    .addReg(NewVReg3, RegState::Kill));
7751     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7752     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7753             .addFrameIndex(FI)
7754             .addImm(36); // &jbuf[1] :: pc
7755     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7756                    .addReg(NewVReg4, RegState::Kill)
7757                    .addReg(NewVReg5, RegState::Kill)
7758                    .addImm(0)
7759                    .addMemOperand(FIMMOSt));
7760   } else {
7761     // Incoming value: jbuf
7762     //   ldr  r1, LCPI1_1
7763     //   add  r1, pc, r1
7764     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7765     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7766     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7767                    .addConstantPoolIndex(CPI)
7768                    .addImm(0)
7769                    .addMemOperand(CPMMO));
7770     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7771     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7772                    .addReg(NewVReg1, RegState::Kill)
7773                    .addImm(PCLabelId));
7774     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7775                    .addReg(NewVReg2, RegState::Kill)
7776                    .addFrameIndex(FI)
7777                    .addImm(36)  // &jbuf[1] :: pc
7778                    .addMemOperand(FIMMOSt));
7779   }
7780 }
7781 
7782 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7783                                               MachineBasicBlock *MBB) const {
7784   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7785   DebugLoc dl = MI.getDebugLoc();
7786   MachineFunction *MF = MBB->getParent();
7787   MachineRegisterInfo *MRI = &MF->getRegInfo();
7788   MachineFrameInfo &MFI = MF->getFrameInfo();
7789   int FI = MFI.getFunctionContextIndex();
7790 
7791   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7792                                                         : &ARM::GPRnopcRegClass;
7793 
7794   // Get a mapping of the call site numbers to all of the landing pads they're
7795   // associated with.
7796   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7797   unsigned MaxCSNum = 0;
7798   MachineModuleInfo &MMI = MF->getMMI();
7799   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7800        ++BB) {
7801     if (!BB->isEHPad()) continue;
7802 
7803     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7804     // pad.
7805     for (MachineBasicBlock::iterator
7806            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7807       if (!II->isEHLabel()) continue;
7808 
7809       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7810       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7811 
7812       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7813       for (SmallVectorImpl<unsigned>::iterator
7814              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7815            CSI != CSE; ++CSI) {
7816         CallSiteNumToLPad[*CSI].push_back(&*BB);
7817         MaxCSNum = std::max(MaxCSNum, *CSI);
7818       }
7819       break;
7820     }
7821   }
7822 
7823   // Get an ordered list of the machine basic blocks for the jump table.
7824   std::vector<MachineBasicBlock*> LPadList;
7825   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7826   LPadList.reserve(CallSiteNumToLPad.size());
7827   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7828     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7829     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7830            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7831       LPadList.push_back(*II);
7832       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7833     }
7834   }
7835 
7836   assert(!LPadList.empty() &&
7837          "No landing pad destinations for the dispatch jump table!");
7838 
7839   // Create the jump table and associated information.
7840   MachineJumpTableInfo *JTI =
7841     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7842   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7843 
7844   // Create the MBBs for the dispatch code.
7845 
7846   // Shove the dispatch's address into the return slot in the function context.
7847   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7848   DispatchBB->setIsEHPad();
7849 
7850   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7851   unsigned trap_opcode;
7852   if (Subtarget->isThumb())
7853     trap_opcode = ARM::tTRAP;
7854   else
7855     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7856 
7857   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7858   DispatchBB->addSuccessor(TrapBB);
7859 
7860   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7861   DispatchBB->addSuccessor(DispContBB);
7862 
7863   // Insert and MBBs.
7864   MF->insert(MF->end(), DispatchBB);
7865   MF->insert(MF->end(), DispContBB);
7866   MF->insert(MF->end(), TrapBB);
7867 
7868   // Insert code into the entry block that creates and registers the function
7869   // context.
7870   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7871 
7872   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7873       MachinePointerInfo::getFixedStack(*MF, FI),
7874       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7875 
7876   MachineInstrBuilder MIB;
7877   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7878 
7879   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7880   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7881 
7882   // Add a register mask with no preserved registers.  This results in all
7883   // registers being marked as clobbered. This can't work if the dispatch block
7884   // is in a Thumb1 function and is linked with ARM code which uses the FP
7885   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
7886   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
7887 
7888   bool IsPositionIndependent = isPositionIndependent();
7889   unsigned NumLPads = LPadList.size();
7890   if (Subtarget->isThumb2()) {
7891     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7892     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7893                    .addFrameIndex(FI)
7894                    .addImm(4)
7895                    .addMemOperand(FIMMOLd));
7896 
7897     if (NumLPads < 256) {
7898       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7899                      .addReg(NewVReg1)
7900                      .addImm(LPadList.size()));
7901     } else {
7902       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7903       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7904                      .addImm(NumLPads & 0xFFFF));
7905 
7906       unsigned VReg2 = VReg1;
7907       if ((NumLPads & 0xFFFF0000) != 0) {
7908         VReg2 = MRI->createVirtualRegister(TRC);
7909         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7910                        .addReg(VReg1)
7911                        .addImm(NumLPads >> 16));
7912       }
7913 
7914       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7915                      .addReg(NewVReg1)
7916                      .addReg(VReg2));
7917     }
7918 
7919     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7920       .addMBB(TrapBB)
7921       .addImm(ARMCC::HI)
7922       .addReg(ARM::CPSR);
7923 
7924     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7925     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7926                    .addJumpTableIndex(MJTI));
7927 
7928     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7929     AddDefaultCC(
7930       AddDefaultPred(
7931         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7932         .addReg(NewVReg3, RegState::Kill)
7933         .addReg(NewVReg1)
7934         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7935 
7936     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7937       .addReg(NewVReg4, RegState::Kill)
7938       .addReg(NewVReg1)
7939       .addJumpTableIndex(MJTI);
7940   } else if (Subtarget->isThumb()) {
7941     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7942     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7943                    .addFrameIndex(FI)
7944                    .addImm(1)
7945                    .addMemOperand(FIMMOLd));
7946 
7947     if (NumLPads < 256) {
7948       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7949                      .addReg(NewVReg1)
7950                      .addImm(NumLPads));
7951     } else {
7952       MachineConstantPool *ConstantPool = MF->getConstantPool();
7953       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7954       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7955 
7956       // MachineConstantPool wants an explicit alignment.
7957       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7958       if (Align == 0)
7959         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7960       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7961 
7962       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7964                      .addReg(VReg1, RegState::Define)
7965                      .addConstantPoolIndex(Idx));
7966       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7967                      .addReg(NewVReg1)
7968                      .addReg(VReg1));
7969     }
7970 
7971     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7972       .addMBB(TrapBB)
7973       .addImm(ARMCC::HI)
7974       .addReg(ARM::CPSR);
7975 
7976     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7977     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7978                    .addReg(ARM::CPSR, RegState::Define)
7979                    .addReg(NewVReg1)
7980                    .addImm(2));
7981 
7982     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7983     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7984                    .addJumpTableIndex(MJTI));
7985 
7986     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7987     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7988                    .addReg(ARM::CPSR, RegState::Define)
7989                    .addReg(NewVReg2, RegState::Kill)
7990                    .addReg(NewVReg3));
7991 
7992     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7993         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7994 
7995     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7996     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7997                    .addReg(NewVReg4, RegState::Kill)
7998                    .addImm(0)
7999                    .addMemOperand(JTMMOLd));
8000 
8001     unsigned NewVReg6 = NewVReg5;
8002     if (IsPositionIndependent) {
8003       NewVReg6 = MRI->createVirtualRegister(TRC);
8004       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8005                      .addReg(ARM::CPSR, RegState::Define)
8006                      .addReg(NewVReg5, RegState::Kill)
8007                      .addReg(NewVReg3));
8008     }
8009 
8010     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8011       .addReg(NewVReg6, RegState::Kill)
8012       .addJumpTableIndex(MJTI);
8013   } else {
8014     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8015     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8016                    .addFrameIndex(FI)
8017                    .addImm(4)
8018                    .addMemOperand(FIMMOLd));
8019 
8020     if (NumLPads < 256) {
8021       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8022                      .addReg(NewVReg1)
8023                      .addImm(NumLPads));
8024     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8025       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8026       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8027                      .addImm(NumLPads & 0xFFFF));
8028 
8029       unsigned VReg2 = VReg1;
8030       if ((NumLPads & 0xFFFF0000) != 0) {
8031         VReg2 = MRI->createVirtualRegister(TRC);
8032         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8033                        .addReg(VReg1)
8034                        .addImm(NumLPads >> 16));
8035       }
8036 
8037       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8038                      .addReg(NewVReg1)
8039                      .addReg(VReg2));
8040     } else {
8041       MachineConstantPool *ConstantPool = MF->getConstantPool();
8042       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8043       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8044 
8045       // MachineConstantPool wants an explicit alignment.
8046       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8047       if (Align == 0)
8048         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8049       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8050 
8051       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8052       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8053                      .addReg(VReg1, RegState::Define)
8054                      .addConstantPoolIndex(Idx)
8055                      .addImm(0));
8056       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8057                      .addReg(NewVReg1)
8058                      .addReg(VReg1, RegState::Kill));
8059     }
8060 
8061     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8062       .addMBB(TrapBB)
8063       .addImm(ARMCC::HI)
8064       .addReg(ARM::CPSR);
8065 
8066     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8067     AddDefaultCC(
8068       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8069                      .addReg(NewVReg1)
8070                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
8071     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8072     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8073                    .addJumpTableIndex(MJTI));
8074 
8075     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8076         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8077     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8078     AddDefaultPred(
8079       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8080       .addReg(NewVReg3, RegState::Kill)
8081       .addReg(NewVReg4)
8082       .addImm(0)
8083       .addMemOperand(JTMMOLd));
8084 
8085     if (IsPositionIndependent) {
8086       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8087         .addReg(NewVReg5, RegState::Kill)
8088         .addReg(NewVReg4)
8089         .addJumpTableIndex(MJTI);
8090     } else {
8091       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8092         .addReg(NewVReg5, RegState::Kill)
8093         .addJumpTableIndex(MJTI);
8094     }
8095   }
8096 
8097   // Add the jump table entries as successors to the MBB.
8098   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8099   for (std::vector<MachineBasicBlock*>::iterator
8100          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8101     MachineBasicBlock *CurMBB = *I;
8102     if (SeenMBBs.insert(CurMBB).second)
8103       DispContBB->addSuccessor(CurMBB);
8104   }
8105 
8106   // N.B. the order the invoke BBs are processed in doesn't matter here.
8107   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8108   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8109   for (MachineBasicBlock *BB : InvokeBBs) {
8110 
8111     // Remove the landing pad successor from the invoke block and replace it
8112     // with the new dispatch block.
8113     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8114                                                   BB->succ_end());
8115     while (!Successors.empty()) {
8116       MachineBasicBlock *SMBB = Successors.pop_back_val();
8117       if (SMBB->isEHPad()) {
8118         BB->removeSuccessor(SMBB);
8119         MBBLPads.push_back(SMBB);
8120       }
8121     }
8122 
8123     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8124     BB->normalizeSuccProbs();
8125 
8126     // Find the invoke call and mark all of the callee-saved registers as
8127     // 'implicit defined' so that they're spilled. This prevents code from
8128     // moving instructions to before the EH block, where they will never be
8129     // executed.
8130     for (MachineBasicBlock::reverse_iterator
8131            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8132       if (!II->isCall()) continue;
8133 
8134       DenseMap<unsigned, bool> DefRegs;
8135       for (MachineInstr::mop_iterator
8136              OI = II->operands_begin(), OE = II->operands_end();
8137            OI != OE; ++OI) {
8138         if (!OI->isReg()) continue;
8139         DefRegs[OI->getReg()] = true;
8140       }
8141 
8142       MachineInstrBuilder MIB(*MF, &*II);
8143 
8144       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8145         unsigned Reg = SavedRegs[i];
8146         if (Subtarget->isThumb2() &&
8147             !ARM::tGPRRegClass.contains(Reg) &&
8148             !ARM::hGPRRegClass.contains(Reg))
8149           continue;
8150         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8151           continue;
8152         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8153           continue;
8154         if (!DefRegs[Reg])
8155           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8156       }
8157 
8158       break;
8159     }
8160   }
8161 
8162   // Mark all former landing pads as non-landing pads. The dispatch is the only
8163   // landing pad now.
8164   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8165          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8166     (*I)->setIsEHPad(false);
8167 
8168   // The instruction is gone now.
8169   MI.eraseFromParent();
8170 }
8171 
8172 static
8173 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8174   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8175        E = MBB->succ_end(); I != E; ++I)
8176     if (*I != Succ)
8177       return *I;
8178   llvm_unreachable("Expecting a BB with two successors!");
8179 }
8180 
8181 /// Return the load opcode for a given load size. If load size >= 8,
8182 /// neon opcode will be returned.
8183 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8184   if (LdSize >= 8)
8185     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8186                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8187   if (IsThumb1)
8188     return LdSize == 4 ? ARM::tLDRi
8189                        : LdSize == 2 ? ARM::tLDRHi
8190                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8191   if (IsThumb2)
8192     return LdSize == 4 ? ARM::t2LDR_POST
8193                        : LdSize == 2 ? ARM::t2LDRH_POST
8194                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8195   return LdSize == 4 ? ARM::LDR_POST_IMM
8196                      : LdSize == 2 ? ARM::LDRH_POST
8197                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8198 }
8199 
8200 /// Return the store opcode for a given store size. If store size >= 8,
8201 /// neon opcode will be returned.
8202 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8203   if (StSize >= 8)
8204     return StSize == 16 ? ARM::VST1q32wb_fixed
8205                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8206   if (IsThumb1)
8207     return StSize == 4 ? ARM::tSTRi
8208                        : StSize == 2 ? ARM::tSTRHi
8209                                      : StSize == 1 ? ARM::tSTRBi : 0;
8210   if (IsThumb2)
8211     return StSize == 4 ? ARM::t2STR_POST
8212                        : StSize == 2 ? ARM::t2STRH_POST
8213                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8214   return StSize == 4 ? ARM::STR_POST_IMM
8215                      : StSize == 2 ? ARM::STRH_POST
8216                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8217 }
8218 
8219 /// Emit a post-increment load operation with given size. The instructions
8220 /// will be added to BB at Pos.
8221 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8222                        const TargetInstrInfo *TII, const DebugLoc &dl,
8223                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8224                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8225   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8226   assert(LdOpc != 0 && "Should have a load opcode");
8227   if (LdSize >= 8) {
8228     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8229                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8230                        .addImm(0));
8231   } else if (IsThumb1) {
8232     // load + update AddrIn
8233     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8234                        .addReg(AddrIn).addImm(0));
8235     MachineInstrBuilder MIB =
8236         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
8237     MIB = AddDefaultT1CC(MIB);
8238     MIB.addReg(AddrIn).addImm(LdSize);
8239     AddDefaultPred(MIB);
8240   } else if (IsThumb2) {
8241     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8242                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8243                        .addImm(LdSize));
8244   } else { // arm
8245     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8246                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8247                        .addReg(0).addImm(LdSize));
8248   }
8249 }
8250 
8251 /// Emit a post-increment store operation with given size. The instructions
8252 /// will be added to BB at Pos.
8253 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8254                        const TargetInstrInfo *TII, const DebugLoc &dl,
8255                        unsigned StSize, unsigned Data, unsigned AddrIn,
8256                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8257   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8258   assert(StOpc != 0 && "Should have a store opcode");
8259   if (StSize >= 8) {
8260     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8261                        .addReg(AddrIn).addImm(0).addReg(Data));
8262   } else if (IsThumb1) {
8263     // store + update AddrIn
8264     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
8265                        .addReg(AddrIn).addImm(0));
8266     MachineInstrBuilder MIB =
8267         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
8268     MIB = AddDefaultT1CC(MIB);
8269     MIB.addReg(AddrIn).addImm(StSize);
8270     AddDefaultPred(MIB);
8271   } else if (IsThumb2) {
8272     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8273                        .addReg(Data).addReg(AddrIn).addImm(StSize));
8274   } else { // arm
8275     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8276                        .addReg(Data).addReg(AddrIn).addReg(0)
8277                        .addImm(StSize));
8278   }
8279 }
8280 
8281 MachineBasicBlock *
8282 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8283                                    MachineBasicBlock *BB) const {
8284   // This pseudo instruction has 3 operands: dst, src, size
8285   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8286   // Otherwise, we will generate unrolled scalar copies.
8287   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8288   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8289   MachineFunction::iterator It = ++BB->getIterator();
8290 
8291   unsigned dest = MI.getOperand(0).getReg();
8292   unsigned src = MI.getOperand(1).getReg();
8293   unsigned SizeVal = MI.getOperand(2).getImm();
8294   unsigned Align = MI.getOperand(3).getImm();
8295   DebugLoc dl = MI.getDebugLoc();
8296 
8297   MachineFunction *MF = BB->getParent();
8298   MachineRegisterInfo &MRI = MF->getRegInfo();
8299   unsigned UnitSize = 0;
8300   const TargetRegisterClass *TRC = nullptr;
8301   const TargetRegisterClass *VecTRC = nullptr;
8302 
8303   bool IsThumb1 = Subtarget->isThumb1Only();
8304   bool IsThumb2 = Subtarget->isThumb2();
8305   bool IsThumb = Subtarget->isThumb();
8306 
8307   if (Align & 1) {
8308     UnitSize = 1;
8309   } else if (Align & 2) {
8310     UnitSize = 2;
8311   } else {
8312     // Check whether we can use NEON instructions.
8313     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8314         Subtarget->hasNEON()) {
8315       if ((Align % 16 == 0) && SizeVal >= 16)
8316         UnitSize = 16;
8317       else if ((Align % 8 == 0) && SizeVal >= 8)
8318         UnitSize = 8;
8319     }
8320     // Can't use NEON instructions.
8321     if (UnitSize == 0)
8322       UnitSize = 4;
8323   }
8324 
8325   // Select the correct opcode and register class for unit size load/store
8326   bool IsNeon = UnitSize >= 8;
8327   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8328   if (IsNeon)
8329     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8330                             : UnitSize == 8 ? &ARM::DPRRegClass
8331                                             : nullptr;
8332 
8333   unsigned BytesLeft = SizeVal % UnitSize;
8334   unsigned LoopSize = SizeVal - BytesLeft;
8335 
8336   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8337     // Use LDR and STR to copy.
8338     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8339     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8340     unsigned srcIn = src;
8341     unsigned destIn = dest;
8342     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8343       unsigned srcOut = MRI.createVirtualRegister(TRC);
8344       unsigned destOut = MRI.createVirtualRegister(TRC);
8345       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8346       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8347                  IsThumb1, IsThumb2);
8348       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8349                  IsThumb1, IsThumb2);
8350       srcIn = srcOut;
8351       destIn = destOut;
8352     }
8353 
8354     // Handle the leftover bytes with LDRB and STRB.
8355     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8356     // [destOut] = STRB_POST(scratch, destIn, 1)
8357     for (unsigned i = 0; i < BytesLeft; i++) {
8358       unsigned srcOut = MRI.createVirtualRegister(TRC);
8359       unsigned destOut = MRI.createVirtualRegister(TRC);
8360       unsigned scratch = MRI.createVirtualRegister(TRC);
8361       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8362                  IsThumb1, IsThumb2);
8363       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8364                  IsThumb1, IsThumb2);
8365       srcIn = srcOut;
8366       destIn = destOut;
8367     }
8368     MI.eraseFromParent(); // The instruction is gone now.
8369     return BB;
8370   }
8371 
8372   // Expand the pseudo op to a loop.
8373   // thisMBB:
8374   //   ...
8375   //   movw varEnd, # --> with thumb2
8376   //   movt varEnd, #
8377   //   ldrcp varEnd, idx --> without thumb2
8378   //   fallthrough --> loopMBB
8379   // loopMBB:
8380   //   PHI varPhi, varEnd, varLoop
8381   //   PHI srcPhi, src, srcLoop
8382   //   PHI destPhi, dst, destLoop
8383   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8384   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8385   //   subs varLoop, varPhi, #UnitSize
8386   //   bne loopMBB
8387   //   fallthrough --> exitMBB
8388   // exitMBB:
8389   //   epilogue to handle left-over bytes
8390   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8391   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8392   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8393   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8394   MF->insert(It, loopMBB);
8395   MF->insert(It, exitMBB);
8396 
8397   // Transfer the remainder of BB and its successor edges to exitMBB.
8398   exitMBB->splice(exitMBB->begin(), BB,
8399                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8400   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8401 
8402   // Load an immediate to varEnd.
8403   unsigned varEnd = MRI.createVirtualRegister(TRC);
8404   if (Subtarget->useMovt(*MF)) {
8405     unsigned Vtmp = varEnd;
8406     if ((LoopSize & 0xFFFF0000) != 0)
8407       Vtmp = MRI.createVirtualRegister(TRC);
8408     AddDefaultPred(BuildMI(BB, dl,
8409                            TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16),
8410                            Vtmp).addImm(LoopSize & 0xFFFF));
8411 
8412     if ((LoopSize & 0xFFFF0000) != 0)
8413       AddDefaultPred(BuildMI(BB, dl,
8414                              TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16),
8415                              varEnd)
8416                          .addReg(Vtmp)
8417                          .addImm(LoopSize >> 16));
8418   } else {
8419     MachineConstantPool *ConstantPool = MF->getConstantPool();
8420     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8421     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8422 
8423     // MachineConstantPool wants an explicit alignment.
8424     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8425     if (Align == 0)
8426       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8427     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8428 
8429     if (IsThumb)
8430       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
8431           varEnd, RegState::Define).addConstantPoolIndex(Idx));
8432     else
8433       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
8434           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
8435   }
8436   BB->addSuccessor(loopMBB);
8437 
8438   // Generate the loop body:
8439   //   varPhi = PHI(varLoop, varEnd)
8440   //   srcPhi = PHI(srcLoop, src)
8441   //   destPhi = PHI(destLoop, dst)
8442   MachineBasicBlock *entryBB = BB;
8443   BB = loopMBB;
8444   unsigned varLoop = MRI.createVirtualRegister(TRC);
8445   unsigned varPhi = MRI.createVirtualRegister(TRC);
8446   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8447   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8448   unsigned destLoop = MRI.createVirtualRegister(TRC);
8449   unsigned destPhi = MRI.createVirtualRegister(TRC);
8450 
8451   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8452     .addReg(varLoop).addMBB(loopMBB)
8453     .addReg(varEnd).addMBB(entryBB);
8454   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8455     .addReg(srcLoop).addMBB(loopMBB)
8456     .addReg(src).addMBB(entryBB);
8457   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8458     .addReg(destLoop).addMBB(loopMBB)
8459     .addReg(dest).addMBB(entryBB);
8460 
8461   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8462   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8463   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8464   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8465              IsThumb1, IsThumb2);
8466   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8467              IsThumb1, IsThumb2);
8468 
8469   // Decrement loop variable by UnitSize.
8470   if (IsThumb1) {
8471     MachineInstrBuilder MIB =
8472         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
8473     MIB = AddDefaultT1CC(MIB);
8474     MIB.addReg(varPhi).addImm(UnitSize);
8475     AddDefaultPred(MIB);
8476   } else {
8477     MachineInstrBuilder MIB =
8478         BuildMI(*BB, BB->end(), dl,
8479                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8480     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
8481     MIB->getOperand(5).setReg(ARM::CPSR);
8482     MIB->getOperand(5).setIsDef(true);
8483   }
8484   BuildMI(*BB, BB->end(), dl,
8485           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8486       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8487 
8488   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8489   BB->addSuccessor(loopMBB);
8490   BB->addSuccessor(exitMBB);
8491 
8492   // Add epilogue to handle BytesLeft.
8493   BB = exitMBB;
8494   auto StartOfExit = exitMBB->begin();
8495 
8496   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8497   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8498   unsigned srcIn = srcLoop;
8499   unsigned destIn = destLoop;
8500   for (unsigned i = 0; i < BytesLeft; i++) {
8501     unsigned srcOut = MRI.createVirtualRegister(TRC);
8502     unsigned destOut = MRI.createVirtualRegister(TRC);
8503     unsigned scratch = MRI.createVirtualRegister(TRC);
8504     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8505                IsThumb1, IsThumb2);
8506     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8507                IsThumb1, IsThumb2);
8508     srcIn = srcOut;
8509     destIn = destOut;
8510   }
8511 
8512   MI.eraseFromParent(); // The instruction is gone now.
8513   return BB;
8514 }
8515 
8516 MachineBasicBlock *
8517 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8518                                        MachineBasicBlock *MBB) const {
8519   const TargetMachine &TM = getTargetMachine();
8520   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8521   DebugLoc DL = MI.getDebugLoc();
8522 
8523   assert(Subtarget->isTargetWindows() &&
8524          "__chkstk is only supported on Windows");
8525   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8526 
8527   // __chkstk takes the number of words to allocate on the stack in R4, and
8528   // returns the stack adjustment in number of bytes in R4.  This will not
8529   // clober any other registers (other than the obvious lr).
8530   //
8531   // Although, technically, IP should be considered a register which may be
8532   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8533   // thumb-2 environment, so there is no interworking required.  As a result, we
8534   // do not expect a veneer to be emitted by the linker, clobbering IP.
8535   //
8536   // Each module receives its own copy of __chkstk, so no import thunk is
8537   // required, again, ensuring that IP is not clobbered.
8538   //
8539   // Finally, although some linkers may theoretically provide a trampoline for
8540   // out of range calls (which is quite common due to a 32M range limitation of
8541   // branches for Thumb), we can generate the long-call version via
8542   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8543   // IP.
8544 
8545   switch (TM.getCodeModel()) {
8546   case CodeModel::Small:
8547   case CodeModel::Medium:
8548   case CodeModel::Default:
8549   case CodeModel::Kernel:
8550     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8551       .addImm((unsigned)ARMCC::AL).addReg(0)
8552       .addExternalSymbol("__chkstk")
8553       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8554       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8555       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8556     break;
8557   case CodeModel::Large:
8558   case CodeModel::JITDefault: {
8559     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8560     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8561 
8562     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8563       .addExternalSymbol("__chkstk");
8564     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8565       .addImm((unsigned)ARMCC::AL).addReg(0)
8566       .addReg(Reg, RegState::Kill)
8567       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8568       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8569       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8570     break;
8571   }
8572   }
8573 
8574   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
8575                                       ARM::SP)
8576                          .addReg(ARM::SP, RegState::Kill)
8577                          .addReg(ARM::R4, RegState::Kill)
8578                          .setMIFlags(MachineInstr::FrameSetup)));
8579 
8580   MI.eraseFromParent();
8581   return MBB;
8582 }
8583 
8584 MachineBasicBlock *
8585 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8586                                        MachineBasicBlock *MBB) const {
8587   DebugLoc DL = MI.getDebugLoc();
8588   MachineFunction *MF = MBB->getParent();
8589   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8590 
8591   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8592   MF->insert(++MBB->getIterator(), ContBB);
8593   ContBB->splice(ContBB->begin(), MBB,
8594                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8595   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8596 
8597   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8598   MF->push_back(TrapBB);
8599   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8600   MBB->addSuccessor(TrapBB);
8601 
8602   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8603       .addReg(MI.getOperand(0).getReg())
8604       .addMBB(TrapBB);
8605   AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB));
8606   MBB->addSuccessor(ContBB);
8607 
8608   MI.eraseFromParent();
8609   return ContBB;
8610 }
8611 
8612 MachineBasicBlock *
8613 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8614                                                MachineBasicBlock *BB) const {
8615   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8616   DebugLoc dl = MI.getDebugLoc();
8617   bool isThumb2 = Subtarget->isThumb2();
8618   switch (MI.getOpcode()) {
8619   default: {
8620     MI.dump();
8621     llvm_unreachable("Unexpected instr type to insert");
8622   }
8623 
8624   // Thumb1 post-indexed loads are really just single-register LDMs.
8625   case ARM::tLDR_postidx: {
8626     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8627       .addOperand(MI.getOperand(1)) // Rn_wb
8628       .addOperand(MI.getOperand(2)) // Rn
8629       .addOperand(MI.getOperand(3)) // PredImm
8630       .addOperand(MI.getOperand(4)) // PredReg
8631       .addOperand(MI.getOperand(0)); // Rt
8632     MI.eraseFromParent();
8633     return BB;
8634   }
8635 
8636   // The Thumb2 pre-indexed stores have the same MI operands, they just
8637   // define them differently in the .td files from the isel patterns, so
8638   // they need pseudos.
8639   case ARM::t2STR_preidx:
8640     MI.setDesc(TII->get(ARM::t2STR_PRE));
8641     return BB;
8642   case ARM::t2STRB_preidx:
8643     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8644     return BB;
8645   case ARM::t2STRH_preidx:
8646     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8647     return BB;
8648 
8649   case ARM::STRi_preidx:
8650   case ARM::STRBi_preidx: {
8651     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8652                                                          : ARM::STRB_PRE_IMM;
8653     // Decode the offset.
8654     unsigned Offset = MI.getOperand(4).getImm();
8655     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8656     Offset = ARM_AM::getAM2Offset(Offset);
8657     if (isSub)
8658       Offset = -Offset;
8659 
8660     MachineMemOperand *MMO = *MI.memoperands_begin();
8661     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8662         .addOperand(MI.getOperand(0)) // Rn_wb
8663         .addOperand(MI.getOperand(1)) // Rt
8664         .addOperand(MI.getOperand(2)) // Rn
8665         .addImm(Offset)               // offset (skip GPR==zero_reg)
8666         .addOperand(MI.getOperand(5)) // pred
8667         .addOperand(MI.getOperand(6))
8668         .addMemOperand(MMO);
8669     MI.eraseFromParent();
8670     return BB;
8671   }
8672   case ARM::STRr_preidx:
8673   case ARM::STRBr_preidx:
8674   case ARM::STRH_preidx: {
8675     unsigned NewOpc;
8676     switch (MI.getOpcode()) {
8677     default: llvm_unreachable("unexpected opcode!");
8678     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8679     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8680     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8681     }
8682     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8683     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8684       MIB.addOperand(MI.getOperand(i));
8685     MI.eraseFromParent();
8686     return BB;
8687   }
8688 
8689   case ARM::tMOVCCr_pseudo: {
8690     // To "insert" a SELECT_CC instruction, we actually have to insert the
8691     // diamond control-flow pattern.  The incoming instruction knows the
8692     // destination vreg to set, the condition code register to branch on, the
8693     // true/false values to select between, and a branch opcode to use.
8694     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8695     MachineFunction::iterator It = ++BB->getIterator();
8696 
8697     //  thisMBB:
8698     //  ...
8699     //   TrueVal = ...
8700     //   cmpTY ccX, r1, r2
8701     //   bCC copy1MBB
8702     //   fallthrough --> copy0MBB
8703     MachineBasicBlock *thisMBB  = BB;
8704     MachineFunction *F = BB->getParent();
8705     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8706     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8707     F->insert(It, copy0MBB);
8708     F->insert(It, sinkMBB);
8709 
8710     // Transfer the remainder of BB and its successor edges to sinkMBB.
8711     sinkMBB->splice(sinkMBB->begin(), BB,
8712                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8713     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8714 
8715     BB->addSuccessor(copy0MBB);
8716     BB->addSuccessor(sinkMBB);
8717 
8718     BuildMI(BB, dl, TII->get(ARM::tBcc))
8719         .addMBB(sinkMBB)
8720         .addImm(MI.getOperand(3).getImm())
8721         .addReg(MI.getOperand(4).getReg());
8722 
8723     //  copy0MBB:
8724     //   %FalseValue = ...
8725     //   # fallthrough to sinkMBB
8726     BB = copy0MBB;
8727 
8728     // Update machine-CFG edges
8729     BB->addSuccessor(sinkMBB);
8730 
8731     //  sinkMBB:
8732     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8733     //  ...
8734     BB = sinkMBB;
8735     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8736         .addReg(MI.getOperand(1).getReg())
8737         .addMBB(copy0MBB)
8738         .addReg(MI.getOperand(2).getReg())
8739         .addMBB(thisMBB);
8740 
8741     MI.eraseFromParent(); // The pseudo instruction is gone now.
8742     return BB;
8743   }
8744 
8745   case ARM::BCCi64:
8746   case ARM::BCCZi64: {
8747     // If there is an unconditional branch to the other successor, remove it.
8748     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8749 
8750     // Compare both parts that make up the double comparison separately for
8751     // equality.
8752     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8753 
8754     unsigned LHS1 = MI.getOperand(1).getReg();
8755     unsigned LHS2 = MI.getOperand(2).getReg();
8756     if (RHSisZero) {
8757       AddDefaultPred(BuildMI(BB, dl,
8758                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8759                      .addReg(LHS1).addImm(0));
8760       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8761         .addReg(LHS2).addImm(0)
8762         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8763     } else {
8764       unsigned RHS1 = MI.getOperand(3).getReg();
8765       unsigned RHS2 = MI.getOperand(4).getReg();
8766       AddDefaultPred(BuildMI(BB, dl,
8767                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8768                      .addReg(LHS1).addReg(RHS1));
8769       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8770         .addReg(LHS2).addReg(RHS2)
8771         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8772     }
8773 
8774     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8775     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8776     if (MI.getOperand(0).getImm() == ARMCC::NE)
8777       std::swap(destMBB, exitMBB);
8778 
8779     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8780       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8781     if (isThumb2)
8782       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8783     else
8784       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8785 
8786     MI.eraseFromParent(); // The pseudo instruction is gone now.
8787     return BB;
8788   }
8789 
8790   case ARM::Int_eh_sjlj_setjmp:
8791   case ARM::Int_eh_sjlj_setjmp_nofp:
8792   case ARM::tInt_eh_sjlj_setjmp:
8793   case ARM::t2Int_eh_sjlj_setjmp:
8794   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8795     return BB;
8796 
8797   case ARM::Int_eh_sjlj_setup_dispatch:
8798     EmitSjLjDispatchBlock(MI, BB);
8799     return BB;
8800 
8801   case ARM::ABS:
8802   case ARM::t2ABS: {
8803     // To insert an ABS instruction, we have to insert the
8804     // diamond control-flow pattern.  The incoming instruction knows the
8805     // source vreg to test against 0, the destination vreg to set,
8806     // the condition code register to branch on, the
8807     // true/false values to select between, and a branch opcode to use.
8808     // It transforms
8809     //     V1 = ABS V0
8810     // into
8811     //     V2 = MOVS V0
8812     //     BCC                      (branch to SinkBB if V0 >= 0)
8813     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8814     //     SinkBB: V1 = PHI(V2, V3)
8815     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8816     MachineFunction::iterator BBI = ++BB->getIterator();
8817     MachineFunction *Fn = BB->getParent();
8818     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8819     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8820     Fn->insert(BBI, RSBBB);
8821     Fn->insert(BBI, SinkBB);
8822 
8823     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8824     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8825     bool ABSSrcKIll = MI.getOperand(1).isKill();
8826     bool isThumb2 = Subtarget->isThumb2();
8827     MachineRegisterInfo &MRI = Fn->getRegInfo();
8828     // In Thumb mode S must not be specified if source register is the SP or
8829     // PC and if destination register is the SP, so restrict register class
8830     unsigned NewRsbDstReg =
8831       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8832 
8833     // Transfer the remainder of BB and its successor edges to sinkMBB.
8834     SinkBB->splice(SinkBB->begin(), BB,
8835                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8836     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8837 
8838     BB->addSuccessor(RSBBB);
8839     BB->addSuccessor(SinkBB);
8840 
8841     // fall through to SinkMBB
8842     RSBBB->addSuccessor(SinkBB);
8843 
8844     // insert a cmp at the end of BB
8845     AddDefaultPred(BuildMI(BB, dl,
8846                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8847                    .addReg(ABSSrcReg).addImm(0));
8848 
8849     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8850     BuildMI(BB, dl,
8851       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8852       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8853 
8854     // insert rsbri in RSBBB
8855     // Note: BCC and rsbri will be converted into predicated rsbmi
8856     // by if-conversion pass
8857     BuildMI(*RSBBB, RSBBB->begin(), dl,
8858       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8859       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8860       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8861 
8862     // insert PHI in SinkBB,
8863     // reuse ABSDstReg to not change uses of ABS instruction
8864     BuildMI(*SinkBB, SinkBB->begin(), dl,
8865       TII->get(ARM::PHI), ABSDstReg)
8866       .addReg(NewRsbDstReg).addMBB(RSBBB)
8867       .addReg(ABSSrcReg).addMBB(BB);
8868 
8869     // remove ABS instruction
8870     MI.eraseFromParent();
8871 
8872     // return last added BB
8873     return SinkBB;
8874   }
8875   case ARM::COPY_STRUCT_BYVAL_I32:
8876     ++NumLoopByVals;
8877     return EmitStructByval(MI, BB);
8878   case ARM::WIN__CHKSTK:
8879     return EmitLowered__chkstk(MI, BB);
8880   case ARM::WIN__DBZCHK:
8881     return EmitLowered__dbzchk(MI, BB);
8882   }
8883 }
8884 
8885 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8886 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8887 /// instead of as a custom inserter because we need the use list from the SDNode.
8888 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8889                                     MachineInstr &MI, const SDNode *Node) {
8890   bool isThumb1 = Subtarget->isThumb1Only();
8891 
8892   DebugLoc DL = MI.getDebugLoc();
8893   MachineFunction *MF = MI.getParent()->getParent();
8894   MachineRegisterInfo &MRI = MF->getRegInfo();
8895   MachineInstrBuilder MIB(*MF, MI);
8896 
8897   // If the new dst/src is unused mark it as dead.
8898   if (!Node->hasAnyUseOfValue(0)) {
8899     MI.getOperand(0).setIsDead(true);
8900   }
8901   if (!Node->hasAnyUseOfValue(1)) {
8902     MI.getOperand(1).setIsDead(true);
8903   }
8904 
8905   // The MEMCPY both defines and kills the scratch registers.
8906   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
8907     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8908                                                          : &ARM::GPRRegClass);
8909     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8910   }
8911 }
8912 
8913 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8914                                                       SDNode *Node) const {
8915   if (MI.getOpcode() == ARM::MEMCPY) {
8916     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8917     return;
8918   }
8919 
8920   const MCInstrDesc *MCID = &MI.getDesc();
8921   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8922   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8923   // operand is still set to noreg. If needed, set the optional operand's
8924   // register to CPSR, and remove the redundant implicit def.
8925   //
8926   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8927 
8928   // Rename pseudo opcodes.
8929   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
8930   if (NewOpc) {
8931     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8932     MCID = &TII->get(NewOpc);
8933 
8934     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
8935            "converted opcode should be the same except for cc_out");
8936 
8937     MI.setDesc(*MCID);
8938 
8939     // Add the optional cc_out operand
8940     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8941   }
8942   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8943 
8944   // Any ARM instruction that sets the 's' bit should specify an optional
8945   // "cc_out" operand in the last operand position.
8946   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8947     assert(!NewOpc && "Optional cc_out operand required");
8948     return;
8949   }
8950   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8951   // since we already have an optional CPSR def.
8952   bool definesCPSR = false;
8953   bool deadCPSR = false;
8954   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
8955        ++i) {
8956     const MachineOperand &MO = MI.getOperand(i);
8957     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8958       definesCPSR = true;
8959       if (MO.isDead())
8960         deadCPSR = true;
8961       MI.RemoveOperand(i);
8962       break;
8963     }
8964   }
8965   if (!definesCPSR) {
8966     assert(!NewOpc && "Optional cc_out operand required");
8967     return;
8968   }
8969   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8970   if (deadCPSR) {
8971     assert(!MI.getOperand(ccOutIdx).getReg() &&
8972            "expect uninitialized optional cc_out operand");
8973     return;
8974   }
8975 
8976   // If this instruction was defined with an optional CPSR def and its dag node
8977   // had a live implicit CPSR def, then activate the optional CPSR def.
8978   MachineOperand &MO = MI.getOperand(ccOutIdx);
8979   MO.setReg(ARM::CPSR);
8980   MO.setIsDef(true);
8981 }
8982 
8983 //===----------------------------------------------------------------------===//
8984 //                           ARM Optimization Hooks
8985 //===----------------------------------------------------------------------===//
8986 
8987 // Helper function that checks if N is a null or all ones constant.
8988 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8989   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8990 }
8991 
8992 // Return true if N is conditionally 0 or all ones.
8993 // Detects these expressions where cc is an i1 value:
8994 //
8995 //   (select cc 0, y)   [AllOnes=0]
8996 //   (select cc y, 0)   [AllOnes=0]
8997 //   (zext cc)          [AllOnes=0]
8998 //   (sext cc)          [AllOnes=0/1]
8999 //   (select cc -1, y)  [AllOnes=1]
9000 //   (select cc y, -1)  [AllOnes=1]
9001 //
9002 // Invert is set when N is the null/all ones constant when CC is false.
9003 // OtherOp is set to the alternative value of N.
9004 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9005                                        SDValue &CC, bool &Invert,
9006                                        SDValue &OtherOp,
9007                                        SelectionDAG &DAG) {
9008   switch (N->getOpcode()) {
9009   default: return false;
9010   case ISD::SELECT: {
9011     CC = N->getOperand(0);
9012     SDValue N1 = N->getOperand(1);
9013     SDValue N2 = N->getOperand(2);
9014     if (isZeroOrAllOnes(N1, AllOnes)) {
9015       Invert = false;
9016       OtherOp = N2;
9017       return true;
9018     }
9019     if (isZeroOrAllOnes(N2, AllOnes)) {
9020       Invert = true;
9021       OtherOp = N1;
9022       return true;
9023     }
9024     return false;
9025   }
9026   case ISD::ZERO_EXTEND:
9027     // (zext cc) can never be the all ones value.
9028     if (AllOnes)
9029       return false;
9030     LLVM_FALLTHROUGH;
9031   case ISD::SIGN_EXTEND: {
9032     SDLoc dl(N);
9033     EVT VT = N->getValueType(0);
9034     CC = N->getOperand(0);
9035     if (CC.getValueType() != MVT::i1)
9036       return false;
9037     Invert = !AllOnes;
9038     if (AllOnes)
9039       // When looking for an AllOnes constant, N is an sext, and the 'other'
9040       // value is 0.
9041       OtherOp = DAG.getConstant(0, dl, VT);
9042     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9043       // When looking for a 0 constant, N can be zext or sext.
9044       OtherOp = DAG.getConstant(1, dl, VT);
9045     else
9046       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9047                                 VT);
9048     return true;
9049   }
9050   }
9051 }
9052 
9053 // Combine a constant select operand into its use:
9054 //
9055 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9056 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9057 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9058 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9059 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9060 //
9061 // The transform is rejected if the select doesn't have a constant operand that
9062 // is null, or all ones when AllOnes is set.
9063 //
9064 // Also recognize sext/zext from i1:
9065 //
9066 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9067 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9068 //
9069 // These transformations eventually create predicated instructions.
9070 //
9071 // @param N       The node to transform.
9072 // @param Slct    The N operand that is a select.
9073 // @param OtherOp The other N operand (x above).
9074 // @param DCI     Context.
9075 // @param AllOnes Require the select constant to be all ones instead of null.
9076 // @returns The new node, or SDValue() on failure.
9077 static
9078 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9079                             TargetLowering::DAGCombinerInfo &DCI,
9080                             bool AllOnes = false) {
9081   SelectionDAG &DAG = DCI.DAG;
9082   EVT VT = N->getValueType(0);
9083   SDValue NonConstantVal;
9084   SDValue CCOp;
9085   bool SwapSelectOps;
9086   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9087                                   NonConstantVal, DAG))
9088     return SDValue();
9089 
9090   // Slct is now know to be the desired identity constant when CC is true.
9091   SDValue TrueVal = OtherOp;
9092   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9093                                  OtherOp, NonConstantVal);
9094   // Unless SwapSelectOps says CC should be false.
9095   if (SwapSelectOps)
9096     std::swap(TrueVal, FalseVal);
9097 
9098   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9099                      CCOp, TrueVal, FalseVal);
9100 }
9101 
9102 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9103 static
9104 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9105                                        TargetLowering::DAGCombinerInfo &DCI) {
9106   SDValue N0 = N->getOperand(0);
9107   SDValue N1 = N->getOperand(1);
9108   if (N0.getNode()->hasOneUse())
9109     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9110       return Result;
9111   if (N1.getNode()->hasOneUse())
9112     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9113       return Result;
9114   return SDValue();
9115 }
9116 
9117 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
9118 // (only after legalization).
9119 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9120                                  TargetLowering::DAGCombinerInfo &DCI,
9121                                  const ARMSubtarget *Subtarget) {
9122 
9123   // Only perform optimization if after legalize, and if NEON is available. We
9124   // also expected both operands to be BUILD_VECTORs.
9125   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9126       || N0.getOpcode() != ISD::BUILD_VECTOR
9127       || N1.getOpcode() != ISD::BUILD_VECTOR)
9128     return SDValue();
9129 
9130   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9131   EVT VT = N->getValueType(0);
9132   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9133     return SDValue();
9134 
9135   // Check that the vector operands are of the right form.
9136   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9137   // operands, where N is the size of the formed vector.
9138   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9139   // index such that we have a pair wise add pattern.
9140 
9141   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9142   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9143     return SDValue();
9144   SDValue Vec = N0->getOperand(0)->getOperand(0);
9145   SDNode *V = Vec.getNode();
9146   unsigned nextIndex = 0;
9147 
9148   // For each operands to the ADD which are BUILD_VECTORs,
9149   // check to see if each of their operands are an EXTRACT_VECTOR with
9150   // the same vector and appropriate index.
9151   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9152     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9153         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9154 
9155       SDValue ExtVec0 = N0->getOperand(i);
9156       SDValue ExtVec1 = N1->getOperand(i);
9157 
9158       // First operand is the vector, verify its the same.
9159       if (V != ExtVec0->getOperand(0).getNode() ||
9160           V != ExtVec1->getOperand(0).getNode())
9161         return SDValue();
9162 
9163       // Second is the constant, verify its correct.
9164       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9165       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9166 
9167       // For the constant, we want to see all the even or all the odd.
9168       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9169           || C1->getZExtValue() != nextIndex+1)
9170         return SDValue();
9171 
9172       // Increment index.
9173       nextIndex+=2;
9174     } else
9175       return SDValue();
9176   }
9177 
9178   // Create VPADDL node.
9179   SelectionDAG &DAG = DCI.DAG;
9180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9181 
9182   SDLoc dl(N);
9183 
9184   // Build operand list.
9185   SmallVector<SDValue, 8> Ops;
9186   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9187                                 TLI.getPointerTy(DAG.getDataLayout())));
9188 
9189   // Input is the vector.
9190   Ops.push_back(Vec);
9191 
9192   // Get widened type and narrowed type.
9193   MVT widenType;
9194   unsigned numElem = VT.getVectorNumElements();
9195 
9196   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9197   switch (inputLaneType.getSimpleVT().SimpleTy) {
9198     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9199     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9200     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9201     default:
9202       llvm_unreachable("Invalid vector element type for padd optimization.");
9203   }
9204 
9205   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9206   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9207   return DAG.getNode(ExtOp, dl, VT, tmp);
9208 }
9209 
9210 static SDValue findMUL_LOHI(SDValue V) {
9211   if (V->getOpcode() == ISD::UMUL_LOHI ||
9212       V->getOpcode() == ISD::SMUL_LOHI)
9213     return V;
9214   return SDValue();
9215 }
9216 
9217 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
9218                                      TargetLowering::DAGCombinerInfo &DCI,
9219                                      const ARMSubtarget *Subtarget) {
9220 
9221   // Look for multiply add opportunities.
9222   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9223   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9224   // a glue link from the first add to the second add.
9225   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9226   // a S/UMLAL instruction.
9227   //                  UMUL_LOHI
9228   //                 / :lo    \ :hi
9229   //                /          \          [no multiline comment]
9230   //    loAdd ->  ADDE         |
9231   //                 \ :glue  /
9232   //                  \      /
9233   //                    ADDC   <- hiAdd
9234   //
9235   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
9236   SDValue AddcOp0 = AddcNode->getOperand(0);
9237   SDValue AddcOp1 = AddcNode->getOperand(1);
9238 
9239   // Check if the two operands are from the same mul_lohi node.
9240   if (AddcOp0.getNode() == AddcOp1.getNode())
9241     return SDValue();
9242 
9243   assert(AddcNode->getNumValues() == 2 &&
9244          AddcNode->getValueType(0) == MVT::i32 &&
9245          "Expect ADDC with two result values. First: i32");
9246 
9247   // Check that we have a glued ADDC node.
9248   if (AddcNode->getValueType(1) != MVT::Glue)
9249     return SDValue();
9250 
9251   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
9252   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9253       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9254       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9255       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9256     return SDValue();
9257 
9258   // Look for the glued ADDE.
9259   SDNode* AddeNode = AddcNode->getGluedUser();
9260   if (!AddeNode)
9261     return SDValue();
9262 
9263   // Make sure it is really an ADDE.
9264   if (AddeNode->getOpcode() != ISD::ADDE)
9265     return SDValue();
9266 
9267   assert(AddeNode->getNumOperands() == 3 &&
9268          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
9269          "ADDE node has the wrong inputs");
9270 
9271   // Check for the triangle shape.
9272   SDValue AddeOp0 = AddeNode->getOperand(0);
9273   SDValue AddeOp1 = AddeNode->getOperand(1);
9274 
9275   // Make sure that the ADDE operands are not coming from the same node.
9276   if (AddeOp0.getNode() == AddeOp1.getNode())
9277     return SDValue();
9278 
9279   // Find the MUL_LOHI node walking up ADDE's operands.
9280   bool IsLeftOperandMUL = false;
9281   SDValue MULOp = findMUL_LOHI(AddeOp0);
9282   if (MULOp == SDValue())
9283    MULOp = findMUL_LOHI(AddeOp1);
9284   else
9285     IsLeftOperandMUL = true;
9286   if (MULOp == SDValue())
9287     return SDValue();
9288 
9289   // Figure out the right opcode.
9290   unsigned Opc = MULOp->getOpcode();
9291   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9292 
9293   // Figure out the high and low input values to the MLAL node.
9294   SDValue* HiAdd = nullptr;
9295   SDValue* LoMul = nullptr;
9296   SDValue* LowAdd = nullptr;
9297 
9298   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9299   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9300     return SDValue();
9301 
9302   if (IsLeftOperandMUL)
9303     HiAdd = &AddeOp1;
9304   else
9305     HiAdd = &AddeOp0;
9306 
9307 
9308   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9309   // whose low result is fed to the ADDC we are checking.
9310 
9311   if (AddcOp0 == MULOp.getValue(0)) {
9312     LoMul = &AddcOp0;
9313     LowAdd = &AddcOp1;
9314   }
9315   if (AddcOp1 == MULOp.getValue(0)) {
9316     LoMul = &AddcOp1;
9317     LowAdd = &AddcOp0;
9318   }
9319 
9320   if (!LoMul)
9321     return SDValue();
9322 
9323   // Create the merged node.
9324   SelectionDAG &DAG = DCI.DAG;
9325 
9326   // Build operand list.
9327   SmallVector<SDValue, 8> Ops;
9328   Ops.push_back(LoMul->getOperand(0));
9329   Ops.push_back(LoMul->getOperand(1));
9330   Ops.push_back(*LowAdd);
9331   Ops.push_back(*HiAdd);
9332 
9333   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9334                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9335 
9336   // Replace the ADDs' nodes uses by the MLA node's values.
9337   SDValue HiMLALResult(MLALNode.getNode(), 1);
9338   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9339 
9340   SDValue LoMLALResult(MLALNode.getNode(), 0);
9341   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9342 
9343   // Return original node to notify the driver to stop replacing.
9344   SDValue resNode(AddcNode, 0);
9345   return resNode;
9346 }
9347 
9348 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
9349                                       TargetLowering::DAGCombinerInfo &DCI,
9350                                       const ARMSubtarget *Subtarget) {
9351   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9352   // While trying to combine for the other MLAL nodes, first search for the
9353   // chance to use UMAAL. Check if Addc uses another addc node which can first
9354   // be combined into a UMLAL. The other pattern is AddcNode being combined
9355   // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
9356 
9357   if (!Subtarget->hasV6Ops() ||
9358       (Subtarget->isThumb() && !Subtarget->hasThumb2()))
9359     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9360 
9361   SDNode *PrevAddc = nullptr;
9362   if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
9363     PrevAddc = AddcNode->getOperand(0).getNode();
9364   else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
9365     PrevAddc = AddcNode->getOperand(1).getNode();
9366 
9367   // If there's no addc chains, just return a search for any MLAL.
9368   if (PrevAddc == nullptr)
9369     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9370 
9371   // Try to convert the addc operand to an MLAL and if that fails try to
9372   // combine AddcNode.
9373   SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
9374   if (MLAL != SDValue(PrevAddc, 0))
9375     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9376 
9377   // Find the converted UMAAL or quit if it doesn't exist.
9378   SDNode *UmlalNode = nullptr;
9379   SDValue AddHi;
9380   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9381     UmlalNode = AddcNode->getOperand(0).getNode();
9382     AddHi = AddcNode->getOperand(1);
9383   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9384     UmlalNode = AddcNode->getOperand(1).getNode();
9385     AddHi = AddcNode->getOperand(0);
9386   } else {
9387     return SDValue();
9388   }
9389 
9390   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9391   // the ADDC as well as Zero.
9392   auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
9393 
9394   if (!Zero || Zero->getZExtValue() != 0)
9395     return SDValue();
9396 
9397   // Check that we have a glued ADDC node.
9398   if (AddcNode->getValueType(1) != MVT::Glue)
9399     return SDValue();
9400 
9401   // Look for the glued ADDE.
9402   SDNode* AddeNode = AddcNode->getGluedUser();
9403   if (!AddeNode)
9404     return SDValue();
9405 
9406   if ((AddeNode->getOperand(0).getNode() == Zero &&
9407        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9408       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9409        AddeNode->getOperand(1).getNode() == Zero)) {
9410 
9411     SelectionDAG &DAG = DCI.DAG;
9412     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9413                       UmlalNode->getOperand(2), AddHi };
9414     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9415                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9416 
9417     // Replace the ADDs' nodes uses by the UMAAL node's values.
9418     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9419     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9420 
9421     // Return original node to notify the driver to stop replacing.
9422     return SDValue(AddcNode, 0);
9423   }
9424   return SDValue();
9425 }
9426 
9427 /// PerformADDCCombine - Target-specific dag combine transform from
9428 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9429 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9430 static SDValue PerformADDCCombine(SDNode *N,
9431                                  TargetLowering::DAGCombinerInfo &DCI,
9432                                  const ARMSubtarget *Subtarget) {
9433 
9434   if (Subtarget->isThumb1Only()) return SDValue();
9435 
9436   // Only perform the checks after legalize when the pattern is available.
9437   if (DCI.isBeforeLegalize()) return SDValue();
9438 
9439   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9440 }
9441 
9442 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9443 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9444 /// called with the default operands, and if that fails, with commuted
9445 /// operands.
9446 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9447                                           TargetLowering::DAGCombinerInfo &DCI,
9448                                           const ARMSubtarget *Subtarget){
9449 
9450   // Attempt to create vpaddl for this add.
9451   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
9452     return Result;
9453 
9454   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9455   if (N0.getNode()->hasOneUse())
9456     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9457       return Result;
9458   return SDValue();
9459 }
9460 
9461 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9462 ///
9463 static SDValue PerformADDCombine(SDNode *N,
9464                                  TargetLowering::DAGCombinerInfo &DCI,
9465                                  const ARMSubtarget *Subtarget) {
9466   SDValue N0 = N->getOperand(0);
9467   SDValue N1 = N->getOperand(1);
9468 
9469   // First try with the default operand order.
9470   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9471     return Result;
9472 
9473   // If that didn't work, try again with the operands commuted.
9474   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9475 }
9476 
9477 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9478 ///
9479 static SDValue PerformSUBCombine(SDNode *N,
9480                                  TargetLowering::DAGCombinerInfo &DCI) {
9481   SDValue N0 = N->getOperand(0);
9482   SDValue N1 = N->getOperand(1);
9483 
9484   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9485   if (N1.getNode()->hasOneUse())
9486     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9487       return Result;
9488 
9489   return SDValue();
9490 }
9491 
9492 /// PerformVMULCombine
9493 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9494 /// special multiplier accumulator forwarding.
9495 ///   vmul d3, d0, d2
9496 ///   vmla d3, d1, d2
9497 /// is faster than
9498 ///   vadd d3, d0, d1
9499 ///   vmul d3, d3, d2
9500 //  However, for (A + B) * (A + B),
9501 //    vadd d2, d0, d1
9502 //    vmul d3, d0, d2
9503 //    vmla d3, d1, d2
9504 //  is slower than
9505 //    vadd d2, d0, d1
9506 //    vmul d3, d2, d2
9507 static SDValue PerformVMULCombine(SDNode *N,
9508                                   TargetLowering::DAGCombinerInfo &DCI,
9509                                   const ARMSubtarget *Subtarget) {
9510   if (!Subtarget->hasVMLxForwarding())
9511     return SDValue();
9512 
9513   SelectionDAG &DAG = DCI.DAG;
9514   SDValue N0 = N->getOperand(0);
9515   SDValue N1 = N->getOperand(1);
9516   unsigned Opcode = N0.getOpcode();
9517   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9518       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9519     Opcode = N1.getOpcode();
9520     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9521         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9522       return SDValue();
9523     std::swap(N0, N1);
9524   }
9525 
9526   if (N0 == N1)
9527     return SDValue();
9528 
9529   EVT VT = N->getValueType(0);
9530   SDLoc DL(N);
9531   SDValue N00 = N0->getOperand(0);
9532   SDValue N01 = N0->getOperand(1);
9533   return DAG.getNode(Opcode, DL, VT,
9534                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9535                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9536 }
9537 
9538 static SDValue PerformMULCombine(SDNode *N,
9539                                  TargetLowering::DAGCombinerInfo &DCI,
9540                                  const ARMSubtarget *Subtarget) {
9541   SelectionDAG &DAG = DCI.DAG;
9542 
9543   if (Subtarget->isThumb1Only())
9544     return SDValue();
9545 
9546   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9547     return SDValue();
9548 
9549   EVT VT = N->getValueType(0);
9550   if (VT.is64BitVector() || VT.is128BitVector())
9551     return PerformVMULCombine(N, DCI, Subtarget);
9552   if (VT != MVT::i32)
9553     return SDValue();
9554 
9555   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9556   if (!C)
9557     return SDValue();
9558 
9559   int64_t MulAmt = C->getSExtValue();
9560   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9561 
9562   ShiftAmt = ShiftAmt & (32 - 1);
9563   SDValue V = N->getOperand(0);
9564   SDLoc DL(N);
9565 
9566   SDValue Res;
9567   MulAmt >>= ShiftAmt;
9568 
9569   if (MulAmt >= 0) {
9570     if (isPowerOf2_32(MulAmt - 1)) {
9571       // (mul x, 2^N + 1) => (add (shl x, N), x)
9572       Res = DAG.getNode(ISD::ADD, DL, VT,
9573                         V,
9574                         DAG.getNode(ISD::SHL, DL, VT,
9575                                     V,
9576                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9577                                                     MVT::i32)));
9578     } else if (isPowerOf2_32(MulAmt + 1)) {
9579       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9580       Res = DAG.getNode(ISD::SUB, DL, VT,
9581                         DAG.getNode(ISD::SHL, DL, VT,
9582                                     V,
9583                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9584                                                     MVT::i32)),
9585                         V);
9586     } else
9587       return SDValue();
9588   } else {
9589     uint64_t MulAmtAbs = -MulAmt;
9590     if (isPowerOf2_32(MulAmtAbs + 1)) {
9591       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9592       Res = DAG.getNode(ISD::SUB, DL, VT,
9593                         V,
9594                         DAG.getNode(ISD::SHL, DL, VT,
9595                                     V,
9596                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9597                                                     MVT::i32)));
9598     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9599       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9600       Res = DAG.getNode(ISD::ADD, DL, VT,
9601                         V,
9602                         DAG.getNode(ISD::SHL, DL, VT,
9603                                     V,
9604                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9605                                                     MVT::i32)));
9606       Res = DAG.getNode(ISD::SUB, DL, VT,
9607                         DAG.getConstant(0, DL, MVT::i32), Res);
9608 
9609     } else
9610       return SDValue();
9611   }
9612 
9613   if (ShiftAmt != 0)
9614     Res = DAG.getNode(ISD::SHL, DL, VT,
9615                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9616 
9617   // Do not add new nodes to DAG combiner worklist.
9618   DCI.CombineTo(N, Res, false);
9619   return SDValue();
9620 }
9621 
9622 static SDValue PerformANDCombine(SDNode *N,
9623                                  TargetLowering::DAGCombinerInfo &DCI,
9624                                  const ARMSubtarget *Subtarget) {
9625 
9626   // Attempt to use immediate-form VBIC
9627   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9628   SDLoc dl(N);
9629   EVT VT = N->getValueType(0);
9630   SelectionDAG &DAG = DCI.DAG;
9631 
9632   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9633     return SDValue();
9634 
9635   APInt SplatBits, SplatUndef;
9636   unsigned SplatBitSize;
9637   bool HasAnyUndefs;
9638   if (BVN &&
9639       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9640     if (SplatBitSize <= 64) {
9641       EVT VbicVT;
9642       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9643                                       SplatUndef.getZExtValue(), SplatBitSize,
9644                                       DAG, dl, VbicVT, VT.is128BitVector(),
9645                                       OtherModImm);
9646       if (Val.getNode()) {
9647         SDValue Input =
9648           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9649         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9650         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9651       }
9652     }
9653   }
9654 
9655   if (!Subtarget->isThumb1Only()) {
9656     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9657     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9658       return Result;
9659   }
9660 
9661   return SDValue();
9662 }
9663 
9664 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9665 static SDValue PerformORCombine(SDNode *N,
9666                                 TargetLowering::DAGCombinerInfo &DCI,
9667                                 const ARMSubtarget *Subtarget) {
9668   // Attempt to use immediate-form VORR
9669   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9670   SDLoc dl(N);
9671   EVT VT = N->getValueType(0);
9672   SelectionDAG &DAG = DCI.DAG;
9673 
9674   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9675     return SDValue();
9676 
9677   APInt SplatBits, SplatUndef;
9678   unsigned SplatBitSize;
9679   bool HasAnyUndefs;
9680   if (BVN && Subtarget->hasNEON() &&
9681       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9682     if (SplatBitSize <= 64) {
9683       EVT VorrVT;
9684       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9685                                       SplatUndef.getZExtValue(), SplatBitSize,
9686                                       DAG, dl, VorrVT, VT.is128BitVector(),
9687                                       OtherModImm);
9688       if (Val.getNode()) {
9689         SDValue Input =
9690           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9691         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9692         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9693       }
9694     }
9695   }
9696 
9697   if (!Subtarget->isThumb1Only()) {
9698     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9699     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9700       return Result;
9701   }
9702 
9703   // The code below optimizes (or (and X, Y), Z).
9704   // The AND operand needs to have a single user to make these optimizations
9705   // profitable.
9706   SDValue N0 = N->getOperand(0);
9707   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9708     return SDValue();
9709   SDValue N1 = N->getOperand(1);
9710 
9711   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9712   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9713       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9714     APInt SplatUndef;
9715     unsigned SplatBitSize;
9716     bool HasAnyUndefs;
9717 
9718     APInt SplatBits0, SplatBits1;
9719     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9720     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9721     // Ensure that the second operand of both ands are constants
9722     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9723                                       HasAnyUndefs) && !HasAnyUndefs) {
9724         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9725                                           HasAnyUndefs) && !HasAnyUndefs) {
9726             // Ensure that the bit width of the constants are the same and that
9727             // the splat arguments are logical inverses as per the pattern we
9728             // are trying to simplify.
9729             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9730                 SplatBits0 == ~SplatBits1) {
9731                 // Canonicalize the vector type to make instruction selection
9732                 // simpler.
9733                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9734                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9735                                              N0->getOperand(1),
9736                                              N0->getOperand(0),
9737                                              N1->getOperand(0));
9738                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9739             }
9740         }
9741     }
9742   }
9743 
9744   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9745   // reasonable.
9746 
9747   // BFI is only available on V6T2+
9748   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9749     return SDValue();
9750 
9751   SDLoc DL(N);
9752   // 1) or (and A, mask), val => ARMbfi A, val, mask
9753   //      iff (val & mask) == val
9754   //
9755   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9756   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9757   //          && mask == ~mask2
9758   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9759   //          && ~mask == mask2
9760   //  (i.e., copy a bitfield value into another bitfield of the same width)
9761 
9762   if (VT != MVT::i32)
9763     return SDValue();
9764 
9765   SDValue N00 = N0.getOperand(0);
9766 
9767   // The value and the mask need to be constants so we can verify this is
9768   // actually a bitfield set. If the mask is 0xffff, we can do better
9769   // via a movt instruction, so don't use BFI in that case.
9770   SDValue MaskOp = N0.getOperand(1);
9771   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9772   if (!MaskC)
9773     return SDValue();
9774   unsigned Mask = MaskC->getZExtValue();
9775   if (Mask == 0xffff)
9776     return SDValue();
9777   SDValue Res;
9778   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9779   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9780   if (N1C) {
9781     unsigned Val = N1C->getZExtValue();
9782     if ((Val & ~Mask) != Val)
9783       return SDValue();
9784 
9785     if (ARM::isBitFieldInvertedMask(Mask)) {
9786       Val >>= countTrailingZeros(~Mask);
9787 
9788       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9789                         DAG.getConstant(Val, DL, MVT::i32),
9790                         DAG.getConstant(Mask, DL, MVT::i32));
9791 
9792       // Do not add new nodes to DAG combiner worklist.
9793       DCI.CombineTo(N, Res, false);
9794       return SDValue();
9795     }
9796   } else if (N1.getOpcode() == ISD::AND) {
9797     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9798     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9799     if (!N11C)
9800       return SDValue();
9801     unsigned Mask2 = N11C->getZExtValue();
9802 
9803     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9804     // as is to match.
9805     if (ARM::isBitFieldInvertedMask(Mask) &&
9806         (Mask == ~Mask2)) {
9807       // The pack halfword instruction works better for masks that fit it,
9808       // so use that when it's available.
9809       if (Subtarget->hasT2ExtractPack() &&
9810           (Mask == 0xffff || Mask == 0xffff0000))
9811         return SDValue();
9812       // 2a
9813       unsigned amt = countTrailingZeros(Mask2);
9814       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9815                         DAG.getConstant(amt, DL, MVT::i32));
9816       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9817                         DAG.getConstant(Mask, DL, MVT::i32));
9818       // Do not add new nodes to DAG combiner worklist.
9819       DCI.CombineTo(N, Res, false);
9820       return SDValue();
9821     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9822                (~Mask == Mask2)) {
9823       // The pack halfword instruction works better for masks that fit it,
9824       // so use that when it's available.
9825       if (Subtarget->hasT2ExtractPack() &&
9826           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9827         return SDValue();
9828       // 2b
9829       unsigned lsb = countTrailingZeros(Mask);
9830       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9831                         DAG.getConstant(lsb, DL, MVT::i32));
9832       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9833                         DAG.getConstant(Mask2, DL, MVT::i32));
9834       // Do not add new nodes to DAG combiner worklist.
9835       DCI.CombineTo(N, Res, false);
9836       return SDValue();
9837     }
9838   }
9839 
9840   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9841       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9842       ARM::isBitFieldInvertedMask(~Mask)) {
9843     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9844     // where lsb(mask) == #shamt and masked bits of B are known zero.
9845     SDValue ShAmt = N00.getOperand(1);
9846     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9847     unsigned LSB = countTrailingZeros(Mask);
9848     if (ShAmtC != LSB)
9849       return SDValue();
9850 
9851     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9852                       DAG.getConstant(~Mask, DL, MVT::i32));
9853 
9854     // Do not add new nodes to DAG combiner worklist.
9855     DCI.CombineTo(N, Res, false);
9856   }
9857 
9858   return SDValue();
9859 }
9860 
9861 static SDValue PerformXORCombine(SDNode *N,
9862                                  TargetLowering::DAGCombinerInfo &DCI,
9863                                  const ARMSubtarget *Subtarget) {
9864   EVT VT = N->getValueType(0);
9865   SelectionDAG &DAG = DCI.DAG;
9866 
9867   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9868     return SDValue();
9869 
9870   if (!Subtarget->isThumb1Only()) {
9871     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9872     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9873       return Result;
9874   }
9875 
9876   return SDValue();
9877 }
9878 
9879 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9880 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9881 // their position in "to" (Rd).
9882 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9883   assert(N->getOpcode() == ARMISD::BFI);
9884 
9885   SDValue From = N->getOperand(1);
9886   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9887   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9888 
9889   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9890   // #C in the base of the SHR.
9891   if (From->getOpcode() == ISD::SRL &&
9892       isa<ConstantSDNode>(From->getOperand(1))) {
9893     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9894     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9895     FromMask <<= Shift.getLimitedValue(31);
9896     From = From->getOperand(0);
9897   }
9898 
9899   return From;
9900 }
9901 
9902 // If A and B contain one contiguous set of bits, does A | B == A . B?
9903 //
9904 // Neither A nor B must be zero.
9905 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9906   unsigned LastActiveBitInA =  A.countTrailingZeros();
9907   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9908   return LastActiveBitInA - 1 == FirstActiveBitInB;
9909 }
9910 
9911 static SDValue FindBFIToCombineWith(SDNode *N) {
9912   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9913   // if one exists.
9914   APInt ToMask, FromMask;
9915   SDValue From = ParseBFI(N, ToMask, FromMask);
9916   SDValue To = N->getOperand(0);
9917 
9918   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9919   // aren't compatible, but not if they set the same bit in their destination as
9920   // we do (or that of any BFI we're going to combine with).
9921   SDValue V = To;
9922   APInt CombinedToMask = ToMask;
9923   while (V.getOpcode() == ARMISD::BFI) {
9924     APInt NewToMask, NewFromMask;
9925     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9926     if (NewFrom != From) {
9927       // This BFI has a different base. Keep going.
9928       CombinedToMask |= NewToMask;
9929       V = V.getOperand(0);
9930       continue;
9931     }
9932 
9933     // Do the written bits conflict with any we've seen so far?
9934     if ((NewToMask & CombinedToMask).getBoolValue())
9935       // Conflicting bits - bail out because going further is unsafe.
9936       return SDValue();
9937 
9938     // Are the new bits contiguous when combined with the old bits?
9939     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9940         BitsProperlyConcatenate(FromMask, NewFromMask))
9941       return V;
9942     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9943         BitsProperlyConcatenate(NewFromMask, FromMask))
9944       return V;
9945 
9946     // We've seen a write to some bits, so track it.
9947     CombinedToMask |= NewToMask;
9948     // Keep going...
9949     V = V.getOperand(0);
9950   }
9951 
9952   return SDValue();
9953 }
9954 
9955 static SDValue PerformBFICombine(SDNode *N,
9956                                  TargetLowering::DAGCombinerInfo &DCI) {
9957   SDValue N1 = N->getOperand(1);
9958   if (N1.getOpcode() == ISD::AND) {
9959     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9960     // the bits being cleared by the AND are not demanded by the BFI.
9961     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9962     if (!N11C)
9963       return SDValue();
9964     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9965     unsigned LSB = countTrailingZeros(~InvMask);
9966     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9967     assert(Width <
9968                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9969            "undefined behavior");
9970     unsigned Mask = (1u << Width) - 1;
9971     unsigned Mask2 = N11C->getZExtValue();
9972     if ((Mask & (~Mask2)) == 0)
9973       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9974                              N->getOperand(0), N1.getOperand(0),
9975                              N->getOperand(2));
9976   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9977     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9978     // Keep track of any consecutive bits set that all come from the same base
9979     // value. We can combine these together into a single BFI.
9980     SDValue CombineBFI = FindBFIToCombineWith(N);
9981     if (CombineBFI == SDValue())
9982       return SDValue();
9983 
9984     // We've found a BFI.
9985     APInt ToMask1, FromMask1;
9986     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9987 
9988     APInt ToMask2, FromMask2;
9989     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9990     assert(From1 == From2);
9991     (void)From2;
9992 
9993     // First, unlink CombineBFI.
9994     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9995     // Then create a new BFI, combining the two together.
9996     APInt NewFromMask = FromMask1 | FromMask2;
9997     APInt NewToMask = ToMask1 | ToMask2;
9998 
9999     EVT VT = N->getValueType(0);
10000     SDLoc dl(N);
10001 
10002     if (NewFromMask[0] == 0)
10003       From1 = DCI.DAG.getNode(
10004         ISD::SRL, dl, VT, From1,
10005         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10006     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10007                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10008   }
10009   return SDValue();
10010 }
10011 
10012 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10013 /// ARMISD::VMOVRRD.
10014 static SDValue PerformVMOVRRDCombine(SDNode *N,
10015                                      TargetLowering::DAGCombinerInfo &DCI,
10016                                      const ARMSubtarget *Subtarget) {
10017   // vmovrrd(vmovdrr x, y) -> x,y
10018   SDValue InDouble = N->getOperand(0);
10019   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10020     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10021 
10022   // vmovrrd(load f64) -> (load i32), (load i32)
10023   SDNode *InNode = InDouble.getNode();
10024   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10025       InNode->getValueType(0) == MVT::f64 &&
10026       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10027       !cast<LoadSDNode>(InNode)->isVolatile()) {
10028     // TODO: Should this be done for non-FrameIndex operands?
10029     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10030 
10031     SelectionDAG &DAG = DCI.DAG;
10032     SDLoc DL(LD);
10033     SDValue BasePtr = LD->getBasePtr();
10034     SDValue NewLD1 =
10035         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10036                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10037 
10038     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10039                                     DAG.getConstant(4, DL, MVT::i32));
10040     SDValue NewLD2 = DAG.getLoad(
10041         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10042         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10043 
10044     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10045     if (DCI.DAG.getDataLayout().isBigEndian())
10046       std::swap (NewLD1, NewLD2);
10047     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10048     return Result;
10049   }
10050 
10051   return SDValue();
10052 }
10053 
10054 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10055 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10056 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10057   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10058   SDValue Op0 = N->getOperand(0);
10059   SDValue Op1 = N->getOperand(1);
10060   if (Op0.getOpcode() == ISD::BITCAST)
10061     Op0 = Op0.getOperand(0);
10062   if (Op1.getOpcode() == ISD::BITCAST)
10063     Op1 = Op1.getOperand(0);
10064   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10065       Op0.getNode() == Op1.getNode() &&
10066       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10067     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10068                        N->getValueType(0), Op0.getOperand(0));
10069   return SDValue();
10070 }
10071 
10072 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10073 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10074 /// i64 vector to have f64 elements, since the value can then be loaded
10075 /// directly into a VFP register.
10076 static bool hasNormalLoadOperand(SDNode *N) {
10077   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10078   for (unsigned i = 0; i < NumElts; ++i) {
10079     SDNode *Elt = N->getOperand(i).getNode();
10080     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10081       return true;
10082   }
10083   return false;
10084 }
10085 
10086 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10087 /// ISD::BUILD_VECTOR.
10088 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10089                                           TargetLowering::DAGCombinerInfo &DCI,
10090                                           const ARMSubtarget *Subtarget) {
10091   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10092   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10093   // into a pair of GPRs, which is fine when the value is used as a scalar,
10094   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10095   SelectionDAG &DAG = DCI.DAG;
10096   if (N->getNumOperands() == 2)
10097     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10098       return RV;
10099 
10100   // Load i64 elements as f64 values so that type legalization does not split
10101   // them up into i32 values.
10102   EVT VT = N->getValueType(0);
10103   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10104     return SDValue();
10105   SDLoc dl(N);
10106   SmallVector<SDValue, 8> Ops;
10107   unsigned NumElts = VT.getVectorNumElements();
10108   for (unsigned i = 0; i < NumElts; ++i) {
10109     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10110     Ops.push_back(V);
10111     // Make the DAGCombiner fold the bitcast.
10112     DCI.AddToWorklist(V.getNode());
10113   }
10114   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10115   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10116   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10117 }
10118 
10119 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10120 static SDValue
10121 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10122   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10123   // At that time, we may have inserted bitcasts from integer to float.
10124   // If these bitcasts have survived DAGCombine, change the lowering of this
10125   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10126   // force to use floating point types.
10127 
10128   // Make sure we can change the type of the vector.
10129   // This is possible iff:
10130   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10131   //    1.1. Vector is used only once.
10132   //    1.2. Use is a bit convert to an integer type.
10133   // 2. The size of its operands are 32-bits (64-bits are not legal).
10134   EVT VT = N->getValueType(0);
10135   EVT EltVT = VT.getVectorElementType();
10136 
10137   // Check 1.1. and 2.
10138   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10139     return SDValue();
10140 
10141   // By construction, the input type must be float.
10142   assert(EltVT == MVT::f32 && "Unexpected type!");
10143 
10144   // Check 1.2.
10145   SDNode *Use = *N->use_begin();
10146   if (Use->getOpcode() != ISD::BITCAST ||
10147       Use->getValueType(0).isFloatingPoint())
10148     return SDValue();
10149 
10150   // Check profitability.
10151   // Model is, if more than half of the relevant operands are bitcast from
10152   // i32, turn the build_vector into a sequence of insert_vector_elt.
10153   // Relevant operands are everything that is not statically
10154   // (i.e., at compile time) bitcasted.
10155   unsigned NumOfBitCastedElts = 0;
10156   unsigned NumElts = VT.getVectorNumElements();
10157   unsigned NumOfRelevantElts = NumElts;
10158   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10159     SDValue Elt = N->getOperand(Idx);
10160     if (Elt->getOpcode() == ISD::BITCAST) {
10161       // Assume only bit cast to i32 will go away.
10162       if (Elt->getOperand(0).getValueType() == MVT::i32)
10163         ++NumOfBitCastedElts;
10164     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10165       // Constants are statically casted, thus do not count them as
10166       // relevant operands.
10167       --NumOfRelevantElts;
10168   }
10169 
10170   // Check if more than half of the elements require a non-free bitcast.
10171   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10172     return SDValue();
10173 
10174   SelectionDAG &DAG = DCI.DAG;
10175   // Create the new vector type.
10176   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10177   // Check if the type is legal.
10178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10179   if (!TLI.isTypeLegal(VecVT))
10180     return SDValue();
10181 
10182   // Combine:
10183   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10184   // => BITCAST INSERT_VECTOR_ELT
10185   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10186   //                      (BITCAST EN), N.
10187   SDValue Vec = DAG.getUNDEF(VecVT);
10188   SDLoc dl(N);
10189   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10190     SDValue V = N->getOperand(Idx);
10191     if (V.isUndef())
10192       continue;
10193     if (V.getOpcode() == ISD::BITCAST &&
10194         V->getOperand(0).getValueType() == MVT::i32)
10195       // Fold obvious case.
10196       V = V.getOperand(0);
10197     else {
10198       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10199       // Make the DAGCombiner fold the bitcasts.
10200       DCI.AddToWorklist(V.getNode());
10201     }
10202     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10203     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10204   }
10205   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10206   // Make the DAGCombiner fold the bitcasts.
10207   DCI.AddToWorklist(Vec.getNode());
10208   return Vec;
10209 }
10210 
10211 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10212 /// ISD::INSERT_VECTOR_ELT.
10213 static SDValue PerformInsertEltCombine(SDNode *N,
10214                                        TargetLowering::DAGCombinerInfo &DCI) {
10215   // Bitcast an i64 load inserted into a vector to f64.
10216   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10217   EVT VT = N->getValueType(0);
10218   SDNode *Elt = N->getOperand(1).getNode();
10219   if (VT.getVectorElementType() != MVT::i64 ||
10220       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10221     return SDValue();
10222 
10223   SelectionDAG &DAG = DCI.DAG;
10224   SDLoc dl(N);
10225   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10226                                  VT.getVectorNumElements());
10227   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10228   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10229   // Make the DAGCombiner fold the bitcasts.
10230   DCI.AddToWorklist(Vec.getNode());
10231   DCI.AddToWorklist(V.getNode());
10232   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10233                                Vec, V, N->getOperand(2));
10234   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10235 }
10236 
10237 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10238 /// ISD::VECTOR_SHUFFLE.
10239 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10240   // The LLVM shufflevector instruction does not require the shuffle mask
10241   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10242   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10243   // operands do not match the mask length, they are extended by concatenating
10244   // them with undef vectors.  That is probably the right thing for other
10245   // targets, but for NEON it is better to concatenate two double-register
10246   // size vector operands into a single quad-register size vector.  Do that
10247   // transformation here:
10248   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10249   //   shuffle(concat(v1, v2), undef)
10250   SDValue Op0 = N->getOperand(0);
10251   SDValue Op1 = N->getOperand(1);
10252   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10253       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10254       Op0.getNumOperands() != 2 ||
10255       Op1.getNumOperands() != 2)
10256     return SDValue();
10257   SDValue Concat0Op1 = Op0.getOperand(1);
10258   SDValue Concat1Op1 = Op1.getOperand(1);
10259   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10260     return SDValue();
10261   // Skip the transformation if any of the types are illegal.
10262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10263   EVT VT = N->getValueType(0);
10264   if (!TLI.isTypeLegal(VT) ||
10265       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10266       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10267     return SDValue();
10268 
10269   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10270                                   Op0.getOperand(0), Op1.getOperand(0));
10271   // Translate the shuffle mask.
10272   SmallVector<int, 16> NewMask;
10273   unsigned NumElts = VT.getVectorNumElements();
10274   unsigned HalfElts = NumElts/2;
10275   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10276   for (unsigned n = 0; n < NumElts; ++n) {
10277     int MaskElt = SVN->getMaskElt(n);
10278     int NewElt = -1;
10279     if (MaskElt < (int)HalfElts)
10280       NewElt = MaskElt;
10281     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10282       NewElt = HalfElts + MaskElt - NumElts;
10283     NewMask.push_back(NewElt);
10284   }
10285   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10286                               DAG.getUNDEF(VT), NewMask);
10287 }
10288 
10289 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10290 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10291 /// base address updates.
10292 /// For generic load/stores, the memory type is assumed to be a vector.
10293 /// The caller is assumed to have checked legality.
10294 static SDValue CombineBaseUpdate(SDNode *N,
10295                                  TargetLowering::DAGCombinerInfo &DCI) {
10296   SelectionDAG &DAG = DCI.DAG;
10297   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10298                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10299   const bool isStore = N->getOpcode() == ISD::STORE;
10300   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10301   SDValue Addr = N->getOperand(AddrOpIdx);
10302   MemSDNode *MemN = cast<MemSDNode>(N);
10303   SDLoc dl(N);
10304 
10305   // Search for a use of the address operand that is an increment.
10306   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10307          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10308     SDNode *User = *UI;
10309     if (User->getOpcode() != ISD::ADD ||
10310         UI.getUse().getResNo() != Addr.getResNo())
10311       continue;
10312 
10313     // Check that the add is independent of the load/store.  Otherwise, folding
10314     // it would create a cycle.
10315     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10316       continue;
10317 
10318     // Find the new opcode for the updating load/store.
10319     bool isLoadOp = true;
10320     bool isLaneOp = false;
10321     unsigned NewOpc = 0;
10322     unsigned NumVecs = 0;
10323     if (isIntrinsic) {
10324       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10325       switch (IntNo) {
10326       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10327       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10328         NumVecs = 1; break;
10329       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10330         NumVecs = 2; break;
10331       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10332         NumVecs = 3; break;
10333       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10334         NumVecs = 4; break;
10335       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10336         NumVecs = 2; isLaneOp = true; break;
10337       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10338         NumVecs = 3; isLaneOp = true; break;
10339       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10340         NumVecs = 4; isLaneOp = true; break;
10341       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10342         NumVecs = 1; isLoadOp = false; break;
10343       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10344         NumVecs = 2; isLoadOp = false; break;
10345       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10346         NumVecs = 3; isLoadOp = false; break;
10347       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10348         NumVecs = 4; isLoadOp = false; break;
10349       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10350         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10351       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10352         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10353       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10354         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10355       }
10356     } else {
10357       isLaneOp = true;
10358       switch (N->getOpcode()) {
10359       default: llvm_unreachable("unexpected opcode for Neon base update");
10360       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10361       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10362       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10363       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10364         NumVecs = 1; isLaneOp = false; break;
10365       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10366         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10367       }
10368     }
10369 
10370     // Find the size of memory referenced by the load/store.
10371     EVT VecTy;
10372     if (isLoadOp) {
10373       VecTy = N->getValueType(0);
10374     } else if (isIntrinsic) {
10375       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10376     } else {
10377       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10378       VecTy = N->getOperand(1).getValueType();
10379     }
10380 
10381     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10382     if (isLaneOp)
10383       NumBytes /= VecTy.getVectorNumElements();
10384 
10385     // If the increment is a constant, it must match the memory ref size.
10386     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10387     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10388       uint64_t IncVal = CInc->getZExtValue();
10389       if (IncVal != NumBytes)
10390         continue;
10391     } else if (NumBytes >= 3 * 16) {
10392       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10393       // separate instructions that make it harder to use a non-constant update.
10394       continue;
10395     }
10396 
10397     // OK, we found an ADD we can fold into the base update.
10398     // Now, create a _UPD node, taking care of not breaking alignment.
10399 
10400     EVT AlignedVecTy = VecTy;
10401     unsigned Alignment = MemN->getAlignment();
10402 
10403     // If this is a less-than-standard-aligned load/store, change the type to
10404     // match the standard alignment.
10405     // The alignment is overlooked when selecting _UPD variants; and it's
10406     // easier to introduce bitcasts here than fix that.
10407     // There are 3 ways to get to this base-update combine:
10408     // - intrinsics: they are assumed to be properly aligned (to the standard
10409     //   alignment of the memory type), so we don't need to do anything.
10410     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10411     //   intrinsics, so, likewise, there's nothing to do.
10412     // - generic load/store instructions: the alignment is specified as an
10413     //   explicit operand, rather than implicitly as the standard alignment
10414     //   of the memory type (like the intrisics).  We need to change the
10415     //   memory type to match the explicit alignment.  That way, we don't
10416     //   generate non-standard-aligned ARMISD::VLDx nodes.
10417     if (isa<LSBaseSDNode>(N)) {
10418       if (Alignment == 0)
10419         Alignment = 1;
10420       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10421         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10422         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10423         assert(!isLaneOp && "Unexpected generic load/store lane.");
10424         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10425         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10426       }
10427       // Don't set an explicit alignment on regular load/stores that we want
10428       // to transform to VLD/VST 1_UPD nodes.
10429       // This matches the behavior of regular load/stores, which only get an
10430       // explicit alignment if the MMO alignment is larger than the standard
10431       // alignment of the memory type.
10432       // Intrinsics, however, always get an explicit alignment, set to the
10433       // alignment of the MMO.
10434       Alignment = 1;
10435     }
10436 
10437     // Create the new updating load/store node.
10438     // First, create an SDVTList for the new updating node's results.
10439     EVT Tys[6];
10440     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10441     unsigned n;
10442     for (n = 0; n < NumResultVecs; ++n)
10443       Tys[n] = AlignedVecTy;
10444     Tys[n++] = MVT::i32;
10445     Tys[n] = MVT::Other;
10446     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10447 
10448     // Then, gather the new node's operands.
10449     SmallVector<SDValue, 8> Ops;
10450     Ops.push_back(N->getOperand(0)); // incoming chain
10451     Ops.push_back(N->getOperand(AddrOpIdx));
10452     Ops.push_back(Inc);
10453 
10454     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10455       // Try to match the intrinsic's signature
10456       Ops.push_back(StN->getValue());
10457     } else {
10458       // Loads (and of course intrinsics) match the intrinsics' signature,
10459       // so just add all but the alignment operand.
10460       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10461         Ops.push_back(N->getOperand(i));
10462     }
10463 
10464     // For all node types, the alignment operand is always the last one.
10465     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10466 
10467     // If this is a non-standard-aligned STORE, the penultimate operand is the
10468     // stored value.  Bitcast it to the aligned type.
10469     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10470       SDValue &StVal = Ops[Ops.size()-2];
10471       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10472     }
10473 
10474     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
10475                                            Ops, AlignedVecTy,
10476                                            MemN->getMemOperand());
10477 
10478     // Update the uses.
10479     SmallVector<SDValue, 5> NewResults;
10480     for (unsigned i = 0; i < NumResultVecs; ++i)
10481       NewResults.push_back(SDValue(UpdN.getNode(), i));
10482 
10483     // If this is an non-standard-aligned LOAD, the first result is the loaded
10484     // value.  Bitcast it to the expected result type.
10485     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10486       SDValue &LdVal = NewResults[0];
10487       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10488     }
10489 
10490     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10491     DCI.CombineTo(N, NewResults);
10492     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10493 
10494     break;
10495   }
10496   return SDValue();
10497 }
10498 
10499 static SDValue PerformVLDCombine(SDNode *N,
10500                                  TargetLowering::DAGCombinerInfo &DCI) {
10501   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10502     return SDValue();
10503 
10504   return CombineBaseUpdate(N, DCI);
10505 }
10506 
10507 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10508 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10509 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10510 /// return true.
10511 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10512   SelectionDAG &DAG = DCI.DAG;
10513   EVT VT = N->getValueType(0);
10514   // vldN-dup instructions only support 64-bit vectors for N > 1.
10515   if (!VT.is64BitVector())
10516     return false;
10517 
10518   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10519   SDNode *VLD = N->getOperand(0).getNode();
10520   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10521     return false;
10522   unsigned NumVecs = 0;
10523   unsigned NewOpc = 0;
10524   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10525   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10526     NumVecs = 2;
10527     NewOpc = ARMISD::VLD2DUP;
10528   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10529     NumVecs = 3;
10530     NewOpc = ARMISD::VLD3DUP;
10531   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10532     NumVecs = 4;
10533     NewOpc = ARMISD::VLD4DUP;
10534   } else {
10535     return false;
10536   }
10537 
10538   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10539   // numbers match the load.
10540   unsigned VLDLaneNo =
10541     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10542   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10543        UI != UE; ++UI) {
10544     // Ignore uses of the chain result.
10545     if (UI.getUse().getResNo() == NumVecs)
10546       continue;
10547     SDNode *User = *UI;
10548     if (User->getOpcode() != ARMISD::VDUPLANE ||
10549         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10550       return false;
10551   }
10552 
10553   // Create the vldN-dup node.
10554   EVT Tys[5];
10555   unsigned n;
10556   for (n = 0; n < NumVecs; ++n)
10557     Tys[n] = VT;
10558   Tys[n] = MVT::Other;
10559   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10560   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10561   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10562   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10563                                            Ops, VLDMemInt->getMemoryVT(),
10564                                            VLDMemInt->getMemOperand());
10565 
10566   // Update the uses.
10567   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10568        UI != UE; ++UI) {
10569     unsigned ResNo = UI.getUse().getResNo();
10570     // Ignore uses of the chain result.
10571     if (ResNo == NumVecs)
10572       continue;
10573     SDNode *User = *UI;
10574     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10575   }
10576 
10577   // Now the vldN-lane intrinsic is dead except for its chain result.
10578   // Update uses of the chain.
10579   std::vector<SDValue> VLDDupResults;
10580   for (unsigned n = 0; n < NumVecs; ++n)
10581     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10582   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10583   DCI.CombineTo(VLD, VLDDupResults);
10584 
10585   return true;
10586 }
10587 
10588 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10589 /// ARMISD::VDUPLANE.
10590 static SDValue PerformVDUPLANECombine(SDNode *N,
10591                                       TargetLowering::DAGCombinerInfo &DCI) {
10592   SDValue Op = N->getOperand(0);
10593 
10594   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10595   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10596   if (CombineVLDDUP(N, DCI))
10597     return SDValue(N, 0);
10598 
10599   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10600   // redundant.  Ignore bit_converts for now; element sizes are checked below.
10601   while (Op.getOpcode() == ISD::BITCAST)
10602     Op = Op.getOperand(0);
10603   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10604     return SDValue();
10605 
10606   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10607   unsigned EltSize = Op.getScalarValueSizeInBits();
10608   // The canonical VMOV for a zero vector uses a 32-bit element size.
10609   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10610   unsigned EltBits;
10611   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10612     EltSize = 8;
10613   EVT VT = N->getValueType(0);
10614   if (EltSize > VT.getScalarSizeInBits())
10615     return SDValue();
10616 
10617   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10618 }
10619 
10620 static SDValue PerformLOADCombine(SDNode *N,
10621                                   TargetLowering::DAGCombinerInfo &DCI) {
10622   EVT VT = N->getValueType(0);
10623 
10624   // If this is a legal vector load, try to combine it into a VLD1_UPD.
10625   if (ISD::isNormalLoad(N) && VT.isVector() &&
10626       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10627     return CombineBaseUpdate(N, DCI);
10628 
10629   return SDValue();
10630 }
10631 
10632 /// PerformSTORECombine - Target-specific dag combine xforms for
10633 /// ISD::STORE.
10634 static SDValue PerformSTORECombine(SDNode *N,
10635                                    TargetLowering::DAGCombinerInfo &DCI) {
10636   StoreSDNode *St = cast<StoreSDNode>(N);
10637   if (St->isVolatile())
10638     return SDValue();
10639 
10640   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
10641   // pack all of the elements in one place.  Next, store to memory in fewer
10642   // chunks.
10643   SDValue StVal = St->getValue();
10644   EVT VT = StVal.getValueType();
10645   if (St->isTruncatingStore() && VT.isVector()) {
10646     SelectionDAG &DAG = DCI.DAG;
10647     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10648     EVT StVT = St->getMemoryVT();
10649     unsigned NumElems = VT.getVectorNumElements();
10650     assert(StVT != VT && "Cannot truncate to the same type");
10651     unsigned FromEltSz = VT.getScalarSizeInBits();
10652     unsigned ToEltSz = StVT.getScalarSizeInBits();
10653 
10654     // From, To sizes and ElemCount must be pow of two
10655     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10656 
10657     // We are going to use the original vector elt for storing.
10658     // Accumulated smaller vector elements must be a multiple of the store size.
10659     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10660 
10661     unsigned SizeRatio  = FromEltSz / ToEltSz;
10662     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10663 
10664     // Create a type on which we perform the shuffle.
10665     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10666                                      NumElems*SizeRatio);
10667     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10668 
10669     SDLoc DL(St);
10670     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10671     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10672     for (unsigned i = 0; i < NumElems; ++i)
10673       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10674                           ? (i + 1) * SizeRatio - 1
10675                           : i * SizeRatio;
10676 
10677     // Can't shuffle using an illegal type.
10678     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10679 
10680     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10681                                 DAG.getUNDEF(WideVec.getValueType()),
10682                                 ShuffleVec);
10683     // At this point all of the data is stored at the bottom of the
10684     // register. We now need to save it to mem.
10685 
10686     // Find the largest store unit
10687     MVT StoreType = MVT::i8;
10688     for (MVT Tp : MVT::integer_valuetypes()) {
10689       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10690         StoreType = Tp;
10691     }
10692     // Didn't find a legal store type.
10693     if (!TLI.isTypeLegal(StoreType))
10694       return SDValue();
10695 
10696     // Bitcast the original vector into a vector of store-size units
10697     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10698             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10699     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10700     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10701     SmallVector<SDValue, 8> Chains;
10702     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10703                                         TLI.getPointerTy(DAG.getDataLayout()));
10704     SDValue BasePtr = St->getBasePtr();
10705 
10706     // Perform one or more big stores into memory.
10707     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10708     for (unsigned I = 0; I < E; I++) {
10709       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10710                                    StoreType, ShuffWide,
10711                                    DAG.getIntPtrConstant(I, DL));
10712       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10713                                 St->getPointerInfo(), St->getAlignment(),
10714                                 St->getMemOperand()->getFlags());
10715       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10716                             Increment);
10717       Chains.push_back(Ch);
10718     }
10719     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10720   }
10721 
10722   if (!ISD::isNormalStore(St))
10723     return SDValue();
10724 
10725   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10726   // ARM stores of arguments in the same cache line.
10727   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10728       StVal.getNode()->hasOneUse()) {
10729     SelectionDAG  &DAG = DCI.DAG;
10730     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10731     SDLoc DL(St);
10732     SDValue BasePtr = St->getBasePtr();
10733     SDValue NewST1 = DAG.getStore(
10734         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10735         BasePtr, St->getPointerInfo(), St->getAlignment(),
10736         St->getMemOperand()->getFlags());
10737 
10738     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10739                                     DAG.getConstant(4, DL, MVT::i32));
10740     return DAG.getStore(NewST1.getValue(0), DL,
10741                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10742                         OffsetPtr, St->getPointerInfo(),
10743                         std::min(4U, St->getAlignment() / 2),
10744                         St->getMemOperand()->getFlags());
10745   }
10746 
10747   if (StVal.getValueType() == MVT::i64 &&
10748       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10749 
10750     // Bitcast an i64 store extracted from a vector to f64.
10751     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10752     SelectionDAG &DAG = DCI.DAG;
10753     SDLoc dl(StVal);
10754     SDValue IntVec = StVal.getOperand(0);
10755     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10756                                    IntVec.getValueType().getVectorNumElements());
10757     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10758     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10759                                  Vec, StVal.getOperand(1));
10760     dl = SDLoc(N);
10761     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10762     // Make the DAGCombiner fold the bitcasts.
10763     DCI.AddToWorklist(Vec.getNode());
10764     DCI.AddToWorklist(ExtElt.getNode());
10765     DCI.AddToWorklist(V.getNode());
10766     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10767                         St->getPointerInfo(), St->getAlignment(),
10768                         St->getMemOperand()->getFlags(), St->getAAInfo());
10769   }
10770 
10771   // If this is a legal vector store, try to combine it into a VST1_UPD.
10772   if (ISD::isNormalStore(N) && VT.isVector() &&
10773       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10774     return CombineBaseUpdate(N, DCI);
10775 
10776   return SDValue();
10777 }
10778 
10779 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10780 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10781 /// when the VMUL has a constant operand that is a power of 2.
10782 ///
10783 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10784 ///  vmul.f32        d16, d17, d16
10785 ///  vcvt.s32.f32    d16, d16
10786 /// becomes:
10787 ///  vcvt.s32.f32    d16, d16, #3
10788 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10789                                   const ARMSubtarget *Subtarget) {
10790   if (!Subtarget->hasNEON())
10791     return SDValue();
10792 
10793   SDValue Op = N->getOperand(0);
10794   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10795       Op.getOpcode() != ISD::FMUL)
10796     return SDValue();
10797 
10798   SDValue ConstVec = Op->getOperand(1);
10799   if (!isa<BuildVectorSDNode>(ConstVec))
10800     return SDValue();
10801 
10802   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10803   uint32_t FloatBits = FloatTy.getSizeInBits();
10804   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10805   uint32_t IntBits = IntTy.getSizeInBits();
10806   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10807   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10808     // These instructions only exist converting from f32 to i32. We can handle
10809     // smaller integers by generating an extra truncate, but larger ones would
10810     // be lossy. We also can't handle more then 4 lanes, since these intructions
10811     // only support v2i32/v4i32 types.
10812     return SDValue();
10813   }
10814 
10815   BitVector UndefElements;
10816   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10817   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10818   if (C == -1 || C == 0 || C > 32)
10819     return SDValue();
10820 
10821   SDLoc dl(N);
10822   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10823   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10824     Intrinsic::arm_neon_vcvtfp2fxu;
10825   SDValue FixConv = DAG.getNode(
10826       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10827       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10828       DAG.getConstant(C, dl, MVT::i32));
10829 
10830   if (IntBits < FloatBits)
10831     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10832 
10833   return FixConv;
10834 }
10835 
10836 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10837 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10838 /// when the VDIV has a constant operand that is a power of 2.
10839 ///
10840 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10841 ///  vcvt.f32.s32    d16, d16
10842 ///  vdiv.f32        d16, d17, d16
10843 /// becomes:
10844 ///  vcvt.f32.s32    d16, d16, #3
10845 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10846                                   const ARMSubtarget *Subtarget) {
10847   if (!Subtarget->hasNEON())
10848     return SDValue();
10849 
10850   SDValue Op = N->getOperand(0);
10851   unsigned OpOpcode = Op.getNode()->getOpcode();
10852   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
10853       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10854     return SDValue();
10855 
10856   SDValue ConstVec = N->getOperand(1);
10857   if (!isa<BuildVectorSDNode>(ConstVec))
10858     return SDValue();
10859 
10860   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10861   uint32_t FloatBits = FloatTy.getSizeInBits();
10862   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10863   uint32_t IntBits = IntTy.getSizeInBits();
10864   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10865   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10866     // These instructions only exist converting from i32 to f32. We can handle
10867     // smaller integers by generating an extra extend, but larger ones would
10868     // be lossy. We also can't handle more then 4 lanes, since these intructions
10869     // only support v2i32/v4i32 types.
10870     return SDValue();
10871   }
10872 
10873   BitVector UndefElements;
10874   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10875   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10876   if (C == -1 || C == 0 || C > 32)
10877     return SDValue();
10878 
10879   SDLoc dl(N);
10880   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10881   SDValue ConvInput = Op.getOperand(0);
10882   if (IntBits < FloatBits)
10883     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10884                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10885                             ConvInput);
10886 
10887   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10888     Intrinsic::arm_neon_vcvtfxu2fp;
10889   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10890                      Op.getValueType(),
10891                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10892                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10893 }
10894 
10895 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10896 /// operand of a vector shift operation, where all the elements of the
10897 /// build_vector must have the same constant integer value.
10898 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10899   // Ignore bit_converts.
10900   while (Op.getOpcode() == ISD::BITCAST)
10901     Op = Op.getOperand(0);
10902   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10903   APInt SplatBits, SplatUndef;
10904   unsigned SplatBitSize;
10905   bool HasAnyUndefs;
10906   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10907                                       HasAnyUndefs, ElementBits) ||
10908       SplatBitSize > ElementBits)
10909     return false;
10910   Cnt = SplatBits.getSExtValue();
10911   return true;
10912 }
10913 
10914 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10915 /// operand of a vector shift left operation.  That value must be in the range:
10916 ///   0 <= Value < ElementBits for a left shift; or
10917 ///   0 <= Value <= ElementBits for a long left shift.
10918 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10919   assert(VT.isVector() && "vector shift count is not a vector type");
10920   int64_t ElementBits = VT.getScalarSizeInBits();
10921   if (! getVShiftImm(Op, ElementBits, Cnt))
10922     return false;
10923   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10924 }
10925 
10926 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10927 /// operand of a vector shift right operation.  For a shift opcode, the value
10928 /// is positive, but for an intrinsic the value count must be negative. The
10929 /// absolute value must be in the range:
10930 ///   1 <= |Value| <= ElementBits for a right shift; or
10931 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10932 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10933                          int64_t &Cnt) {
10934   assert(VT.isVector() && "vector shift count is not a vector type");
10935   int64_t ElementBits = VT.getScalarSizeInBits();
10936   if (! getVShiftImm(Op, ElementBits, Cnt))
10937     return false;
10938   if (!isIntrinsic)
10939     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10940   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10941     Cnt = -Cnt;
10942     return true;
10943   }
10944   return false;
10945 }
10946 
10947 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10948 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10949   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10950   switch (IntNo) {
10951   default:
10952     // Don't do anything for most intrinsics.
10953     break;
10954 
10955   // Vector shifts: check for immediate versions and lower them.
10956   // Note: This is done during DAG combining instead of DAG legalizing because
10957   // the build_vectors for 64-bit vector element shift counts are generally
10958   // not legal, and it is hard to see their values after they get legalized to
10959   // loads from a constant pool.
10960   case Intrinsic::arm_neon_vshifts:
10961   case Intrinsic::arm_neon_vshiftu:
10962   case Intrinsic::arm_neon_vrshifts:
10963   case Intrinsic::arm_neon_vrshiftu:
10964   case Intrinsic::arm_neon_vrshiftn:
10965   case Intrinsic::arm_neon_vqshifts:
10966   case Intrinsic::arm_neon_vqshiftu:
10967   case Intrinsic::arm_neon_vqshiftsu:
10968   case Intrinsic::arm_neon_vqshiftns:
10969   case Intrinsic::arm_neon_vqshiftnu:
10970   case Intrinsic::arm_neon_vqshiftnsu:
10971   case Intrinsic::arm_neon_vqrshiftns:
10972   case Intrinsic::arm_neon_vqrshiftnu:
10973   case Intrinsic::arm_neon_vqrshiftnsu: {
10974     EVT VT = N->getOperand(1).getValueType();
10975     int64_t Cnt;
10976     unsigned VShiftOpc = 0;
10977 
10978     switch (IntNo) {
10979     case Intrinsic::arm_neon_vshifts:
10980     case Intrinsic::arm_neon_vshiftu:
10981       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10982         VShiftOpc = ARMISD::VSHL;
10983         break;
10984       }
10985       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10986         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10987                      ARMISD::VSHRs : ARMISD::VSHRu);
10988         break;
10989       }
10990       return SDValue();
10991 
10992     case Intrinsic::arm_neon_vrshifts:
10993     case Intrinsic::arm_neon_vrshiftu:
10994       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10995         break;
10996       return SDValue();
10997 
10998     case Intrinsic::arm_neon_vqshifts:
10999     case Intrinsic::arm_neon_vqshiftu:
11000       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11001         break;
11002       return SDValue();
11003 
11004     case Intrinsic::arm_neon_vqshiftsu:
11005       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11006         break;
11007       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11008 
11009     case Intrinsic::arm_neon_vrshiftn:
11010     case Intrinsic::arm_neon_vqshiftns:
11011     case Intrinsic::arm_neon_vqshiftnu:
11012     case Intrinsic::arm_neon_vqshiftnsu:
11013     case Intrinsic::arm_neon_vqrshiftns:
11014     case Intrinsic::arm_neon_vqrshiftnu:
11015     case Intrinsic::arm_neon_vqrshiftnsu:
11016       // Narrowing shifts require an immediate right shift.
11017       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11018         break;
11019       llvm_unreachable("invalid shift count for narrowing vector shift "
11020                        "intrinsic");
11021 
11022     default:
11023       llvm_unreachable("unhandled vector shift");
11024     }
11025 
11026     switch (IntNo) {
11027     case Intrinsic::arm_neon_vshifts:
11028     case Intrinsic::arm_neon_vshiftu:
11029       // Opcode already set above.
11030       break;
11031     case Intrinsic::arm_neon_vrshifts:
11032       VShiftOpc = ARMISD::VRSHRs; break;
11033     case Intrinsic::arm_neon_vrshiftu:
11034       VShiftOpc = ARMISD::VRSHRu; break;
11035     case Intrinsic::arm_neon_vrshiftn:
11036       VShiftOpc = ARMISD::VRSHRN; break;
11037     case Intrinsic::arm_neon_vqshifts:
11038       VShiftOpc = ARMISD::VQSHLs; break;
11039     case Intrinsic::arm_neon_vqshiftu:
11040       VShiftOpc = ARMISD::VQSHLu; break;
11041     case Intrinsic::arm_neon_vqshiftsu:
11042       VShiftOpc = ARMISD::VQSHLsu; break;
11043     case Intrinsic::arm_neon_vqshiftns:
11044       VShiftOpc = ARMISD::VQSHRNs; break;
11045     case Intrinsic::arm_neon_vqshiftnu:
11046       VShiftOpc = ARMISD::VQSHRNu; break;
11047     case Intrinsic::arm_neon_vqshiftnsu:
11048       VShiftOpc = ARMISD::VQSHRNsu; break;
11049     case Intrinsic::arm_neon_vqrshiftns:
11050       VShiftOpc = ARMISD::VQRSHRNs; break;
11051     case Intrinsic::arm_neon_vqrshiftnu:
11052       VShiftOpc = ARMISD::VQRSHRNu; break;
11053     case Intrinsic::arm_neon_vqrshiftnsu:
11054       VShiftOpc = ARMISD::VQRSHRNsu; break;
11055     }
11056 
11057     SDLoc dl(N);
11058     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11059                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11060   }
11061 
11062   case Intrinsic::arm_neon_vshiftins: {
11063     EVT VT = N->getOperand(1).getValueType();
11064     int64_t Cnt;
11065     unsigned VShiftOpc = 0;
11066 
11067     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11068       VShiftOpc = ARMISD::VSLI;
11069     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11070       VShiftOpc = ARMISD::VSRI;
11071     else {
11072       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11073     }
11074 
11075     SDLoc dl(N);
11076     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11077                        N->getOperand(1), N->getOperand(2),
11078                        DAG.getConstant(Cnt, dl, MVT::i32));
11079   }
11080 
11081   case Intrinsic::arm_neon_vqrshifts:
11082   case Intrinsic::arm_neon_vqrshiftu:
11083     // No immediate versions of these to check for.
11084     break;
11085   }
11086 
11087   return SDValue();
11088 }
11089 
11090 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11091 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11092 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11093 /// vector element shift counts are generally not legal, and it is hard to see
11094 /// their values after they get legalized to loads from a constant pool.
11095 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11096                                    const ARMSubtarget *ST) {
11097   EVT VT = N->getValueType(0);
11098   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11099     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11100     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11101     SDValue N1 = N->getOperand(1);
11102     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11103       SDValue N0 = N->getOperand(0);
11104       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11105           DAG.MaskedValueIsZero(N0.getOperand(0),
11106                                 APInt::getHighBitsSet(32, 16)))
11107         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11108     }
11109   }
11110 
11111   // Nothing to be done for scalar shifts.
11112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11113   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11114     return SDValue();
11115 
11116   assert(ST->hasNEON() && "unexpected vector shift");
11117   int64_t Cnt;
11118 
11119   switch (N->getOpcode()) {
11120   default: llvm_unreachable("unexpected shift opcode");
11121 
11122   case ISD::SHL:
11123     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11124       SDLoc dl(N);
11125       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11126                          DAG.getConstant(Cnt, dl, MVT::i32));
11127     }
11128     break;
11129 
11130   case ISD::SRA:
11131   case ISD::SRL:
11132     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11133       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11134                             ARMISD::VSHRs : ARMISD::VSHRu);
11135       SDLoc dl(N);
11136       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11137                          DAG.getConstant(Cnt, dl, MVT::i32));
11138     }
11139   }
11140   return SDValue();
11141 }
11142 
11143 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11144 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11145 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11146                                     const ARMSubtarget *ST) {
11147   SDValue N0 = N->getOperand(0);
11148 
11149   // Check for sign- and zero-extensions of vector extract operations of 8-
11150   // and 16-bit vector elements.  NEON supports these directly.  They are
11151   // handled during DAG combining because type legalization will promote them
11152   // to 32-bit types and it is messy to recognize the operations after that.
11153   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11154     SDValue Vec = N0.getOperand(0);
11155     SDValue Lane = N0.getOperand(1);
11156     EVT VT = N->getValueType(0);
11157     EVT EltVT = N0.getValueType();
11158     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11159 
11160     if (VT == MVT::i32 &&
11161         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11162         TLI.isTypeLegal(Vec.getValueType()) &&
11163         isa<ConstantSDNode>(Lane)) {
11164 
11165       unsigned Opc = 0;
11166       switch (N->getOpcode()) {
11167       default: llvm_unreachable("unexpected opcode");
11168       case ISD::SIGN_EXTEND:
11169         Opc = ARMISD::VGETLANEs;
11170         break;
11171       case ISD::ZERO_EXTEND:
11172       case ISD::ANY_EXTEND:
11173         Opc = ARMISD::VGETLANEu;
11174         break;
11175       }
11176       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11177     }
11178   }
11179 
11180   return SDValue();
11181 }
11182 
11183 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
11184                              APInt &KnownOne) {
11185   if (Op.getOpcode() == ARMISD::BFI) {
11186     // Conservatively, we can recurse down the first operand
11187     // and just mask out all affected bits.
11188     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11189 
11190     // The operand to BFI is already a mask suitable for removing the bits it
11191     // sets.
11192     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
11193     const APInt &Mask = CI->getAPIntValue();
11194     KnownZero &= Mask;
11195     KnownOne &= Mask;
11196     return;
11197   }
11198   if (Op.getOpcode() == ARMISD::CMOV) {
11199     APInt KZ2(KnownZero.getBitWidth(), 0);
11200     APInt KO2(KnownOne.getBitWidth(), 0);
11201     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
11202     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
11203 
11204     KnownZero &= KZ2;
11205     KnownOne &= KO2;
11206     return;
11207   }
11208   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
11209 }
11210 
11211 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11212   // If we have a CMOV, OR and AND combination such as:
11213   //   if (x & CN)
11214   //     y |= CM;
11215   //
11216   // And:
11217   //   * CN is a single bit;
11218   //   * All bits covered by CM are known zero in y
11219   //
11220   // Then we can convert this into a sequence of BFI instructions. This will
11221   // always be a win if CM is a single bit, will always be no worse than the
11222   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11223   // three bits (due to the extra IT instruction).
11224 
11225   SDValue Op0 = CMOV->getOperand(0);
11226   SDValue Op1 = CMOV->getOperand(1);
11227   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11228   auto CC = CCNode->getAPIntValue().getLimitedValue();
11229   SDValue CmpZ = CMOV->getOperand(4);
11230 
11231   // The compare must be against zero.
11232   if (!isNullConstant(CmpZ->getOperand(1)))
11233     return SDValue();
11234 
11235   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11236   SDValue And = CmpZ->getOperand(0);
11237   if (And->getOpcode() != ISD::AND)
11238     return SDValue();
11239   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11240   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11241     return SDValue();
11242   SDValue X = And->getOperand(0);
11243 
11244   if (CC == ARMCC::EQ) {
11245     // We're performing an "equal to zero" compare. Swap the operands so we
11246     // canonicalize on a "not equal to zero" compare.
11247     std::swap(Op0, Op1);
11248   } else {
11249     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11250   }
11251 
11252   if (Op1->getOpcode() != ISD::OR)
11253     return SDValue();
11254 
11255   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11256   if (!OrC)
11257     return SDValue();
11258   SDValue Y = Op1->getOperand(0);
11259 
11260   if (Op0 != Y)
11261     return SDValue();
11262 
11263   // Now, is it profitable to continue?
11264   APInt OrCI = OrC->getAPIntValue();
11265   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11266   if (OrCI.countPopulation() > Heuristic)
11267     return SDValue();
11268 
11269   // Lastly, can we determine that the bits defined by OrCI
11270   // are zero in Y?
11271   APInt KnownZero, KnownOne;
11272   computeKnownBits(DAG, Y, KnownZero, KnownOne);
11273   if ((OrCI & KnownZero) != OrCI)
11274     return SDValue();
11275 
11276   // OK, we can do the combine.
11277   SDValue V = Y;
11278   SDLoc dl(X);
11279   EVT VT = X.getValueType();
11280   unsigned BitInX = AndC->getAPIntValue().logBase2();
11281 
11282   if (BitInX != 0) {
11283     // We must shift X first.
11284     X = DAG.getNode(ISD::SRL, dl, VT, X,
11285                     DAG.getConstant(BitInX, dl, VT));
11286   }
11287 
11288   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11289        BitInY < NumActiveBits; ++BitInY) {
11290     if (OrCI[BitInY] == 0)
11291       continue;
11292     APInt Mask(VT.getSizeInBits(), 0);
11293     Mask.setBit(BitInY);
11294     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11295                     // Confusingly, the operand is an *inverted* mask.
11296                     DAG.getConstant(~Mask, dl, VT));
11297   }
11298 
11299   return V;
11300 }
11301 
11302 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11303 SDValue
11304 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11305   SDValue Cmp = N->getOperand(4);
11306   if (Cmp.getOpcode() != ARMISD::CMPZ)
11307     // Only looking at NE cases.
11308     return SDValue();
11309 
11310   EVT VT = N->getValueType(0);
11311   SDLoc dl(N);
11312   SDValue LHS = Cmp.getOperand(0);
11313   SDValue RHS = Cmp.getOperand(1);
11314   SDValue Chain = N->getOperand(0);
11315   SDValue BB = N->getOperand(1);
11316   SDValue ARMcc = N->getOperand(2);
11317   ARMCC::CondCodes CC =
11318     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11319 
11320   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11321   // -> (brcond Chain BB CC CPSR Cmp)
11322   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11323       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11324       LHS->getOperand(0)->hasOneUse()) {
11325     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11326     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11327     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11328     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11329     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11330         (LHS01C && LHS01C->getZExtValue() == 1) &&
11331         (LHS1C && LHS1C->getZExtValue() == 1) &&
11332         (RHSC && RHSC->getZExtValue() == 0)) {
11333       return DAG.getNode(
11334           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11335           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11336     }
11337   }
11338 
11339   return SDValue();
11340 }
11341 
11342 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11343 SDValue
11344 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11345   SDValue Cmp = N->getOperand(4);
11346   if (Cmp.getOpcode() != ARMISD::CMPZ)
11347     // Only looking at EQ and NE cases.
11348     return SDValue();
11349 
11350   EVT VT = N->getValueType(0);
11351   SDLoc dl(N);
11352   SDValue LHS = Cmp.getOperand(0);
11353   SDValue RHS = Cmp.getOperand(1);
11354   SDValue FalseVal = N->getOperand(0);
11355   SDValue TrueVal = N->getOperand(1);
11356   SDValue ARMcc = N->getOperand(2);
11357   ARMCC::CondCodes CC =
11358     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11359 
11360   // BFI is only available on V6T2+.
11361   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11362     SDValue R = PerformCMOVToBFICombine(N, DAG);
11363     if (R)
11364       return R;
11365   }
11366 
11367   // Simplify
11368   //   mov     r1, r0
11369   //   cmp     r1, x
11370   //   mov     r0, y
11371   //   moveq   r0, x
11372   // to
11373   //   cmp     r0, x
11374   //   movne   r0, y
11375   //
11376   //   mov     r1, r0
11377   //   cmp     r1, x
11378   //   mov     r0, x
11379   //   movne   r0, y
11380   // to
11381   //   cmp     r0, x
11382   //   movne   r0, y
11383   /// FIXME: Turn this into a target neutral optimization?
11384   SDValue Res;
11385   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11386     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11387                       N->getOperand(3), Cmp);
11388   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11389     SDValue ARMcc;
11390     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11391     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11392                       N->getOperand(3), NewCmp);
11393   }
11394 
11395   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11396   // -> (cmov F T CC CPSR Cmp)
11397   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11398     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11399     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11400     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11401     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11402         (LHS1C && LHS1C->getZExtValue() == 1) &&
11403         (RHSC && RHSC->getZExtValue() == 0)) {
11404       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11405                          LHS->getOperand(2), LHS->getOperand(3),
11406                          LHS->getOperand(4));
11407     }
11408   }
11409 
11410   if (Res.getNode()) {
11411     APInt KnownZero, KnownOne;
11412     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11413     // Capture demanded bits information that would be otherwise lost.
11414     if (KnownZero == 0xfffffffe)
11415       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11416                         DAG.getValueType(MVT::i1));
11417     else if (KnownZero == 0xffffff00)
11418       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11419                         DAG.getValueType(MVT::i8));
11420     else if (KnownZero == 0xffff0000)
11421       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11422                         DAG.getValueType(MVT::i16));
11423   }
11424 
11425   return Res;
11426 }
11427 
11428 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11429                                              DAGCombinerInfo &DCI) const {
11430   switch (N->getOpcode()) {
11431   default: break;
11432   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
11433   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11434   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11435   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11436   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11437   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11438   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11439   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11440   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11441   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11442   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11443   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11444   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11445   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11446   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11447   case ISD::FP_TO_SINT:
11448   case ISD::FP_TO_UINT:
11449     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11450   case ISD::FDIV:
11451     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11452   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11453   case ISD::SHL:
11454   case ISD::SRA:
11455   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11456   case ISD::SIGN_EXTEND:
11457   case ISD::ZERO_EXTEND:
11458   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11459   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11460   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11461   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11462   case ARMISD::VLD2DUP:
11463   case ARMISD::VLD3DUP:
11464   case ARMISD::VLD4DUP:
11465     return PerformVLDCombine(N, DCI);
11466   case ARMISD::BUILD_VECTOR:
11467     return PerformARMBUILD_VECTORCombine(N, DCI);
11468   case ISD::INTRINSIC_VOID:
11469   case ISD::INTRINSIC_W_CHAIN:
11470     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11471     case Intrinsic::arm_neon_vld1:
11472     case Intrinsic::arm_neon_vld2:
11473     case Intrinsic::arm_neon_vld3:
11474     case Intrinsic::arm_neon_vld4:
11475     case Intrinsic::arm_neon_vld2lane:
11476     case Intrinsic::arm_neon_vld3lane:
11477     case Intrinsic::arm_neon_vld4lane:
11478     case Intrinsic::arm_neon_vst1:
11479     case Intrinsic::arm_neon_vst2:
11480     case Intrinsic::arm_neon_vst3:
11481     case Intrinsic::arm_neon_vst4:
11482     case Intrinsic::arm_neon_vst2lane:
11483     case Intrinsic::arm_neon_vst3lane:
11484     case Intrinsic::arm_neon_vst4lane:
11485       return PerformVLDCombine(N, DCI);
11486     default: break;
11487     }
11488     break;
11489   }
11490   return SDValue();
11491 }
11492 
11493 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11494                                                           EVT VT) const {
11495   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11496 }
11497 
11498 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11499                                                        unsigned,
11500                                                        unsigned,
11501                                                        bool *Fast) const {
11502   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11503   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11504 
11505   switch (VT.getSimpleVT().SimpleTy) {
11506   default:
11507     return false;
11508   case MVT::i8:
11509   case MVT::i16:
11510   case MVT::i32: {
11511     // Unaligned access can use (for example) LRDB, LRDH, LDR
11512     if (AllowsUnaligned) {
11513       if (Fast)
11514         *Fast = Subtarget->hasV7Ops();
11515       return true;
11516     }
11517     return false;
11518   }
11519   case MVT::f64:
11520   case MVT::v2f64: {
11521     // For any little-endian targets with neon, we can support unaligned ld/st
11522     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11523     // A big-endian target may also explicitly support unaligned accesses
11524     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11525       if (Fast)
11526         *Fast = true;
11527       return true;
11528     }
11529     return false;
11530   }
11531   }
11532 }
11533 
11534 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11535                        unsigned AlignCheck) {
11536   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11537           (DstAlign == 0 || DstAlign % AlignCheck == 0));
11538 }
11539 
11540 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11541                                            unsigned DstAlign, unsigned SrcAlign,
11542                                            bool IsMemset, bool ZeroMemset,
11543                                            bool MemcpyStrSrc,
11544                                            MachineFunction &MF) const {
11545   const Function *F = MF.getFunction();
11546 
11547   // See if we can use NEON instructions for this...
11548   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11549       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11550     bool Fast;
11551     if (Size >= 16 &&
11552         (memOpAlign(SrcAlign, DstAlign, 16) ||
11553          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11554       return MVT::v2f64;
11555     } else if (Size >= 8 &&
11556                (memOpAlign(SrcAlign, DstAlign, 8) ||
11557                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11558                  Fast))) {
11559       return MVT::f64;
11560     }
11561   }
11562 
11563   // Lowering to i32/i16 if the size permits.
11564   if (Size >= 4)
11565     return MVT::i32;
11566   else if (Size >= 2)
11567     return MVT::i16;
11568 
11569   // Let the target-independent logic figure it out.
11570   return MVT::Other;
11571 }
11572 
11573 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11574   if (Val.getOpcode() != ISD::LOAD)
11575     return false;
11576 
11577   EVT VT1 = Val.getValueType();
11578   if (!VT1.isSimple() || !VT1.isInteger() ||
11579       !VT2.isSimple() || !VT2.isInteger())
11580     return false;
11581 
11582   switch (VT1.getSimpleVT().SimpleTy) {
11583   default: break;
11584   case MVT::i1:
11585   case MVT::i8:
11586   case MVT::i16:
11587     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11588     return true;
11589   }
11590 
11591   return false;
11592 }
11593 
11594 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11595   EVT VT = ExtVal.getValueType();
11596 
11597   if (!isTypeLegal(VT))
11598     return false;
11599 
11600   // Don't create a loadext if we can fold the extension into a wide/long
11601   // instruction.
11602   // If there's more than one user instruction, the loadext is desirable no
11603   // matter what.  There can be two uses by the same instruction.
11604   if (ExtVal->use_empty() ||
11605       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11606     return true;
11607 
11608   SDNode *U = *ExtVal->use_begin();
11609   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11610        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11611     return false;
11612 
11613   return true;
11614 }
11615 
11616 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11617   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11618     return false;
11619 
11620   if (!isTypeLegal(EVT::getEVT(Ty1)))
11621     return false;
11622 
11623   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11624 
11625   // Assuming the caller doesn't have a zeroext or signext return parameter,
11626   // truncation all the way down to i1 is valid.
11627   return true;
11628 }
11629 
11630 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
11631                                                 const AddrMode &AM, Type *Ty,
11632                                                 unsigned AS) const {
11633   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
11634     if (Subtarget->hasFPAO())
11635       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
11636     return 0;
11637   }
11638   return -1;
11639 }
11640 
11641 
11642 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11643   if (V < 0)
11644     return false;
11645 
11646   unsigned Scale = 1;
11647   switch (VT.getSimpleVT().SimpleTy) {
11648   default: return false;
11649   case MVT::i1:
11650   case MVT::i8:
11651     // Scale == 1;
11652     break;
11653   case MVT::i16:
11654     // Scale == 2;
11655     Scale = 2;
11656     break;
11657   case MVT::i32:
11658     // Scale == 4;
11659     Scale = 4;
11660     break;
11661   }
11662 
11663   if ((V & (Scale - 1)) != 0)
11664     return false;
11665   V /= Scale;
11666   return V == (V & ((1LL << 5) - 1));
11667 }
11668 
11669 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11670                                       const ARMSubtarget *Subtarget) {
11671   bool isNeg = false;
11672   if (V < 0) {
11673     isNeg = true;
11674     V = - V;
11675   }
11676 
11677   switch (VT.getSimpleVT().SimpleTy) {
11678   default: return false;
11679   case MVT::i1:
11680   case MVT::i8:
11681   case MVT::i16:
11682   case MVT::i32:
11683     // + imm12 or - imm8
11684     if (isNeg)
11685       return V == (V & ((1LL << 8) - 1));
11686     return V == (V & ((1LL << 12) - 1));
11687   case MVT::f32:
11688   case MVT::f64:
11689     // Same as ARM mode. FIXME: NEON?
11690     if (!Subtarget->hasVFP2())
11691       return false;
11692     if ((V & 3) != 0)
11693       return false;
11694     V >>= 2;
11695     return V == (V & ((1LL << 8) - 1));
11696   }
11697 }
11698 
11699 /// isLegalAddressImmediate - Return true if the integer value can be used
11700 /// as the offset of the target addressing mode for load / store of the
11701 /// given type.
11702 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11703                                     const ARMSubtarget *Subtarget) {
11704   if (V == 0)
11705     return true;
11706 
11707   if (!VT.isSimple())
11708     return false;
11709 
11710   if (Subtarget->isThumb1Only())
11711     return isLegalT1AddressImmediate(V, VT);
11712   else if (Subtarget->isThumb2())
11713     return isLegalT2AddressImmediate(V, VT, Subtarget);
11714 
11715   // ARM mode.
11716   if (V < 0)
11717     V = - V;
11718   switch (VT.getSimpleVT().SimpleTy) {
11719   default: return false;
11720   case MVT::i1:
11721   case MVT::i8:
11722   case MVT::i32:
11723     // +- imm12
11724     return V == (V & ((1LL << 12) - 1));
11725   case MVT::i16:
11726     // +- imm8
11727     return V == (V & ((1LL << 8) - 1));
11728   case MVT::f32:
11729   case MVT::f64:
11730     if (!Subtarget->hasVFP2()) // FIXME: NEON?
11731       return false;
11732     if ((V & 3) != 0)
11733       return false;
11734     V >>= 2;
11735     return V == (V & ((1LL << 8) - 1));
11736   }
11737 }
11738 
11739 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11740                                                       EVT VT) const {
11741   int Scale = AM.Scale;
11742   if (Scale < 0)
11743     return false;
11744 
11745   switch (VT.getSimpleVT().SimpleTy) {
11746   default: return false;
11747   case MVT::i1:
11748   case MVT::i8:
11749   case MVT::i16:
11750   case MVT::i32:
11751     if (Scale == 1)
11752       return true;
11753     // r + r << imm
11754     Scale = Scale & ~1;
11755     return Scale == 2 || Scale == 4 || Scale == 8;
11756   case MVT::i64:
11757     // r + r
11758     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11759       return true;
11760     return false;
11761   case MVT::isVoid:
11762     // Note, we allow "void" uses (basically, uses that aren't loads or
11763     // stores), because arm allows folding a scale into many arithmetic
11764     // operations.  This should be made more precise and revisited later.
11765 
11766     // Allow r << imm, but the imm has to be a multiple of two.
11767     if (Scale & 1) return false;
11768     return isPowerOf2_32(Scale);
11769   }
11770 }
11771 
11772 /// isLegalAddressingMode - Return true if the addressing mode represented
11773 /// by AM is legal for this target, for a load/store of the specified type.
11774 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11775                                               const AddrMode &AM, Type *Ty,
11776                                               unsigned AS) const {
11777   EVT VT = getValueType(DL, Ty, true);
11778   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11779     return false;
11780 
11781   // Can never fold addr of global into load/store.
11782   if (AM.BaseGV)
11783     return false;
11784 
11785   switch (AM.Scale) {
11786   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11787     break;
11788   case 1:
11789     if (Subtarget->isThumb1Only())
11790       return false;
11791     LLVM_FALLTHROUGH;
11792   default:
11793     // ARM doesn't support any R+R*scale+imm addr modes.
11794     if (AM.BaseOffs)
11795       return false;
11796 
11797     if (!VT.isSimple())
11798       return false;
11799 
11800     if (Subtarget->isThumb2())
11801       return isLegalT2ScaledAddressingMode(AM, VT);
11802 
11803     int Scale = AM.Scale;
11804     switch (VT.getSimpleVT().SimpleTy) {
11805     default: return false;
11806     case MVT::i1:
11807     case MVT::i8:
11808     case MVT::i32:
11809       if (Scale < 0) Scale = -Scale;
11810       if (Scale == 1)
11811         return true;
11812       // r + r << imm
11813       return isPowerOf2_32(Scale & ~1);
11814     case MVT::i16:
11815     case MVT::i64:
11816       // r + r
11817       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11818         return true;
11819       return false;
11820 
11821     case MVT::isVoid:
11822       // Note, we allow "void" uses (basically, uses that aren't loads or
11823       // stores), because arm allows folding a scale into many arithmetic
11824       // operations.  This should be made more precise and revisited later.
11825 
11826       // Allow r << imm, but the imm has to be a multiple of two.
11827       if (Scale & 1) return false;
11828       return isPowerOf2_32(Scale);
11829     }
11830   }
11831   return true;
11832 }
11833 
11834 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11835 /// icmp immediate, that is the target has icmp instructions which can compare
11836 /// a register against the immediate without having to materialize the
11837 /// immediate into a register.
11838 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11839   // Thumb2 and ARM modes can use cmn for negative immediates.
11840   if (!Subtarget->isThumb())
11841     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11842   if (Subtarget->isThumb2())
11843     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11844   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11845   return Imm >= 0 && Imm <= 255;
11846 }
11847 
11848 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11849 /// *or sub* immediate, that is the target has add or sub instructions which can
11850 /// add a register with the immediate without having to materialize the
11851 /// immediate into a register.
11852 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11853   // Same encoding for add/sub, just flip the sign.
11854   int64_t AbsImm = std::abs(Imm);
11855   if (!Subtarget->isThumb())
11856     return ARM_AM::getSOImmVal(AbsImm) != -1;
11857   if (Subtarget->isThumb2())
11858     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11859   // Thumb1 only has 8-bit unsigned immediate.
11860   return AbsImm >= 0 && AbsImm <= 255;
11861 }
11862 
11863 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11864                                       bool isSEXTLoad, SDValue &Base,
11865                                       SDValue &Offset, bool &isInc,
11866                                       SelectionDAG &DAG) {
11867   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11868     return false;
11869 
11870   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11871     // AddressingMode 3
11872     Base = Ptr->getOperand(0);
11873     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11874       int RHSC = (int)RHS->getZExtValue();
11875       if (RHSC < 0 && RHSC > -256) {
11876         assert(Ptr->getOpcode() == ISD::ADD);
11877         isInc = false;
11878         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11879         return true;
11880       }
11881     }
11882     isInc = (Ptr->getOpcode() == ISD::ADD);
11883     Offset = Ptr->getOperand(1);
11884     return true;
11885   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11886     // AddressingMode 2
11887     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11888       int RHSC = (int)RHS->getZExtValue();
11889       if (RHSC < 0 && RHSC > -0x1000) {
11890         assert(Ptr->getOpcode() == ISD::ADD);
11891         isInc = false;
11892         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11893         Base = Ptr->getOperand(0);
11894         return true;
11895       }
11896     }
11897 
11898     if (Ptr->getOpcode() == ISD::ADD) {
11899       isInc = true;
11900       ARM_AM::ShiftOpc ShOpcVal=
11901         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11902       if (ShOpcVal != ARM_AM::no_shift) {
11903         Base = Ptr->getOperand(1);
11904         Offset = Ptr->getOperand(0);
11905       } else {
11906         Base = Ptr->getOperand(0);
11907         Offset = Ptr->getOperand(1);
11908       }
11909       return true;
11910     }
11911 
11912     isInc = (Ptr->getOpcode() == ISD::ADD);
11913     Base = Ptr->getOperand(0);
11914     Offset = Ptr->getOperand(1);
11915     return true;
11916   }
11917 
11918   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11919   return false;
11920 }
11921 
11922 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11923                                      bool isSEXTLoad, SDValue &Base,
11924                                      SDValue &Offset, bool &isInc,
11925                                      SelectionDAG &DAG) {
11926   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11927     return false;
11928 
11929   Base = Ptr->getOperand(0);
11930   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11931     int RHSC = (int)RHS->getZExtValue();
11932     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11933       assert(Ptr->getOpcode() == ISD::ADD);
11934       isInc = false;
11935       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11936       return true;
11937     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11938       isInc = Ptr->getOpcode() == ISD::ADD;
11939       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11940       return true;
11941     }
11942   }
11943 
11944   return false;
11945 }
11946 
11947 /// getPreIndexedAddressParts - returns true by value, base pointer and
11948 /// offset pointer and addressing mode by reference if the node's address
11949 /// can be legally represented as pre-indexed load / store address.
11950 bool
11951 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11952                                              SDValue &Offset,
11953                                              ISD::MemIndexedMode &AM,
11954                                              SelectionDAG &DAG) const {
11955   if (Subtarget->isThumb1Only())
11956     return false;
11957 
11958   EVT VT;
11959   SDValue Ptr;
11960   bool isSEXTLoad = false;
11961   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11962     Ptr = LD->getBasePtr();
11963     VT  = LD->getMemoryVT();
11964     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11965   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11966     Ptr = ST->getBasePtr();
11967     VT  = ST->getMemoryVT();
11968   } else
11969     return false;
11970 
11971   bool isInc;
11972   bool isLegal = false;
11973   if (Subtarget->isThumb2())
11974     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11975                                        Offset, isInc, DAG);
11976   else
11977     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11978                                         Offset, isInc, DAG);
11979   if (!isLegal)
11980     return false;
11981 
11982   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11983   return true;
11984 }
11985 
11986 /// getPostIndexedAddressParts - returns true by value, base pointer and
11987 /// offset pointer and addressing mode by reference if this node can be
11988 /// combined with a load / store to form a post-indexed load / store.
11989 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11990                                                    SDValue &Base,
11991                                                    SDValue &Offset,
11992                                                    ISD::MemIndexedMode &AM,
11993                                                    SelectionDAG &DAG) const {
11994   EVT VT;
11995   SDValue Ptr;
11996   bool isSEXTLoad = false, isNonExt;
11997   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11998     VT  = LD->getMemoryVT();
11999     Ptr = LD->getBasePtr();
12000     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12001     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12002   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12003     VT  = ST->getMemoryVT();
12004     Ptr = ST->getBasePtr();
12005     isNonExt = !ST->isTruncatingStore();
12006   } else
12007     return false;
12008 
12009   if (Subtarget->isThumb1Only()) {
12010     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12011     // must be non-extending/truncating, i32, with an offset of 4.
12012     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12013     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12014       return false;
12015     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12016     if (!RHS || RHS->getZExtValue() != 4)
12017       return false;
12018 
12019     Offset = Op->getOperand(1);
12020     Base = Op->getOperand(0);
12021     AM = ISD::POST_INC;
12022     return true;
12023   }
12024 
12025   bool isInc;
12026   bool isLegal = false;
12027   if (Subtarget->isThumb2())
12028     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12029                                        isInc, DAG);
12030   else
12031     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12032                                         isInc, DAG);
12033   if (!isLegal)
12034     return false;
12035 
12036   if (Ptr != Base) {
12037     // Swap base ptr and offset to catch more post-index load / store when
12038     // it's legal. In Thumb2 mode, offset must be an immediate.
12039     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12040         !Subtarget->isThumb2())
12041       std::swap(Base, Offset);
12042 
12043     // Post-indexed load / store update the base pointer.
12044     if (Ptr != Base)
12045       return false;
12046   }
12047 
12048   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12049   return true;
12050 }
12051 
12052 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12053                                                       APInt &KnownZero,
12054                                                       APInt &KnownOne,
12055                                                       const SelectionDAG &DAG,
12056                                                       unsigned Depth) const {
12057   unsigned BitWidth = KnownOne.getBitWidth();
12058   KnownZero = KnownOne = APInt(BitWidth, 0);
12059   switch (Op.getOpcode()) {
12060   default: break;
12061   case ARMISD::ADDC:
12062   case ARMISD::ADDE:
12063   case ARMISD::SUBC:
12064   case ARMISD::SUBE:
12065     // These nodes' second result is a boolean
12066     if (Op.getResNo() == 0)
12067       break;
12068     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12069     break;
12070   case ARMISD::CMOV: {
12071     // Bits are known zero/one if known on the LHS and RHS.
12072     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12073     if (KnownZero == 0 && KnownOne == 0) return;
12074 
12075     APInt KnownZeroRHS, KnownOneRHS;
12076     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12077     KnownZero &= KnownZeroRHS;
12078     KnownOne  &= KnownOneRHS;
12079     return;
12080   }
12081   case ISD::INTRINSIC_W_CHAIN: {
12082     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12083     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12084     switch (IntID) {
12085     default: return;
12086     case Intrinsic::arm_ldaex:
12087     case Intrinsic::arm_ldrex: {
12088       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12089       unsigned MemBits = VT.getScalarSizeInBits();
12090       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12091       return;
12092     }
12093     }
12094   }
12095   }
12096 }
12097 
12098 //===----------------------------------------------------------------------===//
12099 //                           ARM Inline Assembly Support
12100 //===----------------------------------------------------------------------===//
12101 
12102 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12103   // Looking for "rev" which is V6+.
12104   if (!Subtarget->hasV6Ops())
12105     return false;
12106 
12107   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12108   std::string AsmStr = IA->getAsmString();
12109   SmallVector<StringRef, 4> AsmPieces;
12110   SplitString(AsmStr, AsmPieces, ";\n");
12111 
12112   switch (AsmPieces.size()) {
12113   default: return false;
12114   case 1:
12115     AsmStr = AsmPieces[0];
12116     AsmPieces.clear();
12117     SplitString(AsmStr, AsmPieces, " \t,");
12118 
12119     // rev $0, $1
12120     if (AsmPieces.size() == 3 &&
12121         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12122         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12123       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12124       if (Ty && Ty->getBitWidth() == 32)
12125         return IntrinsicLowering::LowerToByteSwap(CI);
12126     }
12127     break;
12128   }
12129 
12130   return false;
12131 }
12132 
12133 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12134   // At this point, we have to lower this constraint to something else, so we
12135   // lower it to an "r" or "w". However, by doing this we will force the result
12136   // to be in register, while the X constraint is much more permissive.
12137   //
12138   // Although we are correct (we are free to emit anything, without
12139   // constraints), we might break use cases that would expect us to be more
12140   // efficient and emit something else.
12141   if (!Subtarget->hasVFP2())
12142     return "r";
12143   if (ConstraintVT.isFloatingPoint())
12144     return "w";
12145   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12146      (ConstraintVT.getSizeInBits() == 64 ||
12147       ConstraintVT.getSizeInBits() == 128))
12148     return "w";
12149 
12150   return "r";
12151 }
12152 
12153 /// getConstraintType - Given a constraint letter, return the type of
12154 /// constraint it is for this target.
12155 ARMTargetLowering::ConstraintType
12156 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12157   if (Constraint.size() == 1) {
12158     switch (Constraint[0]) {
12159     default:  break;
12160     case 'l': return C_RegisterClass;
12161     case 'w': return C_RegisterClass;
12162     case 'h': return C_RegisterClass;
12163     case 'x': return C_RegisterClass;
12164     case 't': return C_RegisterClass;
12165     case 'j': return C_Other; // Constant for movw.
12166       // An address with a single base register. Due to the way we
12167       // currently handle addresses it is the same as an 'r' memory constraint.
12168     case 'Q': return C_Memory;
12169     }
12170   } else if (Constraint.size() == 2) {
12171     switch (Constraint[0]) {
12172     default: break;
12173     // All 'U+' constraints are addresses.
12174     case 'U': return C_Memory;
12175     }
12176   }
12177   return TargetLowering::getConstraintType(Constraint);
12178 }
12179 
12180 /// Examine constraint type and operand type and determine a weight value.
12181 /// This object must already have been set up with the operand type
12182 /// and the current alternative constraint selected.
12183 TargetLowering::ConstraintWeight
12184 ARMTargetLowering::getSingleConstraintMatchWeight(
12185     AsmOperandInfo &info, const char *constraint) const {
12186   ConstraintWeight weight = CW_Invalid;
12187   Value *CallOperandVal = info.CallOperandVal;
12188     // If we don't have a value, we can't do a match,
12189     // but allow it at the lowest weight.
12190   if (!CallOperandVal)
12191     return CW_Default;
12192   Type *type = CallOperandVal->getType();
12193   // Look at the constraint type.
12194   switch (*constraint) {
12195   default:
12196     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12197     break;
12198   case 'l':
12199     if (type->isIntegerTy()) {
12200       if (Subtarget->isThumb())
12201         weight = CW_SpecificReg;
12202       else
12203         weight = CW_Register;
12204     }
12205     break;
12206   case 'w':
12207     if (type->isFloatingPointTy())
12208       weight = CW_Register;
12209     break;
12210   }
12211   return weight;
12212 }
12213 
12214 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12215 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12216     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12217   if (Constraint.size() == 1) {
12218     // GCC ARM Constraint Letters
12219     switch (Constraint[0]) {
12220     case 'l': // Low regs or general regs.
12221       if (Subtarget->isThumb())
12222         return RCPair(0U, &ARM::tGPRRegClass);
12223       return RCPair(0U, &ARM::GPRRegClass);
12224     case 'h': // High regs or no regs.
12225       if (Subtarget->isThumb())
12226         return RCPair(0U, &ARM::hGPRRegClass);
12227       break;
12228     case 'r':
12229       if (Subtarget->isThumb1Only())
12230         return RCPair(0U, &ARM::tGPRRegClass);
12231       return RCPair(0U, &ARM::GPRRegClass);
12232     case 'w':
12233       if (VT == MVT::Other)
12234         break;
12235       if (VT == MVT::f32)
12236         return RCPair(0U, &ARM::SPRRegClass);
12237       if (VT.getSizeInBits() == 64)
12238         return RCPair(0U, &ARM::DPRRegClass);
12239       if (VT.getSizeInBits() == 128)
12240         return RCPair(0U, &ARM::QPRRegClass);
12241       break;
12242     case 'x':
12243       if (VT == MVT::Other)
12244         break;
12245       if (VT == MVT::f32)
12246         return RCPair(0U, &ARM::SPR_8RegClass);
12247       if (VT.getSizeInBits() == 64)
12248         return RCPair(0U, &ARM::DPR_8RegClass);
12249       if (VT.getSizeInBits() == 128)
12250         return RCPair(0U, &ARM::QPR_8RegClass);
12251       break;
12252     case 't':
12253       if (VT == MVT::f32)
12254         return RCPair(0U, &ARM::SPRRegClass);
12255       break;
12256     }
12257   }
12258   if (StringRef("{cc}").equals_lower(Constraint))
12259     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12260 
12261   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12262 }
12263 
12264 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12265 /// vector.  If it is invalid, don't add anything to Ops.
12266 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12267                                                      std::string &Constraint,
12268                                                      std::vector<SDValue>&Ops,
12269                                                      SelectionDAG &DAG) const {
12270   SDValue Result;
12271 
12272   // Currently only support length 1 constraints.
12273   if (Constraint.length() != 1) return;
12274 
12275   char ConstraintLetter = Constraint[0];
12276   switch (ConstraintLetter) {
12277   default: break;
12278   case 'j':
12279   case 'I': case 'J': case 'K': case 'L':
12280   case 'M': case 'N': case 'O':
12281     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12282     if (!C)
12283       return;
12284 
12285     int64_t CVal64 = C->getSExtValue();
12286     int CVal = (int) CVal64;
12287     // None of these constraints allow values larger than 32 bits.  Check
12288     // that the value fits in an int.
12289     if (CVal != CVal64)
12290       return;
12291 
12292     switch (ConstraintLetter) {
12293       case 'j':
12294         // Constant suitable for movw, must be between 0 and
12295         // 65535.
12296         if (Subtarget->hasV6T2Ops())
12297           if (CVal >= 0 && CVal <= 65535)
12298             break;
12299         return;
12300       case 'I':
12301         if (Subtarget->isThumb1Only()) {
12302           // This must be a constant between 0 and 255, for ADD
12303           // immediates.
12304           if (CVal >= 0 && CVal <= 255)
12305             break;
12306         } else if (Subtarget->isThumb2()) {
12307           // A constant that can be used as an immediate value in a
12308           // data-processing instruction.
12309           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12310             break;
12311         } else {
12312           // A constant that can be used as an immediate value in a
12313           // data-processing instruction.
12314           if (ARM_AM::getSOImmVal(CVal) != -1)
12315             break;
12316         }
12317         return;
12318 
12319       case 'J':
12320         if (Subtarget->isThumb1Only()) {
12321           // This must be a constant between -255 and -1, for negated ADD
12322           // immediates. This can be used in GCC with an "n" modifier that
12323           // prints the negated value, for use with SUB instructions. It is
12324           // not useful otherwise but is implemented for compatibility.
12325           if (CVal >= -255 && CVal <= -1)
12326             break;
12327         } else {
12328           // This must be a constant between -4095 and 4095. It is not clear
12329           // what this constraint is intended for. Implemented for
12330           // compatibility with GCC.
12331           if (CVal >= -4095 && CVal <= 4095)
12332             break;
12333         }
12334         return;
12335 
12336       case 'K':
12337         if (Subtarget->isThumb1Only()) {
12338           // A 32-bit value where only one byte has a nonzero value. Exclude
12339           // zero to match GCC. This constraint is used by GCC internally for
12340           // constants that can be loaded with a move/shift combination.
12341           // It is not useful otherwise but is implemented for compatibility.
12342           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12343             break;
12344         } else if (Subtarget->isThumb2()) {
12345           // A constant whose bitwise inverse can be used as an immediate
12346           // value in a data-processing instruction. This can be used in GCC
12347           // with a "B" modifier that prints the inverted value, for use with
12348           // BIC and MVN instructions. It is not useful otherwise but is
12349           // implemented for compatibility.
12350           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12351             break;
12352         } else {
12353           // A constant whose bitwise inverse can be used as an immediate
12354           // value in a data-processing instruction. This can be used in GCC
12355           // with a "B" modifier that prints the inverted value, for use with
12356           // BIC and MVN instructions. It is not useful otherwise but is
12357           // implemented for compatibility.
12358           if (ARM_AM::getSOImmVal(~CVal) != -1)
12359             break;
12360         }
12361         return;
12362 
12363       case 'L':
12364         if (Subtarget->isThumb1Only()) {
12365           // This must be a constant between -7 and 7,
12366           // for 3-operand ADD/SUB immediate instructions.
12367           if (CVal >= -7 && CVal < 7)
12368             break;
12369         } else if (Subtarget->isThumb2()) {
12370           // A constant whose negation can be used as an immediate value in a
12371           // data-processing instruction. This can be used in GCC with an "n"
12372           // modifier that prints the negated value, for use with SUB
12373           // instructions. It is not useful otherwise but is implemented for
12374           // compatibility.
12375           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12376             break;
12377         } else {
12378           // A constant whose negation can be used as an immediate value in a
12379           // data-processing instruction. This can be used in GCC with an "n"
12380           // modifier that prints the negated value, for use with SUB
12381           // instructions. It is not useful otherwise but is implemented for
12382           // compatibility.
12383           if (ARM_AM::getSOImmVal(-CVal) != -1)
12384             break;
12385         }
12386         return;
12387 
12388       case 'M':
12389         if (Subtarget->isThumb1Only()) {
12390           // This must be a multiple of 4 between 0 and 1020, for
12391           // ADD sp + immediate.
12392           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12393             break;
12394         } else {
12395           // A power of two or a constant between 0 and 32.  This is used in
12396           // GCC for the shift amount on shifted register operands, but it is
12397           // useful in general for any shift amounts.
12398           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12399             break;
12400         }
12401         return;
12402 
12403       case 'N':
12404         if (Subtarget->isThumb()) {  // FIXME thumb2
12405           // This must be a constant between 0 and 31, for shift amounts.
12406           if (CVal >= 0 && CVal <= 31)
12407             break;
12408         }
12409         return;
12410 
12411       case 'O':
12412         if (Subtarget->isThumb()) {  // FIXME thumb2
12413           // This must be a multiple of 4 between -508 and 508, for
12414           // ADD/SUB sp = sp + immediate.
12415           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12416             break;
12417         }
12418         return;
12419     }
12420     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12421     break;
12422   }
12423 
12424   if (Result.getNode()) {
12425     Ops.push_back(Result);
12426     return;
12427   }
12428   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12429 }
12430 
12431 static RTLIB::Libcall getDivRemLibcall(
12432     const SDNode *N, MVT::SimpleValueType SVT) {
12433   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12434           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12435          "Unhandled Opcode in getDivRemLibcall");
12436   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12437                   N->getOpcode() == ISD::SREM;
12438   RTLIB::Libcall LC;
12439   switch (SVT) {
12440   default: llvm_unreachable("Unexpected request for libcall!");
12441   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12442   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12443   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12444   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12445   }
12446   return LC;
12447 }
12448 
12449 static TargetLowering::ArgListTy getDivRemArgList(
12450     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
12451   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12452           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12453          "Unhandled Opcode in getDivRemArgList");
12454   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12455                   N->getOpcode() == ISD::SREM;
12456   TargetLowering::ArgListTy Args;
12457   TargetLowering::ArgListEntry Entry;
12458   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12459     EVT ArgVT = N->getOperand(i).getValueType();
12460     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12461     Entry.Node = N->getOperand(i);
12462     Entry.Ty = ArgTy;
12463     Entry.isSExt = isSigned;
12464     Entry.isZExt = !isSigned;
12465     Args.push_back(Entry);
12466   }
12467   if (Subtarget->isTargetWindows() && Args.size() >= 2)
12468     std::swap(Args[0], Args[1]);
12469   return Args;
12470 }
12471 
12472 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12473   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12474           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
12475           Subtarget->isTargetWindows()) &&
12476          "Register-based DivRem lowering only");
12477   unsigned Opcode = Op->getOpcode();
12478   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12479          "Invalid opcode for Div/Rem lowering");
12480   bool isSigned = (Opcode == ISD::SDIVREM);
12481   EVT VT = Op->getValueType(0);
12482   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12483   SDLoc dl(Op);
12484 
12485   // If the target has hardware divide, use divide + multiply + subtract:
12486   //     div = a / b
12487   //     rem = a - b * div
12488   //     return {div, rem}
12489   // This should be lowered into UDIV/SDIV + MLS later on.
12490   if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() &&
12491       Op->getSimpleValueType(0) == MVT::i32) {
12492     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
12493     const SDValue Dividend = Op->getOperand(0);
12494     const SDValue Divisor = Op->getOperand(1);
12495     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
12496     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
12497     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
12498 
12499     SDValue Values[2] = {Div, Rem};
12500     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
12501   }
12502 
12503   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12504                                        VT.getSimpleVT().SimpleTy);
12505   SDValue InChain = DAG.getEntryNode();
12506 
12507   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12508                                                     DAG.getContext(),
12509                                                     Subtarget);
12510 
12511   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12512                                          getPointerTy(DAG.getDataLayout()));
12513 
12514   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12515 
12516   if (Subtarget->isTargetWindows())
12517     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
12518 
12519   TargetLowering::CallLoweringInfo CLI(DAG);
12520   CLI.setDebugLoc(dl).setChain(InChain)
12521     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12522     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12523 
12524   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12525   return CallInfo.first;
12526 }
12527 
12528 // Lowers REM using divmod helpers
12529 // see RTABI section 4.2/4.3
12530 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12531   // Build return types (div and rem)
12532   std::vector<Type*> RetTyParams;
12533   Type *RetTyElement;
12534 
12535   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12536   default: llvm_unreachable("Unexpected request for libcall!");
12537   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
12538   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12539   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12540   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12541   }
12542 
12543   RetTyParams.push_back(RetTyElement);
12544   RetTyParams.push_back(RetTyElement);
12545   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12546   Type *RetTy = StructType::get(*DAG.getContext(), ret);
12547 
12548   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12549                                                              SimpleTy);
12550   SDValue InChain = DAG.getEntryNode();
12551   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
12552                                                     Subtarget);
12553   bool isSigned = N->getOpcode() == ISD::SREM;
12554   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12555                                          getPointerTy(DAG.getDataLayout()));
12556 
12557   if (Subtarget->isTargetWindows())
12558     InChain = WinDBZCheckDenominator(DAG, N, InChain);
12559 
12560   // Lower call
12561   CallLoweringInfo CLI(DAG);
12562   CLI.setChain(InChain)
12563      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12564      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12565   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12566 
12567   // Return second (rem) result operand (first contains div)
12568   SDNode *ResNode = CallResult.first.getNode();
12569   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12570   return ResNode->getOperand(1);
12571 }
12572 
12573 SDValue
12574 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12575   assert(Subtarget->isTargetWindows() && "unsupported target platform");
12576   SDLoc DL(Op);
12577 
12578   // Get the inputs.
12579   SDValue Chain = Op.getOperand(0);
12580   SDValue Size  = Op.getOperand(1);
12581 
12582   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12583                               DAG.getConstant(2, DL, MVT::i32));
12584 
12585   SDValue Flag;
12586   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12587   Flag = Chain.getValue(1);
12588 
12589   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12590   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12591 
12592   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12593   Chain = NewSP.getValue(1);
12594 
12595   SDValue Ops[2] = { NewSP, Chain };
12596   return DAG.getMergeValues(Ops, DL);
12597 }
12598 
12599 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12600   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12601          "Unexpected type for custom-lowering FP_EXTEND");
12602 
12603   RTLIB::Libcall LC;
12604   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12605 
12606   SDValue SrcVal = Op.getOperand(0);
12607   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12608                      SDLoc(Op)).first;
12609 }
12610 
12611 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12612   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12613          Subtarget->isFPOnlySP() &&
12614          "Unexpected type for custom-lowering FP_ROUND");
12615 
12616   RTLIB::Libcall LC;
12617   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12618 
12619   SDValue SrcVal = Op.getOperand(0);
12620   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12621                      SDLoc(Op)).first;
12622 }
12623 
12624 bool
12625 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12626   // The ARM target isn't yet aware of offsets.
12627   return false;
12628 }
12629 
12630 bool ARM::isBitFieldInvertedMask(unsigned v) {
12631   if (v == 0xffffffff)
12632     return false;
12633 
12634   // there can be 1's on either or both "outsides", all the "inside"
12635   // bits must be 0's
12636   return isShiftedMask_32(~v);
12637 }
12638 
12639 /// isFPImmLegal - Returns true if the target can instruction select the
12640 /// specified FP immediate natively. If false, the legalizer will
12641 /// materialize the FP immediate as a load from a constant pool.
12642 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12643   if (!Subtarget->hasVFP3())
12644     return false;
12645   if (VT == MVT::f32)
12646     return ARM_AM::getFP32Imm(Imm) != -1;
12647   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12648     return ARM_AM::getFP64Imm(Imm) != -1;
12649   return false;
12650 }
12651 
12652 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12653 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
12654 /// specified in the intrinsic calls.
12655 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12656                                            const CallInst &I,
12657                                            unsigned Intrinsic) const {
12658   switch (Intrinsic) {
12659   case Intrinsic::arm_neon_vld1:
12660   case Intrinsic::arm_neon_vld2:
12661   case Intrinsic::arm_neon_vld3:
12662   case Intrinsic::arm_neon_vld4:
12663   case Intrinsic::arm_neon_vld2lane:
12664   case Intrinsic::arm_neon_vld3lane:
12665   case Intrinsic::arm_neon_vld4lane: {
12666     Info.opc = ISD::INTRINSIC_W_CHAIN;
12667     // Conservatively set memVT to the entire set of vectors loaded.
12668     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12669     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12670     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12671     Info.ptrVal = I.getArgOperand(0);
12672     Info.offset = 0;
12673     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12674     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12675     Info.vol = false; // volatile loads with NEON intrinsics not supported
12676     Info.readMem = true;
12677     Info.writeMem = false;
12678     return true;
12679   }
12680   case Intrinsic::arm_neon_vst1:
12681   case Intrinsic::arm_neon_vst2:
12682   case Intrinsic::arm_neon_vst3:
12683   case Intrinsic::arm_neon_vst4:
12684   case Intrinsic::arm_neon_vst2lane:
12685   case Intrinsic::arm_neon_vst3lane:
12686   case Intrinsic::arm_neon_vst4lane: {
12687     Info.opc = ISD::INTRINSIC_VOID;
12688     // Conservatively set memVT to the entire set of vectors stored.
12689     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12690     unsigned NumElts = 0;
12691     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12692       Type *ArgTy = I.getArgOperand(ArgI)->getType();
12693       if (!ArgTy->isVectorTy())
12694         break;
12695       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12696     }
12697     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12698     Info.ptrVal = I.getArgOperand(0);
12699     Info.offset = 0;
12700     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12701     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12702     Info.vol = false; // volatile stores with NEON intrinsics not supported
12703     Info.readMem = false;
12704     Info.writeMem = true;
12705     return true;
12706   }
12707   case Intrinsic::arm_ldaex:
12708   case Intrinsic::arm_ldrex: {
12709     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12710     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12711     Info.opc = ISD::INTRINSIC_W_CHAIN;
12712     Info.memVT = MVT::getVT(PtrTy->getElementType());
12713     Info.ptrVal = I.getArgOperand(0);
12714     Info.offset = 0;
12715     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12716     Info.vol = true;
12717     Info.readMem = true;
12718     Info.writeMem = false;
12719     return true;
12720   }
12721   case Intrinsic::arm_stlex:
12722   case Intrinsic::arm_strex: {
12723     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12724     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12725     Info.opc = ISD::INTRINSIC_W_CHAIN;
12726     Info.memVT = MVT::getVT(PtrTy->getElementType());
12727     Info.ptrVal = I.getArgOperand(1);
12728     Info.offset = 0;
12729     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12730     Info.vol = true;
12731     Info.readMem = false;
12732     Info.writeMem = true;
12733     return true;
12734   }
12735   case Intrinsic::arm_stlexd:
12736   case Intrinsic::arm_strexd: {
12737     Info.opc = ISD::INTRINSIC_W_CHAIN;
12738     Info.memVT = MVT::i64;
12739     Info.ptrVal = I.getArgOperand(2);
12740     Info.offset = 0;
12741     Info.align = 8;
12742     Info.vol = true;
12743     Info.readMem = false;
12744     Info.writeMem = true;
12745     return true;
12746   }
12747   case Intrinsic::arm_ldaexd:
12748   case Intrinsic::arm_ldrexd: {
12749     Info.opc = ISD::INTRINSIC_W_CHAIN;
12750     Info.memVT = MVT::i64;
12751     Info.ptrVal = I.getArgOperand(0);
12752     Info.offset = 0;
12753     Info.align = 8;
12754     Info.vol = true;
12755     Info.readMem = true;
12756     Info.writeMem = false;
12757     return true;
12758   }
12759   default:
12760     break;
12761   }
12762 
12763   return false;
12764 }
12765 
12766 /// \brief Returns true if it is beneficial to convert a load of a constant
12767 /// to just the constant itself.
12768 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12769                                                           Type *Ty) const {
12770   assert(Ty->isIntegerTy());
12771 
12772   unsigned Bits = Ty->getPrimitiveSizeInBits();
12773   if (Bits == 0 || Bits > 32)
12774     return false;
12775   return true;
12776 }
12777 
12778 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
12779                                         ARM_MB::MemBOpt Domain) const {
12780   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12781 
12782   // First, if the target has no DMB, see what fallback we can use.
12783   if (!Subtarget->hasDataBarrier()) {
12784     // Some ARMv6 cpus can support data barriers with an mcr instruction.
12785     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
12786     // here.
12787     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
12788       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
12789       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
12790                         Builder.getInt32(0), Builder.getInt32(7),
12791                         Builder.getInt32(10), Builder.getInt32(5)};
12792       return Builder.CreateCall(MCR, args);
12793     } else {
12794       // Instead of using barriers, atomic accesses on these subtargets use
12795       // libcalls.
12796       llvm_unreachable("makeDMB on a target so old that it has no barriers");
12797     }
12798   } else {
12799     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
12800     // Only a full system barrier exists in the M-class architectures.
12801     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
12802     Constant *CDomain = Builder.getInt32(Domain);
12803     return Builder.CreateCall(DMB, CDomain);
12804   }
12805 }
12806 
12807 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
12808 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
12809                                          AtomicOrdering Ord, bool IsStore,
12810                                          bool IsLoad) const {
12811   switch (Ord) {
12812   case AtomicOrdering::NotAtomic:
12813   case AtomicOrdering::Unordered:
12814     llvm_unreachable("Invalid fence: unordered/non-atomic");
12815   case AtomicOrdering::Monotonic:
12816   case AtomicOrdering::Acquire:
12817     return nullptr; // Nothing to do
12818   case AtomicOrdering::SequentiallyConsistent:
12819     if (!IsStore)
12820       return nullptr; // Nothing to do
12821     /*FALLTHROUGH*/
12822   case AtomicOrdering::Release:
12823   case AtomicOrdering::AcquireRelease:
12824     if (Subtarget->preferISHSTBarriers())
12825       return makeDMB(Builder, ARM_MB::ISHST);
12826     // FIXME: add a comment with a link to documentation justifying this.
12827     else
12828       return makeDMB(Builder, ARM_MB::ISH);
12829   }
12830   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12831 }
12832 
12833 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12834                                           AtomicOrdering Ord, bool IsStore,
12835                                           bool IsLoad) const {
12836   switch (Ord) {
12837   case AtomicOrdering::NotAtomic:
12838   case AtomicOrdering::Unordered:
12839     llvm_unreachable("Invalid fence: unordered/not-atomic");
12840   case AtomicOrdering::Monotonic:
12841   case AtomicOrdering::Release:
12842     return nullptr; // Nothing to do
12843   case AtomicOrdering::Acquire:
12844   case AtomicOrdering::AcquireRelease:
12845   case AtomicOrdering::SequentiallyConsistent:
12846     return makeDMB(Builder, ARM_MB::ISH);
12847   }
12848   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12849 }
12850 
12851 // Loads and stores less than 64-bits are already atomic; ones above that
12852 // are doomed anyway, so defer to the default libcall and blame the OS when
12853 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12854 // anything for those.
12855 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12856   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12857   return (Size == 64) && !Subtarget->isMClass();
12858 }
12859 
12860 // Loads and stores less than 64-bits are already atomic; ones above that
12861 // are doomed anyway, so defer to the default libcall and blame the OS when
12862 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12863 // anything for those.
12864 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12865 // guarantee, see DDI0406C ARM architecture reference manual,
12866 // sections A8.8.72-74 LDRD)
12867 TargetLowering::AtomicExpansionKind
12868 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12869   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12870   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12871                                                   : AtomicExpansionKind::None;
12872 }
12873 
12874 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12875 // and up to 64 bits on the non-M profiles
12876 TargetLowering::AtomicExpansionKind
12877 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12878   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12879   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12880              ? AtomicExpansionKind::LLSC
12881              : AtomicExpansionKind::None;
12882 }
12883 
12884 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12885     AtomicCmpXchgInst *AI) const {
12886   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12887   // implement cmpxchg without spilling. If the address being exchanged is also
12888   // on the stack and close enough to the spill slot, this can lead to a
12889   // situation where the monitor always gets cleared and the atomic operation
12890   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12891   return getTargetMachine().getOptLevel() != 0;
12892 }
12893 
12894 bool ARMTargetLowering::shouldInsertFencesForAtomic(
12895     const Instruction *I) const {
12896   return InsertFencesForAtomic;
12897 }
12898 
12899 // This has so far only been implemented for MachO.
12900 bool ARMTargetLowering::useLoadStackGuardNode() const {
12901   return Subtarget->isTargetMachO();
12902 }
12903 
12904 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12905                                                   unsigned &Cost) const {
12906   // If we do not have NEON, vector types are not natively supported.
12907   if (!Subtarget->hasNEON())
12908     return false;
12909 
12910   // Floating point values and vector values map to the same register file.
12911   // Therefore, although we could do a store extract of a vector type, this is
12912   // better to leave at float as we have more freedom in the addressing mode for
12913   // those.
12914   if (VectorTy->isFPOrFPVectorTy())
12915     return false;
12916 
12917   // If the index is unknown at compile time, this is very expensive to lower
12918   // and it is not possible to combine the store with the extract.
12919   if (!isa<ConstantInt>(Idx))
12920     return false;
12921 
12922   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12923   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12924   // We can do a store + vector extract on any vector that fits perfectly in a D
12925   // or Q register.
12926   if (BitWidth == 64 || BitWidth == 128) {
12927     Cost = 0;
12928     return true;
12929   }
12930   return false;
12931 }
12932 
12933 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12934   return Subtarget->hasV6T2Ops();
12935 }
12936 
12937 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12938   return Subtarget->hasV6T2Ops();
12939 }
12940 
12941 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12942                                          AtomicOrdering Ord) const {
12943   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12944   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12945   bool IsAcquire = isAcquireOrStronger(Ord);
12946 
12947   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12948   // intrinsic must return {i32, i32} and we have to recombine them into a
12949   // single i64 here.
12950   if (ValTy->getPrimitiveSizeInBits() == 64) {
12951     Intrinsic::ID Int =
12952         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12953     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12954 
12955     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12956     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12957 
12958     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12959     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12960     if (!Subtarget->isLittle())
12961       std::swap (Lo, Hi);
12962     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12963     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12964     return Builder.CreateOr(
12965         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12966   }
12967 
12968   Type *Tys[] = { Addr->getType() };
12969   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12970   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12971 
12972   return Builder.CreateTruncOrBitCast(
12973       Builder.CreateCall(Ldrex, Addr),
12974       cast<PointerType>(Addr->getType())->getElementType());
12975 }
12976 
12977 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12978     IRBuilder<> &Builder) const {
12979   if (!Subtarget->hasV7Ops())
12980     return;
12981   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12982   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12983 }
12984 
12985 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12986                                                Value *Addr,
12987                                                AtomicOrdering Ord) const {
12988   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12989   bool IsRelease = isReleaseOrStronger(Ord);
12990 
12991   // Since the intrinsics must have legal type, the i64 intrinsics take two
12992   // parameters: "i32, i32". We must marshal Val into the appropriate form
12993   // before the call.
12994   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12995     Intrinsic::ID Int =
12996         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12997     Function *Strex = Intrinsic::getDeclaration(M, Int);
12998     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12999 
13000     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13001     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13002     if (!Subtarget->isLittle())
13003       std::swap (Lo, Hi);
13004     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13005     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13006   }
13007 
13008   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13009   Type *Tys[] = { Addr->getType() };
13010   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13011 
13012   return Builder.CreateCall(
13013       Strex, {Builder.CreateZExtOrBitCast(
13014                   Val, Strex->getFunctionType()->getParamType(0)),
13015               Addr});
13016 }
13017 
13018 /// \brief Lower an interleaved load into a vldN intrinsic.
13019 ///
13020 /// E.g. Lower an interleaved load (Factor = 2):
13021 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13022 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13023 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13024 ///
13025 ///      Into:
13026 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13027 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13028 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13029 bool ARMTargetLowering::lowerInterleavedLoad(
13030     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13031     ArrayRef<unsigned> Indices, unsigned Factor) const {
13032   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13033          "Invalid interleave factor");
13034   assert(!Shuffles.empty() && "Empty shufflevector input");
13035   assert(Shuffles.size() == Indices.size() &&
13036          "Unmatched number of shufflevectors and indices");
13037 
13038   VectorType *VecTy = Shuffles[0]->getType();
13039   Type *EltTy = VecTy->getVectorElementType();
13040 
13041   const DataLayout &DL = LI->getModule()->getDataLayout();
13042   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13043   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13044 
13045   // Skip if we do not have NEON and skip illegal vector types and vector types
13046   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
13047   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
13048     return false;
13049 
13050   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13051   // load integer vectors first and then convert to pointer vectors.
13052   if (EltTy->isPointerTy())
13053     VecTy =
13054         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13055 
13056   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13057                                             Intrinsic::arm_neon_vld3,
13058                                             Intrinsic::arm_neon_vld4};
13059 
13060   IRBuilder<> Builder(LI);
13061   SmallVector<Value *, 2> Ops;
13062 
13063   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13064   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
13065   Ops.push_back(Builder.getInt32(LI->getAlignment()));
13066 
13067   Type *Tys[] = { VecTy, Int8Ptr };
13068   Function *VldnFunc =
13069       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13070   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13071 
13072   // Replace uses of each shufflevector with the corresponding vector loaded
13073   // by ldN.
13074   for (unsigned i = 0; i < Shuffles.size(); i++) {
13075     ShuffleVectorInst *SV = Shuffles[i];
13076     unsigned Index = Indices[i];
13077 
13078     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13079 
13080     // Convert the integer vector to pointer vector if the element is pointer.
13081     if (EltTy->isPointerTy())
13082       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13083 
13084     SV->replaceAllUsesWith(SubVec);
13085   }
13086 
13087   return true;
13088 }
13089 
13090 /// \brief Get a mask consisting of sequential integers starting from \p Start.
13091 ///
13092 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
13093 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
13094                                    unsigned NumElts) {
13095   SmallVector<Constant *, 16> Mask;
13096   for (unsigned i = 0; i < NumElts; i++)
13097     Mask.push_back(Builder.getInt32(Start + i));
13098 
13099   return ConstantVector::get(Mask);
13100 }
13101 
13102 /// \brief Lower an interleaved store into a vstN intrinsic.
13103 ///
13104 /// E.g. Lower an interleaved store (Factor = 3):
13105 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13106 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13107 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13108 ///
13109 ///      Into:
13110 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13111 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13112 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13113 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13114 ///
13115 /// Note that the new shufflevectors will be removed and we'll only generate one
13116 /// vst3 instruction in CodeGen.
13117 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13118                                               ShuffleVectorInst *SVI,
13119                                               unsigned Factor) const {
13120   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13121          "Invalid interleave factor");
13122 
13123   VectorType *VecTy = SVI->getType();
13124   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13125          "Invalid interleaved store");
13126 
13127   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
13128   Type *EltTy = VecTy->getVectorElementType();
13129   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
13130 
13131   const DataLayout &DL = SI->getModule()->getDataLayout();
13132   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
13133   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13134 
13135   // Skip if we do not have NEON and skip illegal vector types and vector types
13136   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
13137   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
13138       EltIs64Bits)
13139     return false;
13140 
13141   Value *Op0 = SVI->getOperand(0);
13142   Value *Op1 = SVI->getOperand(1);
13143   IRBuilder<> Builder(SI);
13144 
13145   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13146   // vectors to integer vectors.
13147   if (EltTy->isPointerTy()) {
13148     Type *IntTy = DL.getIntPtrType(EltTy);
13149 
13150     // Convert to the corresponding integer vector.
13151     Type *IntVecTy =
13152         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13153     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13154     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13155 
13156     SubVecTy = VectorType::get(IntTy, NumSubElts);
13157   }
13158 
13159   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13160                                              Intrinsic::arm_neon_vst3,
13161                                              Intrinsic::arm_neon_vst4};
13162   SmallVector<Value *, 6> Ops;
13163 
13164   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13165   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
13166 
13167   Type *Tys[] = { Int8Ptr, SubVecTy };
13168   Function *VstNFunc = Intrinsic::getDeclaration(
13169       SI->getModule(), StoreInts[Factor - 2], Tys);
13170 
13171   // Split the shufflevector operands into sub vectors for the new vstN call.
13172   for (unsigned i = 0; i < Factor; i++)
13173     Ops.push_back(Builder.CreateShuffleVector(
13174         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
13175 
13176   Ops.push_back(Builder.getInt32(SI->getAlignment()));
13177   Builder.CreateCall(VstNFunc, Ops);
13178   return true;
13179 }
13180 
13181 enum HABaseType {
13182   HA_UNKNOWN = 0,
13183   HA_FLOAT,
13184   HA_DOUBLE,
13185   HA_VECT64,
13186   HA_VECT128
13187 };
13188 
13189 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13190                                    uint64_t &Members) {
13191   if (auto *ST = dyn_cast<StructType>(Ty)) {
13192     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13193       uint64_t SubMembers = 0;
13194       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13195         return false;
13196       Members += SubMembers;
13197     }
13198   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13199     uint64_t SubMembers = 0;
13200     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13201       return false;
13202     Members += SubMembers * AT->getNumElements();
13203   } else if (Ty->isFloatTy()) {
13204     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13205       return false;
13206     Members = 1;
13207     Base = HA_FLOAT;
13208   } else if (Ty->isDoubleTy()) {
13209     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13210       return false;
13211     Members = 1;
13212     Base = HA_DOUBLE;
13213   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13214     Members = 1;
13215     switch (Base) {
13216     case HA_FLOAT:
13217     case HA_DOUBLE:
13218       return false;
13219     case HA_VECT64:
13220       return VT->getBitWidth() == 64;
13221     case HA_VECT128:
13222       return VT->getBitWidth() == 128;
13223     case HA_UNKNOWN:
13224       switch (VT->getBitWidth()) {
13225       case 64:
13226         Base = HA_VECT64;
13227         return true;
13228       case 128:
13229         Base = HA_VECT128;
13230         return true;
13231       default:
13232         return false;
13233       }
13234     }
13235   }
13236 
13237   return (Members > 0 && Members <= 4);
13238 }
13239 
13240 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13241 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13242 /// passing according to AAPCS rules.
13243 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13244     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13245   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13246       CallingConv::ARM_AAPCS_VFP)
13247     return false;
13248 
13249   HABaseType Base = HA_UNKNOWN;
13250   uint64_t Members = 0;
13251   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13252   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13253 
13254   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13255   return IsHA || IsIntArray;
13256 }
13257 
13258 unsigned ARMTargetLowering::getExceptionPointerRegister(
13259     const Constant *PersonalityFn) const {
13260   // Platforms which do not use SjLj EH may return values in these registers
13261   // via the personality function.
13262   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13263 }
13264 
13265 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13266     const Constant *PersonalityFn) const {
13267   // Platforms which do not use SjLj EH may return values in these registers
13268   // via the personality function.
13269   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13270 }
13271 
13272 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13273   // Update IsSplitCSR in ARMFunctionInfo.
13274   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13275   AFI->setIsSplitCSR(true);
13276 }
13277 
13278 void ARMTargetLowering::insertCopiesSplitCSR(
13279     MachineBasicBlock *Entry,
13280     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13281   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13282   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13283   if (!IStart)
13284     return;
13285 
13286   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13287   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13288   MachineBasicBlock::iterator MBBI = Entry->begin();
13289   for (const MCPhysReg *I = IStart; *I; ++I) {
13290     const TargetRegisterClass *RC = nullptr;
13291     if (ARM::GPRRegClass.contains(*I))
13292       RC = &ARM::GPRRegClass;
13293     else if (ARM::DPRRegClass.contains(*I))
13294       RC = &ARM::DPRRegClass;
13295     else
13296       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13297 
13298     unsigned NewVR = MRI->createVirtualRegister(RC);
13299     // Create copy from CSR to a virtual register.
13300     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13301     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13302     // nounwind. If we want to generalize this later, we may need to emit
13303     // CFI pseudo-instructions.
13304     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13305                Attribute::NoUnwind) &&
13306            "Function should be nounwind in insertCopiesSplitCSR!");
13307     Entry->addLiveIn(*I);
13308     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13309         .addReg(*I);
13310 
13311     // Insert the copy-back instructions right before the terminator.
13312     for (auto *Exit : Exits)
13313       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13314               TII->get(TargetOpcode::COPY), *I)
13315           .addReg(NewVR);
13316   }
13317 }
13318