AArch64/ARM64: Port NEON post-increment load/store with 2/3/4 vectors to ARM64 backend.
[oota-llvm.git] / lib / Target / ARM64 / ARM64ISelLowering.cpp
1 //===-- ARM64ISelLowering.cpp - ARM64 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 implements the ARM64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM64ISelLowering.h"
15 #include "ARM64PerfectShuffle.h"
16 #include "ARM64Subtarget.h"
17 #include "ARM64CallingConv.h"
18 #include "ARM64MachineFunctionInfo.h"
19 #include "ARM64TargetMachine.h"
20 #include "ARM64TargetObjectFile.h"
21 #include "MCTargetDesc/ARM64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
35 using namespace llvm;
36
37 #define DEBUG_TYPE "arm64-lower"
38
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
41
42 // This option should go away when tail calls fully work.
43 static cl::opt<bool>
44 EnableARM64TailCalls("arm64-tail-calls", cl::Hidden,
45                      cl::desc("Generate ARM64 tail calls (TEMPORARY OPTION)."),
46                      cl::init(true));
47
48 enum AlignMode {
49   StrictAlign,
50   NoStrictAlign
51 };
52
53 static cl::opt<AlignMode>
54 Align(cl::desc("Load/store alignment support"),
55       cl::Hidden, cl::init(NoStrictAlign),
56       cl::values(
57           clEnumValN(StrictAlign,   "arm64-strict-align",
58                      "Disallow all unaligned memory accesses"),
59           clEnumValN(NoStrictAlign, "arm64-no-strict-align",
60                      "Allow unaligned memory accesses"),
61           clEnumValEnd));
62
63 // Place holder until extr generation is tested fully.
64 static cl::opt<bool>
65 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
66                           cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
67                           cl::init(true));
68
69 static cl::opt<bool>
70 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
71                          cl::desc("Allow ARM64 SLI/SRI formation"),
72                          cl::init(false));
73
74 //===----------------------------------------------------------------------===//
75 // ARM64 Lowering public interface.
76 //===----------------------------------------------------------------------===//
77 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
78   if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
79     return new ARM64_MachoTargetObjectFile();
80
81   return new ARM64_ELFTargetObjectFile();
82 }
83
84 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
85     : TargetLowering(TM, createTLOF(TM)) {
86   Subtarget = &TM.getSubtarget<ARM64Subtarget>();
87
88   // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
89   // we have to make something up. Arbitrarily, choose ZeroOrOne.
90   setBooleanContents(ZeroOrOneBooleanContent);
91   // When comparing vectors the result sets the different elements in the
92   // vector to all-one or all-zero.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // Set up the register classes.
96   addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
97   addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
98
99   if (Subtarget->hasFPARMv8()) {
100     addRegisterClass(MVT::f16, &ARM64::FPR16RegClass);
101     addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
102     addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
103     addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
104   }
105
106   if (Subtarget->hasNEON()) {
107     addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
108     addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
109     // Someone set us up the NEON.
110     addDRTypeForNEON(MVT::v2f32);
111     addDRTypeForNEON(MVT::v8i8);
112     addDRTypeForNEON(MVT::v4i16);
113     addDRTypeForNEON(MVT::v2i32);
114     addDRTypeForNEON(MVT::v1i64);
115     addDRTypeForNEON(MVT::v1f64);
116
117     addQRTypeForNEON(MVT::v4f32);
118     addQRTypeForNEON(MVT::v2f64);
119     addQRTypeForNEON(MVT::v16i8);
120     addQRTypeForNEON(MVT::v8i16);
121     addQRTypeForNEON(MVT::v4i32);
122     addQRTypeForNEON(MVT::v2i64);
123   }
124
125   // Compute derived properties from the register classes
126   computeRegisterProperties();
127
128   // Provide all sorts of operation actions
129   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
130   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
131   setOperationAction(ISD::SETCC, MVT::i32, Custom);
132   setOperationAction(ISD::SETCC, MVT::i64, Custom);
133   setOperationAction(ISD::SETCC, MVT::f32, Custom);
134   setOperationAction(ISD::SETCC, MVT::f64, Custom);
135   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
136   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
137   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
138   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
139   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
140   setOperationAction(ISD::SELECT, MVT::i32, Custom);
141   setOperationAction(ISD::SELECT, MVT::i64, Custom);
142   setOperationAction(ISD::SELECT, MVT::f32, Custom);
143   setOperationAction(ISD::SELECT, MVT::f64, Custom);
144   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
145   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
146   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
147   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
148   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
149   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
150
151   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
152   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
153   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
154
155   setOperationAction(ISD::FREM, MVT::f32, Expand);
156   setOperationAction(ISD::FREM, MVT::f64, Expand);
157   setOperationAction(ISD::FREM, MVT::f80, Expand);
158
159   // Custom lowering hooks are needed for XOR
160   // to fold it into CSINC/CSINV.
161   setOperationAction(ISD::XOR, MVT::i32, Custom);
162   setOperationAction(ISD::XOR, MVT::i64, Custom);
163
164   // Virtually no operation on f128 is legal, but LLVM can't expand them when
165   // there's a valid register class, so we need custom operations in most cases.
166   setOperationAction(ISD::FABS, MVT::f128, Expand);
167   setOperationAction(ISD::FADD, MVT::f128, Custom);
168   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
169   setOperationAction(ISD::FCOS, MVT::f128, Expand);
170   setOperationAction(ISD::FDIV, MVT::f128, Custom);
171   setOperationAction(ISD::FMA, MVT::f128, Expand);
172   setOperationAction(ISD::FMUL, MVT::f128, Custom);
173   setOperationAction(ISD::FNEG, MVT::f128, Expand);
174   setOperationAction(ISD::FPOW, MVT::f128, Expand);
175   setOperationAction(ISD::FREM, MVT::f128, Expand);
176   setOperationAction(ISD::FRINT, MVT::f128, Expand);
177   setOperationAction(ISD::FSIN, MVT::f128, Expand);
178   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
179   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
180   setOperationAction(ISD::FSUB, MVT::f128, Custom);
181   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
182   setOperationAction(ISD::SETCC, MVT::f128, Custom);
183   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
184   setOperationAction(ISD::SELECT, MVT::f128, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
186   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
187
188   // Lowering for many of the conversions is actually specified by the non-f128
189   // type. The LowerXXX function will be trivial when f128 isn't involved.
190   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
191   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
192   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
193   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
194   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
195   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
196   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
197   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
198   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
199   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
200   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
201   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
202   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
203   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
204
205   // Variable arguments.
206   setOperationAction(ISD::VASTART, MVT::Other, Custom);
207   setOperationAction(ISD::VAARG, MVT::Other, Custom);
208   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
209   setOperationAction(ISD::VAEND, MVT::Other, Expand);
210
211   // Variable-sized objects.
212   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
215
216   // Exception handling.
217   // FIXME: These are guesses. Has this been defined yet?
218   setExceptionPointerRegister(ARM64::X0);
219   setExceptionSelectorRegister(ARM64::X1);
220
221   // Constant pool entries
222   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
223
224   // BlockAddress
225   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
226
227   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
228   setOperationAction(ISD::ADDC, MVT::i32, Custom);
229   setOperationAction(ISD::ADDE, MVT::i32, Custom);
230   setOperationAction(ISD::SUBC, MVT::i32, Custom);
231   setOperationAction(ISD::SUBE, MVT::i32, Custom);
232   setOperationAction(ISD::ADDC, MVT::i64, Custom);
233   setOperationAction(ISD::ADDE, MVT::i64, Custom);
234   setOperationAction(ISD::SUBC, MVT::i64, Custom);
235   setOperationAction(ISD::SUBE, MVT::i64, Custom);
236
237   // ARM64 lacks both left-rotate and popcount instructions.
238   setOperationAction(ISD::ROTL, MVT::i32, Expand);
239   setOperationAction(ISD::ROTL, MVT::i64, Expand);
240
241   // ARM64 doesn't have {U|S}MUL_LOHI.
242   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
243   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
244
245
246   // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
247   // counterparts, which ARM64 supports directly.
248   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
249   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
250   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
251   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
252
253   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
254   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
255
256   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
257   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
258   setOperationAction(ISD::SREM, MVT::i32, Expand);
259   setOperationAction(ISD::SREM, MVT::i64, Expand);
260   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
262   setOperationAction(ISD::UREM, MVT::i32, Expand);
263   setOperationAction(ISD::UREM, MVT::i64, Expand);
264
265   // Custom lower Add/Sub/Mul with overflow.
266   setOperationAction(ISD::SADDO, MVT::i32, Custom);
267   setOperationAction(ISD::SADDO, MVT::i64, Custom);
268   setOperationAction(ISD::UADDO, MVT::i32, Custom);
269   setOperationAction(ISD::UADDO, MVT::i64, Custom);
270   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
271   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
272   setOperationAction(ISD::USUBO, MVT::i32, Custom);
273   setOperationAction(ISD::USUBO, MVT::i64, Custom);
274   setOperationAction(ISD::SMULO, MVT::i32, Custom);
275   setOperationAction(ISD::SMULO, MVT::i64, Custom);
276   setOperationAction(ISD::UMULO, MVT::i32, Custom);
277   setOperationAction(ISD::UMULO, MVT::i64, Custom);
278
279   setOperationAction(ISD::FSIN, MVT::f32, Expand);
280   setOperationAction(ISD::FSIN, MVT::f64, Expand);
281   setOperationAction(ISD::FCOS, MVT::f32, Expand);
282   setOperationAction(ISD::FCOS, MVT::f64, Expand);
283   setOperationAction(ISD::FPOW, MVT::f32, Expand);
284   setOperationAction(ISD::FPOW, MVT::f64, Expand);
285   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
287
288   // ARM64 has implementations of a lot of rounding-like FP operations.
289   static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
290   for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
291     MVT Ty = RoundingTypes[I];
292     setOperationAction(ISD::FFLOOR, Ty, Legal);
293     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
294     setOperationAction(ISD::FCEIL, Ty, Legal);
295     setOperationAction(ISD::FRINT, Ty, Legal);
296     setOperationAction(ISD::FTRUNC, Ty, Legal);
297     setOperationAction(ISD::FROUND, Ty, Legal);
298   }
299
300   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
301
302   if (Subtarget->isTargetMachO()) {
303     // For iOS, we don't want to the normal expansion of a libcall to
304     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
305     // traffic.
306     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
307     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
308   } else {
309     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
310     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
311   }
312
313   // ARM64 does not have floating-point extending loads, i1 sign-extending load,
314   // floating-point truncating stores, or v2i32->v2i16 truncating store.
315   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
316   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
317   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
318   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
319   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
320   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
321   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
322   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
323   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
324   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
325   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
326   // Indexed loads and stores are supported.
327   for (unsigned im = (unsigned)ISD::PRE_INC;
328        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
329     setIndexedLoadAction(im, MVT::i8, Legal);
330     setIndexedLoadAction(im, MVT::i16, Legal);
331     setIndexedLoadAction(im, MVT::i32, Legal);
332     setIndexedLoadAction(im, MVT::i64, Legal);
333     setIndexedLoadAction(im, MVT::f64, Legal);
334     setIndexedLoadAction(im, MVT::f32, Legal);
335     setIndexedStoreAction(im, MVT::i8, Legal);
336     setIndexedStoreAction(im, MVT::i16, Legal);
337     setIndexedStoreAction(im, MVT::i32, Legal);
338     setIndexedStoreAction(im, MVT::i64, Legal);
339     setIndexedStoreAction(im, MVT::f64, Legal);
340     setIndexedStoreAction(im, MVT::f32, Legal);
341   }
342
343   // Trap.
344   setOperationAction(ISD::TRAP, MVT::Other, Legal);
345
346   // We combine OR nodes for bitfield operations.
347   setTargetDAGCombine(ISD::OR);
348
349   // Vector add and sub nodes may conceal a high-half opportunity.
350   // Also, try to fold ADD into CSINC/CSINV..
351   setTargetDAGCombine(ISD::ADD);
352   setTargetDAGCombine(ISD::SUB);
353
354   setTargetDAGCombine(ISD::XOR);
355   setTargetDAGCombine(ISD::SINT_TO_FP);
356   setTargetDAGCombine(ISD::UINT_TO_FP);
357
358   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
359
360   setTargetDAGCombine(ISD::ANY_EXTEND);
361   setTargetDAGCombine(ISD::ZERO_EXTEND);
362   setTargetDAGCombine(ISD::SIGN_EXTEND);
363   setTargetDAGCombine(ISD::BITCAST);
364   setTargetDAGCombine(ISD::CONCAT_VECTORS);
365   setTargetDAGCombine(ISD::STORE);
366
367   setTargetDAGCombine(ISD::MUL);
368
369   setTargetDAGCombine(ISD::SELECT);
370   setTargetDAGCombine(ISD::VSELECT);
371
372   setTargetDAGCombine(ISD::INTRINSIC_VOID);
373   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
374
375   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
376   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
377   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
378
379   setStackPointerRegisterToSaveRestore(ARM64::SP);
380
381   setSchedulingPreference(Sched::Hybrid);
382
383   // Enable TBZ/TBNZ
384   MaskAndBranchFoldingIsLegal = true;
385
386   setMinFunctionAlignment(2);
387
388   RequireStrictAlign = (Align == StrictAlign);
389
390   setHasExtractBitsInsn(true);
391
392   if (Subtarget->hasNEON()) {
393     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
394     // silliness like this:
395     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
396     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
397     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
398     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
399     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
400     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
401     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
402     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
403     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
404     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
405     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
406     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
407     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
408     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
409     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
410     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
411     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
412     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
413     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
414     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
415     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
416     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
417     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
418     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
419     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
420
421     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
422     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
423     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
424     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
425     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
426
427     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
428
429     // ARM64 doesn't have a direct vector ->f32 conversion instructions for
430     // elements smaller than i32, so promote the input to i32 first.
431     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
432     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
433     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
434     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
435     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
436     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
437     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
438     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
439     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
440
441     // ARM64 doesn't have MUL.2d:
442     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
443     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
444     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
445     // Likewise, narrowing and extending vector loads/stores aren't handled
446     // directly.
447     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448          VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
449
450       setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
451                          Expand);
452
453       setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
454       setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
455       setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
456       setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
457
458       for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
459            InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
460         setTruncStoreAction((MVT::SimpleValueType)VT,
461                             (MVT::SimpleValueType)InnerVT, Expand);
462       setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
463       setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
464       setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
465     }
466
467     // ARM64 has implementations of a lot of rounding-like FP operations.
468     static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
469     for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
470       MVT Ty = RoundingVecTypes[I];
471       setOperationAction(ISD::FFLOOR, Ty, Legal);
472       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
473       setOperationAction(ISD::FCEIL, Ty, Legal);
474       setOperationAction(ISD::FRINT, Ty, Legal);
475       setOperationAction(ISD::FTRUNC, Ty, Legal);
476       setOperationAction(ISD::FROUND, Ty, Legal);
477     }
478   }
479 }
480
481 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
482   if (VT == MVT::v2f32) {
483     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
484     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
485
486     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
487     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
488   } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
489     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
490     AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
491
492     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
493     AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
494   }
495
496   // Mark vector float intrinsics as expand.
497   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
498     setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
499     setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
500     setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
501     setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
502     setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
503     setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
504     setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
505     setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
506     setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
507   }
508
509   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
510   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
511   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
512   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
513   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
514   setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
515   setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
516   setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
517   setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
518   setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
519   setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
520   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
521
522   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
523   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
524   setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
525   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
526
527   // CNT supports only B element sizes.
528   if (VT != MVT::v8i8 && VT != MVT::v16i8)
529     setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
530
531   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
532   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
533   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
534   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
535   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
536
537   setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
538   setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
539
540   if (Subtarget->isLittleEndian()) {
541     for (unsigned im = (unsigned)ISD::PRE_INC;
542          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
543       setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
544       setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
545     }
546   }
547 }
548
549 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
550   addRegisterClass(VT, &ARM64::FPR64RegClass);
551   addTypeForNEON(VT, MVT::v2i32);
552 }
553
554 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
555   addRegisterClass(VT, &ARM64::FPR128RegClass);
556   addTypeForNEON(VT, MVT::v4i32);
557 }
558
559 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
560   if (!VT.isVector())
561     return MVT::i32;
562   return VT.changeVectorElementTypeToInteger();
563 }
564
565 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
566 /// Mask are known to be either zero or one and return them in the
567 /// KnownZero/KnownOne bitsets.
568 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
569     const SDValue Op, APInt &KnownZero, APInt &KnownOne,
570     const SelectionDAG &DAG, unsigned Depth) const {
571   switch (Op.getOpcode()) {
572   default:
573     break;
574   case ARM64ISD::CSEL: {
575     APInt KnownZero2, KnownOne2;
576     DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
577     DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
578     KnownZero &= KnownZero2;
579     KnownOne &= KnownOne2;
580     break;
581   }
582   case ISD::INTRINSIC_W_CHAIN: {
583    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
584     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
585     switch (IntID) {
586     default: return;
587     case Intrinsic::arm64_ldaxr:
588     case Intrinsic::arm64_ldxr: {
589       unsigned BitWidth = KnownOne.getBitWidth();
590       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
591       unsigned MemBits = VT.getScalarType().getSizeInBits();
592       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
593       return;
594     }
595     }
596     break;
597   }
598   case ISD::INTRINSIC_WO_CHAIN:
599   case ISD::INTRINSIC_VOID: {
600     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
601     switch (IntNo) {
602     default:
603       break;
604     case Intrinsic::arm64_neon_umaxv:
605     case Intrinsic::arm64_neon_uminv: {
606       // Figure out the datatype of the vector operand. The UMINV instruction
607       // will zero extend the result, so we can mark as known zero all the
608       // bits larger than the element datatype. 32-bit or larget doesn't need
609       // this as those are legal types and will be handled by isel directly.
610       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
611       unsigned BitWidth = KnownZero.getBitWidth();
612       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
613         assert(BitWidth >= 8 && "Unexpected width!");
614         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
615         KnownZero |= Mask;
616       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
617         assert(BitWidth >= 16 && "Unexpected width!");
618         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
619         KnownZero |= Mask;
620       }
621       break;
622     } break;
623     }
624   }
625   }
626 }
627
628 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
629   return MVT::i64;
630 }
631
632 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
633   // FIXME: On ARM64, this depends on the type.
634   // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
635   // and the offset has to be a multiple of the related size in bytes.
636   return 4095;
637 }
638
639 FastISel *
640 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
641                                     const TargetLibraryInfo *libInfo) const {
642   return ARM64::createFastISel(funcInfo, libInfo);
643 }
644
645 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
646   switch (Opcode) {
647   default:
648     return nullptr;
649   case ARM64ISD::CALL:              return "ARM64ISD::CALL";
650   case ARM64ISD::ADRP:              return "ARM64ISD::ADRP";
651   case ARM64ISD::ADDlow:            return "ARM64ISD::ADDlow";
652   case ARM64ISD::LOADgot:           return "ARM64ISD::LOADgot";
653   case ARM64ISD::RET_FLAG:          return "ARM64ISD::RET_FLAG";
654   case ARM64ISD::BRCOND:            return "ARM64ISD::BRCOND";
655   case ARM64ISD::CSEL:              return "ARM64ISD::CSEL";
656   case ARM64ISD::FCSEL:             return "ARM64ISD::FCSEL";
657   case ARM64ISD::CSINV:             return "ARM64ISD::CSINV";
658   case ARM64ISD::CSNEG:             return "ARM64ISD::CSNEG";
659   case ARM64ISD::CSINC:             return "ARM64ISD::CSINC";
660   case ARM64ISD::THREAD_POINTER:    return "ARM64ISD::THREAD_POINTER";
661   case ARM64ISD::TLSDESC_CALL:      return "ARM64ISD::TLSDESC_CALL";
662   case ARM64ISD::ADC:               return "ARM64ISD::ADC";
663   case ARM64ISD::SBC:               return "ARM64ISD::SBC";
664   case ARM64ISD::ADDS:              return "ARM64ISD::ADDS";
665   case ARM64ISD::SUBS:              return "ARM64ISD::SUBS";
666   case ARM64ISD::ADCS:              return "ARM64ISD::ADCS";
667   case ARM64ISD::SBCS:              return "ARM64ISD::SBCS";
668   case ARM64ISD::ANDS:              return "ARM64ISD::ANDS";
669   case ARM64ISD::FCMP:              return "ARM64ISD::FCMP";
670   case ARM64ISD::FMIN:              return "ARM64ISD::FMIN";
671   case ARM64ISD::FMAX:              return "ARM64ISD::FMAX";
672   case ARM64ISD::DUP:               return "ARM64ISD::DUP";
673   case ARM64ISD::DUPLANE8:          return "ARM64ISD::DUPLANE8";
674   case ARM64ISD::DUPLANE16:         return "ARM64ISD::DUPLANE16";
675   case ARM64ISD::DUPLANE32:         return "ARM64ISD::DUPLANE32";
676   case ARM64ISD::DUPLANE64:         return "ARM64ISD::DUPLANE64";
677   case ARM64ISD::MOVI:              return "ARM64ISD::MOVI";
678   case ARM64ISD::MOVIshift:         return "ARM64ISD::MOVIshift";
679   case ARM64ISD::MOVIedit:          return "ARM64ISD::MOVIedit";
680   case ARM64ISD::MOVImsl:           return "ARM64ISD::MOVImsl";
681   case ARM64ISD::FMOV:              return "ARM64ISD::FMOV";
682   case ARM64ISD::MVNIshift:         return "ARM64ISD::MVNIshift";
683   case ARM64ISD::MVNImsl:           return "ARM64ISD::MVNImsl";
684   case ARM64ISD::BICi:              return "ARM64ISD::BICi";
685   case ARM64ISD::ORRi:              return "ARM64ISD::ORRi";
686   case ARM64ISD::BSL:               return "ARM64ISD::BSL";
687   case ARM64ISD::NEG:               return "ARM64ISD::NEG";
688   case ARM64ISD::EXTR:              return "ARM64ISD::EXTR";
689   case ARM64ISD::ZIP1:              return "ARM64ISD::ZIP1";
690   case ARM64ISD::ZIP2:              return "ARM64ISD::ZIP2";
691   case ARM64ISD::UZP1:              return "ARM64ISD::UZP1";
692   case ARM64ISD::UZP2:              return "ARM64ISD::UZP2";
693   case ARM64ISD::TRN1:              return "ARM64ISD::TRN1";
694   case ARM64ISD::TRN2:              return "ARM64ISD::TRN2";
695   case ARM64ISD::REV16:             return "ARM64ISD::REV16";
696   case ARM64ISD::REV32:             return "ARM64ISD::REV32";
697   case ARM64ISD::REV64:             return "ARM64ISD::REV64";
698   case ARM64ISD::EXT:               return "ARM64ISD::EXT";
699   case ARM64ISD::VSHL:              return "ARM64ISD::VSHL";
700   case ARM64ISD::VLSHR:             return "ARM64ISD::VLSHR";
701   case ARM64ISD::VASHR:             return "ARM64ISD::VASHR";
702   case ARM64ISD::CMEQ:              return "ARM64ISD::CMEQ";
703   case ARM64ISD::CMGE:              return "ARM64ISD::CMGE";
704   case ARM64ISD::CMGT:              return "ARM64ISD::CMGT";
705   case ARM64ISD::CMHI:              return "ARM64ISD::CMHI";
706   case ARM64ISD::CMHS:              return "ARM64ISD::CMHS";
707   case ARM64ISD::FCMEQ:             return "ARM64ISD::FCMEQ";
708   case ARM64ISD::FCMGE:             return "ARM64ISD::FCMGE";
709   case ARM64ISD::FCMGT:             return "ARM64ISD::FCMGT";
710   case ARM64ISD::CMEQz:             return "ARM64ISD::CMEQz";
711   case ARM64ISD::CMGEz:             return "ARM64ISD::CMGEz";
712   case ARM64ISD::CMGTz:             return "ARM64ISD::CMGTz";
713   case ARM64ISD::CMLEz:             return "ARM64ISD::CMLEz";
714   case ARM64ISD::CMLTz:             return "ARM64ISD::CMLTz";
715   case ARM64ISD::FCMEQz:            return "ARM64ISD::FCMEQz";
716   case ARM64ISD::FCMGEz:            return "ARM64ISD::FCMGEz";
717   case ARM64ISD::FCMGTz:            return "ARM64ISD::FCMGTz";
718   case ARM64ISD::FCMLEz:            return "ARM64ISD::FCMLEz";
719   case ARM64ISD::FCMLTz:            return "ARM64ISD::FCMLTz";
720   case ARM64ISD::NOT:               return "ARM64ISD::NOT";
721   case ARM64ISD::BIT:               return "ARM64ISD::BIT";
722   case ARM64ISD::CBZ:               return "ARM64ISD::CBZ";
723   case ARM64ISD::CBNZ:              return "ARM64ISD::CBNZ";
724   case ARM64ISD::TBZ:               return "ARM64ISD::TBZ";
725   case ARM64ISD::TBNZ:              return "ARM64ISD::TBNZ";
726   case ARM64ISD::TC_RETURN:         return "ARM64ISD::TC_RETURN";
727   case ARM64ISD::SITOF:             return "ARM64ISD::SITOF";
728   case ARM64ISD::UITOF:             return "ARM64ISD::UITOF";
729   case ARM64ISD::SQSHL_I:           return "ARM64ISD::SQSHL_I";
730   case ARM64ISD::UQSHL_I:           return "ARM64ISD::UQSHL_I";
731   case ARM64ISD::SRSHR_I:           return "ARM64ISD::SRSHR_I";
732   case ARM64ISD::URSHR_I:           return "ARM64ISD::URSHR_I";
733   case ARM64ISD::SQSHLU_I:          return "ARM64ISD::SQSHLU_I";
734   case ARM64ISD::WrapperLarge:      return "ARM64ISD::WrapperLarge";
735   case ARM64ISD::LD2post:           return "ARM64ISD::LD2post";
736   case ARM64ISD::LD3post:           return "ARM64ISD::LD3post";
737   case ARM64ISD::LD4post:           return "ARM64ISD::LD4post";
738   case ARM64ISD::ST2post:           return "ARM64ISD::ST2post";
739   case ARM64ISD::ST3post:           return "ARM64ISD::ST3post";
740   case ARM64ISD::ST4post:           return "ARM64ISD::ST4post";
741   case ARM64ISD::LD1x2post:         return "ARM64ISD::LD1x2post";
742   case ARM64ISD::LD1x3post:         return "ARM64ISD::LD1x3post";
743   case ARM64ISD::LD1x4post:         return "ARM64ISD::LD1x4post";
744   case ARM64ISD::ST1x2post:         return "ARM64ISD::ST1x2post";
745   case ARM64ISD::ST1x3post:         return "ARM64ISD::ST1x3post";
746   case ARM64ISD::ST1x4post:         return "ARM64ISD::ST1x4post";
747   case ARM64ISD::LD2DUPpost:        return "ARM64ISD::LD2DUPpost";
748   case ARM64ISD::LD3DUPpost:        return "ARM64ISD::LD3DUPpost";
749   case ARM64ISD::LD4DUPpost:        return "ARM64ISD::LD4DUPpost";
750   case ARM64ISD::LD2LANEpost:       return "ARM64ISD::LD2LANEpost";
751   case ARM64ISD::LD3LANEpost:       return "ARM64ISD::LD3LANEpost";
752   case ARM64ISD::LD4LANEpost:       return "ARM64ISD::LD4LANEpost";
753   case ARM64ISD::ST2LANEpost:       return "ARM64ISD::ST2LANEpost";
754   case ARM64ISD::ST3LANEpost:       return "ARM64ISD::ST3LANEpost";
755   case ARM64ISD::ST4LANEpost:       return "ARM64ISD::ST4LANEpost";
756   }
757 }
758
759 MachineBasicBlock *
760 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
761                                   MachineBasicBlock *MBB) const {
762   // We materialise the F128CSEL pseudo-instruction as some control flow and a
763   // phi node:
764
765   // OrigBB:
766   //     [... previous instrs leading to comparison ...]
767   //     b.ne TrueBB
768   //     b EndBB
769   // TrueBB:
770   //     ; Fallthrough
771   // EndBB:
772   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
773
774   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
775   MachineFunction *MF = MBB->getParent();
776   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
777   DebugLoc DL = MI->getDebugLoc();
778   MachineFunction::iterator It = MBB;
779   ++It;
780
781   unsigned DestReg = MI->getOperand(0).getReg();
782   unsigned IfTrueReg = MI->getOperand(1).getReg();
783   unsigned IfFalseReg = MI->getOperand(2).getReg();
784   unsigned CondCode = MI->getOperand(3).getImm();
785   bool NZCVKilled = MI->getOperand(4).isKill();
786
787   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
788   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
789   MF->insert(It, TrueBB);
790   MF->insert(It, EndBB);
791
792   // Transfer rest of current basic-block to EndBB
793   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
794                 MBB->end());
795   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
796
797   BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
798   BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
799   MBB->addSuccessor(TrueBB);
800   MBB->addSuccessor(EndBB);
801
802   // TrueBB falls through to the end.
803   TrueBB->addSuccessor(EndBB);
804
805   if (!NZCVKilled) {
806     TrueBB->addLiveIn(ARM64::NZCV);
807     EndBB->addLiveIn(ARM64::NZCV);
808   }
809
810   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
811       .addReg(IfTrueReg)
812       .addMBB(TrueBB)
813       .addReg(IfFalseReg)
814       .addMBB(MBB);
815
816   MI->eraseFromParent();
817   return EndBB;
818 }
819
820 MachineBasicBlock *
821 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
822                                                  MachineBasicBlock *BB) const {
823   switch (MI->getOpcode()) {
824   default:
825 #ifndef NDEBUG
826     MI->dump();
827 #endif
828     assert(0 && "Unexpected instruction for custom inserter!");
829     break;
830
831   case ARM64::F128CSEL:
832     return EmitF128CSEL(MI, BB);
833
834   case TargetOpcode::STACKMAP:
835   case TargetOpcode::PATCHPOINT:
836     return emitPatchPoint(MI, BB);
837   }
838   llvm_unreachable("Unexpected instruction for custom inserter!");
839 }
840
841 //===----------------------------------------------------------------------===//
842 // ARM64 Lowering private implementation.
843 //===----------------------------------------------------------------------===//
844
845 //===----------------------------------------------------------------------===//
846 // Lowering Code
847 //===----------------------------------------------------------------------===//
848
849 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
850 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
851   switch (CC) {
852   default:
853     llvm_unreachable("Unknown condition code!");
854   case ISD::SETNE:
855     return ARM64CC::NE;
856   case ISD::SETEQ:
857     return ARM64CC::EQ;
858   case ISD::SETGT:
859     return ARM64CC::GT;
860   case ISD::SETGE:
861     return ARM64CC::GE;
862   case ISD::SETLT:
863     return ARM64CC::LT;
864   case ISD::SETLE:
865     return ARM64CC::LE;
866   case ISD::SETUGT:
867     return ARM64CC::HI;
868   case ISD::SETUGE:
869     return ARM64CC::HS;
870   case ISD::SETULT:
871     return ARM64CC::LO;
872   case ISD::SETULE:
873     return ARM64CC::LS;
874   }
875 }
876
877 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
878 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
879                                 ARM64CC::CondCode &CondCode2) {
880   CondCode2 = ARM64CC::AL;
881   switch (CC) {
882   default:
883     llvm_unreachable("Unknown FP condition!");
884   case ISD::SETEQ:
885   case ISD::SETOEQ:
886     CondCode = ARM64CC::EQ;
887     break;
888   case ISD::SETGT:
889   case ISD::SETOGT:
890     CondCode = ARM64CC::GT;
891     break;
892   case ISD::SETGE:
893   case ISD::SETOGE:
894     CondCode = ARM64CC::GE;
895     break;
896   case ISD::SETOLT:
897     CondCode = ARM64CC::MI;
898     break;
899   case ISD::SETOLE:
900     CondCode = ARM64CC::LS;
901     break;
902   case ISD::SETONE:
903     CondCode = ARM64CC::MI;
904     CondCode2 = ARM64CC::GT;
905     break;
906   case ISD::SETO:
907     CondCode = ARM64CC::VC;
908     break;
909   case ISD::SETUO:
910     CondCode = ARM64CC::VS;
911     break;
912   case ISD::SETUEQ:
913     CondCode = ARM64CC::EQ;
914     CondCode2 = ARM64CC::VS;
915     break;
916   case ISD::SETUGT:
917     CondCode = ARM64CC::HI;
918     break;
919   case ISD::SETUGE:
920     CondCode = ARM64CC::PL;
921     break;
922   case ISD::SETLT:
923   case ISD::SETULT:
924     CondCode = ARM64CC::LT;
925     break;
926   case ISD::SETLE:
927   case ISD::SETULE:
928     CondCode = ARM64CC::LE;
929     break;
930   case ISD::SETNE:
931   case ISD::SETUNE:
932     CondCode = ARM64CC::NE;
933     break;
934   }
935 }
936
937 /// changeVectorFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC
938 /// usable with the vector instructions. Fewer operations are available without
939 /// a real NZCV register, so we have to use less efficient combinations to get
940 /// the same effect.
941 static void changeVectorFPCCToARM64CC(ISD::CondCode CC,
942                                       ARM64CC::CondCode &CondCode,
943                                       ARM64CC::CondCode &CondCode2,
944                                       bool &Invert) {
945   Invert = false;
946   switch (CC) {
947   default:
948     // Mostly the scalar mappings work fine.
949     changeFPCCToARM64CC(CC, CondCode, CondCode2);
950     break;
951   case ISD::SETUO:
952     Invert = true; // Fallthrough
953   case ISD::SETO:
954     CondCode = ARM64CC::MI;
955     CondCode2 = ARM64CC::GE;
956     break;
957   case ISD::SETUEQ:
958   case ISD::SETULT:
959   case ISD::SETULE:
960   case ISD::SETUGT:
961   case ISD::SETUGE:
962     // All of the compare-mask comparisons are ordered, but we can switch
963     // between the two by a double inversion. E.g. ULE == !OGT.
964     Invert = true;
965     changeFPCCToARM64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
966     break;
967   }
968 }
969
970 static bool isLegalArithImmed(uint64_t C) {
971   // Matches ARM64DAGToDAGISel::SelectArithImmed().
972   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
973 }
974
975 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
976                               SDLoc dl, SelectionDAG &DAG) {
977   EVT VT = LHS.getValueType();
978
979   if (VT.isFloatingPoint())
980     return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
981
982   // The CMP instruction is just an alias for SUBS, and representing it as
983   // SUBS means that it's possible to get CSE with subtract operations.
984   // A later phase can perform the optimization of setting the destination
985   // register to WZR/XZR if it ends up being unused.
986   unsigned Opcode = ARM64ISD::SUBS;
987
988   if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
989       cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
990       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
991     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
992     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
993     // can be set differently by this operation. It comes down to whether
994     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
995     // everything is fine. If not then the optimization is wrong. Thus general
996     // comparisons are only valid if op2 != 0.
997
998     // So, finally, the only LLVM-native comparisons that don't mention C and V
999     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1000     // the absence of information about op2.
1001     Opcode = ARM64ISD::ADDS;
1002     RHS = RHS.getOperand(1);
1003   } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1004              cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1005              !isUnsignedIntSetCC(CC)) {
1006     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1007     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1008     // of the signed comparisons.
1009     Opcode = ARM64ISD::ANDS;
1010     RHS = LHS.getOperand(1);
1011     LHS = LHS.getOperand(0);
1012   }
1013
1014   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1015       .getValue(1);
1016 }
1017
1018 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1019                            SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
1020   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1021     EVT VT = RHS.getValueType();
1022     uint64_t C = RHSC->getZExtValue();
1023     if (!isLegalArithImmed(C)) {
1024       // Constant does not fit, try adjusting it by one?
1025       switch (CC) {
1026       default:
1027         break;
1028       case ISD::SETLT:
1029       case ISD::SETGE:
1030         if ((VT == MVT::i32 && C != 0x80000000 &&
1031              isLegalArithImmed((uint32_t)(C - 1))) ||
1032             (VT == MVT::i64 && C != 0x80000000ULL &&
1033              isLegalArithImmed(C - 1ULL))) {
1034           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1035           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1036           RHS = DAG.getConstant(C, VT);
1037         }
1038         break;
1039       case ISD::SETULT:
1040       case ISD::SETUGE:
1041         if ((VT == MVT::i32 && C != 0 &&
1042              isLegalArithImmed((uint32_t)(C - 1))) ||
1043             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1044           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1045           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1046           RHS = DAG.getConstant(C, VT);
1047         }
1048         break;
1049       case ISD::SETLE:
1050       case ISD::SETGT:
1051         if ((VT == MVT::i32 && C != 0x7fffffff &&
1052              isLegalArithImmed((uint32_t)(C + 1))) ||
1053             (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1054              isLegalArithImmed(C + 1ULL))) {
1055           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1056           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1057           RHS = DAG.getConstant(C, VT);
1058         }
1059         break;
1060       case ISD::SETULE:
1061       case ISD::SETUGT:
1062         if ((VT == MVT::i32 && C != 0xffffffff &&
1063              isLegalArithImmed((uint32_t)(C + 1))) ||
1064             (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1065              isLegalArithImmed(C + 1ULL))) {
1066           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1067           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1068           RHS = DAG.getConstant(C, VT);
1069         }
1070         break;
1071       }
1072     }
1073   }
1074
1075   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1076   ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1077   ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1078   return Cmp;
1079 }
1080
1081 static std::pair<SDValue, SDValue>
1082 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1083   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1084          "Unsupported value type");
1085   SDValue Value, Overflow;
1086   SDLoc DL(Op);
1087   SDValue LHS = Op.getOperand(0);
1088   SDValue RHS = Op.getOperand(1);
1089   unsigned Opc = 0;
1090   switch (Op.getOpcode()) {
1091   default:
1092     llvm_unreachable("Unknown overflow instruction!");
1093   case ISD::SADDO:
1094     Opc = ARM64ISD::ADDS;
1095     CC = ARM64CC::VS;
1096     break;
1097   case ISD::UADDO:
1098     Opc = ARM64ISD::ADDS;
1099     CC = ARM64CC::HS;
1100     break;
1101   case ISD::SSUBO:
1102     Opc = ARM64ISD::SUBS;
1103     CC = ARM64CC::VS;
1104     break;
1105   case ISD::USUBO:
1106     Opc = ARM64ISD::SUBS;
1107     CC = ARM64CC::LO;
1108     break;
1109   // Multiply needs a little bit extra work.
1110   case ISD::SMULO:
1111   case ISD::UMULO: {
1112     CC = ARM64CC::NE;
1113     bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1114     if (Op.getValueType() == MVT::i32) {
1115       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1116       // For a 32 bit multiply with overflow check we want the instruction
1117       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1118       // need to generate the following pattern:
1119       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1120       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1121       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1122       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1123       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1124                                 DAG.getConstant(0, MVT::i64));
1125       // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1126       // operation. We need to clear out the upper 32 bits, because we used a
1127       // widening multiply that wrote all 64 bits. In the end this should be a
1128       // noop.
1129       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1130       if (IsSigned) {
1131         // The signed overflow check requires more than just a simple check for
1132         // any bit set in the upper 32 bits of the result. These bits could be
1133         // just the sign bits of a negative number. To perform the overflow
1134         // check we have to arithmetic shift right the 32nd bit of the result by
1135         // 31 bits. Then we compare the result to the upper 32 bits.
1136         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1137                                         DAG.getConstant(32, MVT::i64));
1138         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1139         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1140                                         DAG.getConstant(31, MVT::i64));
1141         // It is important that LowerBits is last, otherwise the arithmetic
1142         // shift will not be folded into the compare (SUBS).
1143         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1144         Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1145                        .getValue(1);
1146       } else {
1147         // The overflow check for unsigned multiply is easy. We only need to
1148         // check if any of the upper 32 bits are set. This can be done with a
1149         // CMP (shifted register). For that we need to generate the following
1150         // pattern:
1151         // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1152         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1153                                         DAG.getConstant(32, MVT::i64));
1154         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1155         Overflow =
1156             DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1157                         UpperBits).getValue(1);
1158       }
1159       break;
1160     }
1161     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1162     // For the 64 bit multiply
1163     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1164     if (IsSigned) {
1165       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1166       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1167                                       DAG.getConstant(63, MVT::i64));
1168       // It is important that LowerBits is last, otherwise the arithmetic
1169       // shift will not be folded into the compare (SUBS).
1170       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1171       Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1172                      .getValue(1);
1173     } else {
1174       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1175       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1176       Overflow =
1177           DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1178                       UpperBits).getValue(1);
1179     }
1180     break;
1181   }
1182   } // switch (...)
1183
1184   if (Opc) {
1185     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1186
1187     // Emit the ARM64 operation with overflow check.
1188     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1189     Overflow = Value.getValue(1);
1190   }
1191   return std::make_pair(Value, Overflow);
1192 }
1193
1194 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1195                                            RTLIB::Libcall Call) const {
1196   SmallVector<SDValue, 2> Ops;
1197   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1198     Ops.push_back(Op.getOperand(i));
1199
1200   return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1201                      SDLoc(Op)).first;
1202 }
1203
1204 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1205   SDValue Sel = Op.getOperand(0);
1206   SDValue Other = Op.getOperand(1);
1207
1208   // If neither operand is a SELECT_CC, give up.
1209   if (Sel.getOpcode() != ISD::SELECT_CC)
1210     std::swap(Sel, Other);
1211   if (Sel.getOpcode() != ISD::SELECT_CC)
1212     return Op;
1213
1214   // The folding we want to perform is:
1215   // (xor x, (select_cc a, b, cc, 0, -1) )
1216   //   -->
1217   // (csel x, (xor x, -1), cc ...)
1218   //
1219   // The latter will get matched to a CSINV instruction.
1220
1221   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1222   SDValue LHS = Sel.getOperand(0);
1223   SDValue RHS = Sel.getOperand(1);
1224   SDValue TVal = Sel.getOperand(2);
1225   SDValue FVal = Sel.getOperand(3);
1226   SDLoc dl(Sel);
1227
1228   // FIXME: This could be generalized to non-integer comparisons.
1229   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1230     return Op;
1231
1232   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1233   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1234
1235   // The the values aren't constants, this isn't the pattern we're looking for.
1236   if (!CFVal || !CTVal)
1237     return Op;
1238
1239   // We can commute the SELECT_CC by inverting the condition.  This
1240   // might be needed to make this fit into a CSINV pattern.
1241   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1242     std::swap(TVal, FVal);
1243     std::swap(CTVal, CFVal);
1244     CC = ISD::getSetCCInverse(CC, true);
1245   }
1246
1247   // If the constants line up, perform the transform!
1248   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1249     SDValue CCVal;
1250     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1251
1252     FVal = Other;
1253     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1254                        DAG.getConstant(-1ULL, Other.getValueType()));
1255
1256     return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1257                        CCVal, Cmp);
1258   }
1259
1260   return Op;
1261 }
1262
1263 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1264   EVT VT = Op.getValueType();
1265
1266   // Let legalize expand this if it isn't a legal type yet.
1267   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1268     return SDValue();
1269
1270   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1271
1272   unsigned Opc;
1273   bool ExtraOp = false;
1274   switch (Op.getOpcode()) {
1275   default:
1276     assert(0 && "Invalid code");
1277   case ISD::ADDC:
1278     Opc = ARM64ISD::ADDS;
1279     break;
1280   case ISD::SUBC:
1281     Opc = ARM64ISD::SUBS;
1282     break;
1283   case ISD::ADDE:
1284     Opc = ARM64ISD::ADCS;
1285     ExtraOp = true;
1286     break;
1287   case ISD::SUBE:
1288     Opc = ARM64ISD::SBCS;
1289     ExtraOp = true;
1290     break;
1291   }
1292
1293   if (!ExtraOp)
1294     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1295   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1296                      Op.getOperand(2));
1297 }
1298
1299 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1300   // Let legalize expand this if it isn't a legal type yet.
1301   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1302     return SDValue();
1303
1304   ARM64CC::CondCode CC;
1305   // The actual operation that sets the overflow or carry flag.
1306   SDValue Value, Overflow;
1307   std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1308
1309   // We use 0 and 1 as false and true values.
1310   SDValue TVal = DAG.getConstant(1, MVT::i32);
1311   SDValue FVal = DAG.getConstant(0, MVT::i32);
1312
1313   // We use an inverted condition, because the conditional select is inverted
1314   // too. This will allow it to be selected to a single instruction:
1315   // CSINC Wd, WZR, WZR, invert(cond).
1316   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1317   Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1318                          Overflow);
1319
1320   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1321   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1322 }
1323
1324 // Prefetch operands are:
1325 // 1: Address to prefetch
1326 // 2: bool isWrite
1327 // 3: int locality (0 = no locality ... 3 = extreme locality)
1328 // 4: bool isDataCache
1329 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1330   SDLoc DL(Op);
1331   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1332   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1333   // The data thing is not used.
1334   // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1335
1336   bool IsStream = !Locality;
1337   // When the locality number is set
1338   if (Locality) {
1339     // The front-end should have filtered out the out-of-range values
1340     assert(Locality <= 3 && "Prefetch locality out-of-range");
1341     // The locality degree is the opposite of the cache speed.
1342     // Put the number the other way around.
1343     // The encoding starts at 0 for level 1
1344     Locality = 3 - Locality;
1345   }
1346
1347   // built the mask value encoding the expected behavior.
1348   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
1349                    (Locality << 1) |    // Cache level bits
1350                    (unsigned)IsStream;  // Stream bit
1351   return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1352                      DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1353 }
1354
1355 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1356                                             SelectionDAG &DAG) const {
1357   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1358
1359   RTLIB::Libcall LC;
1360   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1361
1362   return LowerF128Call(Op, DAG, LC);
1363 }
1364
1365 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1366                                            SelectionDAG &DAG) const {
1367   if (Op.getOperand(0).getValueType() != MVT::f128) {
1368     // It's legal except when f128 is involved
1369     return Op;
1370   }
1371
1372   RTLIB::Libcall LC;
1373   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1374
1375   // FP_ROUND node has a second operand indicating whether it is known to be
1376   // precise. That doesn't take part in the LibCall so we can't directly use
1377   // LowerF128Call.
1378   SDValue SrcVal = Op.getOperand(0);
1379   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1380                      /*isSigned*/ false, SDLoc(Op)).first;
1381 }
1382
1383 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1384   // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1385   // Any additional optimization in this function should be recorded
1386   // in the cost tables.
1387   EVT InVT = Op.getOperand(0).getValueType();
1388   EVT VT = Op.getValueType();
1389
1390   // FP_TO_XINT conversion from the same type are legal.
1391   if (VT.getSizeInBits() == InVT.getSizeInBits())
1392     return Op;
1393
1394   if (InVT == MVT::v2f64 || InVT == MVT::v4f32) {
1395     SDLoc dl(Op);
1396     SDValue Cv =
1397         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1398                     Op.getOperand(0));
1399     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1400   } else if (InVT == MVT::v2f32) {
1401     SDLoc dl(Op);
1402     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1403     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1404   }
1405
1406   // Type changing conversions are illegal.
1407   return SDValue();
1408 }
1409
1410 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1411                                             SelectionDAG &DAG) const {
1412   if (Op.getOperand(0).getValueType().isVector())
1413     return LowerVectorFP_TO_INT(Op, DAG);
1414
1415   if (Op.getOperand(0).getValueType() != MVT::f128) {
1416     // It's legal except when f128 is involved
1417     return Op;
1418   }
1419
1420   RTLIB::Libcall LC;
1421   if (Op.getOpcode() == ISD::FP_TO_SINT)
1422     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1423   else
1424     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1425
1426   SmallVector<SDValue, 2> Ops;
1427   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1428     Ops.push_back(Op.getOperand(i));
1429
1430   return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1431                      SDLoc(Op)).first;
1432 }
1433
1434 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1435   // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1436   // Any additional optimization in this function should be recorded
1437   // in the cost tables.
1438   EVT VT = Op.getValueType();
1439   SDLoc dl(Op);
1440   SDValue In = Op.getOperand(0);
1441   EVT InVT = In.getValueType();
1442
1443   // v2i32 to v2f32 is legal.
1444   if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1445     return Op;
1446
1447   // This function only handles v2f64 outputs.
1448   if (VT == MVT::v2f64) {
1449     // Extend the input argument to a v2i64 that we can feed into the
1450     // floating point conversion. Zero or sign extend based on whether
1451     // we're doing a signed or unsigned float conversion.
1452     unsigned Opc =
1453         Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1454     assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1455     SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1456     return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1457   }
1458
1459   // Scalarize v2i64 to v2f32 conversions.
1460   std::vector<SDValue> BuildVectorOps;
1461   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1462     SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1463                                DAG.getConstant(i, MVT::i64));
1464     Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1465     BuildVectorOps.push_back(Sclr);
1466   }
1467
1468   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, BuildVectorOps);
1469 }
1470
1471 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1472                                             SelectionDAG &DAG) const {
1473   if (Op.getValueType().isVector())
1474     return LowerVectorINT_TO_FP(Op, DAG);
1475
1476   // i128 conversions are libcalls.
1477   if (Op.getOperand(0).getValueType() == MVT::i128)
1478     return SDValue();
1479
1480   // Other conversions are legal, unless it's to the completely software-based
1481   // fp128.
1482   if (Op.getValueType() != MVT::f128)
1483     return Op;
1484
1485   RTLIB::Libcall LC;
1486   if (Op.getOpcode() == ISD::SINT_TO_FP)
1487     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1488   else
1489     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1490
1491   return LowerF128Call(Op, DAG, LC);
1492 }
1493
1494 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1495   // For iOS, we want to call an alternative entry point: __sincos_stret,
1496   // which returns the values in two S / D registers.
1497   SDLoc dl(Op);
1498   SDValue Arg = Op.getOperand(0);
1499   EVT ArgVT = Arg.getValueType();
1500   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1501
1502   ArgListTy Args;
1503   ArgListEntry Entry;
1504
1505   Entry.Node = Arg;
1506   Entry.Ty = ArgTy;
1507   Entry.isSExt = false;
1508   Entry.isZExt = false;
1509   Args.push_back(Entry);
1510
1511   const char *LibcallName =
1512       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1513   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1514
1515   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1516   TargetLowering::CallLoweringInfo CLI(
1517       DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1518       CallingConv::Fast, /*isTaillCall=*/false,
1519       /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1520   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1521   return CallResult.first;
1522 }
1523
1524 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1525                                             SelectionDAG &DAG) const {
1526   switch (Op.getOpcode()) {
1527   default:
1528     llvm_unreachable("unimplemented operand");
1529     return SDValue();
1530   case ISD::GlobalAddress:
1531     return LowerGlobalAddress(Op, DAG);
1532   case ISD::GlobalTLSAddress:
1533     return LowerGlobalTLSAddress(Op, DAG);
1534   case ISD::SETCC:
1535     return LowerSETCC(Op, DAG);
1536   case ISD::BR_CC:
1537     return LowerBR_CC(Op, DAG);
1538   case ISD::SELECT:
1539     return LowerSELECT(Op, DAG);
1540   case ISD::SELECT_CC:
1541     return LowerSELECT_CC(Op, DAG);
1542   case ISD::JumpTable:
1543     return LowerJumpTable(Op, DAG);
1544   case ISD::ConstantPool:
1545     return LowerConstantPool(Op, DAG);
1546   case ISD::BlockAddress:
1547     return LowerBlockAddress(Op, DAG);
1548   case ISD::VASTART:
1549     return LowerVASTART(Op, DAG);
1550   case ISD::VACOPY:
1551     return LowerVACOPY(Op, DAG);
1552   case ISD::VAARG:
1553     return LowerVAARG(Op, DAG);
1554   case ISD::ADDC:
1555   case ISD::ADDE:
1556   case ISD::SUBC:
1557   case ISD::SUBE:
1558     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1559   case ISD::SADDO:
1560   case ISD::UADDO:
1561   case ISD::SSUBO:
1562   case ISD::USUBO:
1563   case ISD::SMULO:
1564   case ISD::UMULO:
1565     return LowerXALUO(Op, DAG);
1566   case ISD::FADD:
1567     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1568   case ISD::FSUB:
1569     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1570   case ISD::FMUL:
1571     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1572   case ISD::FDIV:
1573     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1574   case ISD::FP_ROUND:
1575     return LowerFP_ROUND(Op, DAG);
1576   case ISD::FP_EXTEND:
1577     return LowerFP_EXTEND(Op, DAG);
1578   case ISD::FRAMEADDR:
1579     return LowerFRAMEADDR(Op, DAG);
1580   case ISD::RETURNADDR:
1581     return LowerRETURNADDR(Op, DAG);
1582   case ISD::INSERT_VECTOR_ELT:
1583     return LowerINSERT_VECTOR_ELT(Op, DAG);
1584   case ISD::EXTRACT_VECTOR_ELT:
1585     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1586   case ISD::BUILD_VECTOR:
1587     return LowerBUILD_VECTOR(Op, DAG);
1588   case ISD::VECTOR_SHUFFLE:
1589     return LowerVECTOR_SHUFFLE(Op, DAG);
1590   case ISD::EXTRACT_SUBVECTOR:
1591     return LowerEXTRACT_SUBVECTOR(Op, DAG);
1592   case ISD::SRA:
1593   case ISD::SRL:
1594   case ISD::SHL:
1595     return LowerVectorSRA_SRL_SHL(Op, DAG);
1596   case ISD::SHL_PARTS:
1597     return LowerShiftLeftParts(Op, DAG);
1598   case ISD::SRL_PARTS:
1599   case ISD::SRA_PARTS:
1600     return LowerShiftRightParts(Op, DAG);
1601   case ISD::CTPOP:
1602     return LowerCTPOP(Op, DAG);
1603   case ISD::FCOPYSIGN:
1604     return LowerFCOPYSIGN(Op, DAG);
1605   case ISD::AND:
1606     return LowerVectorAND(Op, DAG);
1607   case ISD::OR:
1608     return LowerVectorOR(Op, DAG);
1609   case ISD::XOR:
1610     return LowerXOR(Op, DAG);
1611   case ISD::PREFETCH:
1612     return LowerPREFETCH(Op, DAG);
1613   case ISD::SINT_TO_FP:
1614   case ISD::UINT_TO_FP:
1615     return LowerINT_TO_FP(Op, DAG);
1616   case ISD::FP_TO_SINT:
1617   case ISD::FP_TO_UINT:
1618     return LowerFP_TO_INT(Op, DAG);
1619   case ISD::FSINCOS:
1620     return LowerFSINCOS(Op, DAG);
1621   }
1622 }
1623
1624 /// getFunctionAlignment - Return the Log2 alignment of this function.
1625 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1626   return 2;
1627 }
1628
1629 //===----------------------------------------------------------------------===//
1630 //                      Calling Convention Implementation
1631 //===----------------------------------------------------------------------===//
1632
1633 #include "ARM64GenCallingConv.inc"
1634
1635 /// Selects the correct CCAssignFn for a the given CallingConvention
1636 /// value.
1637 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1638                                                    bool IsVarArg) const {
1639   switch (CC) {
1640   default:
1641     llvm_unreachable("Unsupported calling convention.");
1642   case CallingConv::WebKit_JS:
1643     return CC_ARM64_WebKit_JS;
1644   case CallingConv::C:
1645   case CallingConv::Fast:
1646     if (!Subtarget->isTargetDarwin())
1647       return CC_ARM64_AAPCS;
1648     return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1649   }
1650 }
1651
1652 SDValue ARM64TargetLowering::LowerFormalArguments(
1653     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1654     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1655     SmallVectorImpl<SDValue> &InVals) const {
1656   MachineFunction &MF = DAG.getMachineFunction();
1657   MachineFrameInfo *MFI = MF.getFrameInfo();
1658
1659   // Assign locations to all of the incoming arguments.
1660   SmallVector<CCValAssign, 16> ArgLocs;
1661   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1662                  getTargetMachine(), ArgLocs, *DAG.getContext());
1663
1664   // At this point, Ins[].VT may already be promoted to i32. To correctly
1665   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1666   // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1667   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1668   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1669   // LocVT.
1670   unsigned NumArgs = Ins.size();
1671   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1672   unsigned CurArgIdx = 0;
1673   for (unsigned i = 0; i != NumArgs; ++i) {
1674     MVT ValVT = Ins[i].VT;
1675     std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1676     CurArgIdx = Ins[i].OrigArgIndex;
1677
1678     // Get type of the original argument.
1679     EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1680     MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1681     // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1682     MVT LocVT = ValVT;
1683     if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1684       LocVT = MVT::i8;
1685     else if (ActualMVT == MVT::i16)
1686       LocVT = MVT::i16;
1687
1688     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1689     bool Res =
1690         AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1691     assert(!Res && "Call operand has unhandled type");
1692     (void)Res;
1693   }
1694   assert(ArgLocs.size() == Ins.size());
1695   SmallVector<SDValue, 16> ArgValues;
1696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1697     CCValAssign &VA = ArgLocs[i];
1698
1699     if (Ins[i].Flags.isByVal()) {
1700       // Byval is used for HFAs in the PCS, but the system should work in a
1701       // non-compliant manner for larger structs.
1702       EVT PtrTy = getPointerTy();
1703       int Size = Ins[i].Flags.getByValSize();
1704       unsigned NumRegs = (Size + 7) / 8;
1705
1706       // FIXME: This works on big-endian for composite byvals, which are the common
1707       // case. It should also work for fundamental types too.
1708       unsigned FrameIdx =
1709         MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1710       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1711       InVals.push_back(FrameIdxN);
1712
1713       continue;
1714     } if (VA.isRegLoc()) {
1715       // Arguments stored in registers.
1716       EVT RegVT = VA.getLocVT();
1717
1718       SDValue ArgValue;
1719       const TargetRegisterClass *RC;
1720
1721       if (RegVT == MVT::i32)
1722         RC = &ARM64::GPR32RegClass;
1723       else if (RegVT == MVT::i64)
1724         RC = &ARM64::GPR64RegClass;
1725       else if (RegVT == MVT::f32)
1726         RC = &ARM64::FPR32RegClass;
1727       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1728         RC = &ARM64::FPR64RegClass;
1729       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1730         RC = &ARM64::FPR128RegClass;
1731       else
1732         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1733
1734       // Transform the arguments in physical registers into virtual ones.
1735       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1736       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1737
1738       // If this is an 8, 16 or 32-bit value, it is really passed promoted
1739       // to 64 bits.  Insert an assert[sz]ext to capture this, then
1740       // truncate to the right size.
1741       switch (VA.getLocInfo()) {
1742       default:
1743         llvm_unreachable("Unknown loc info!");
1744       case CCValAssign::Full:
1745         break;
1746       case CCValAssign::BCvt:
1747         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1748         break;
1749       case CCValAssign::SExt:
1750         ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1751                                DAG.getValueType(VA.getValVT()));
1752         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1753         break;
1754       case CCValAssign::ZExt:
1755         ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1756                                DAG.getValueType(VA.getValVT()));
1757         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1758         break;
1759       }
1760
1761       InVals.push_back(ArgValue);
1762
1763     } else { // VA.isRegLoc()
1764       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1765       unsigned ArgOffset = VA.getLocMemOffset();
1766       unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1767
1768       uint32_t BEAlign = 0;
1769       if (ArgSize < 8 && !Subtarget->isLittleEndian())
1770         BEAlign = 8 - ArgSize;
1771
1772       int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
1773
1774       // Create load nodes to retrieve arguments from the stack.
1775       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1776       SDValue ArgValue;
1777
1778       // If the loc type and val type are not the same, create an anyext load.
1779       if (VA.getLocVT().getSizeInBits() != VA.getValVT().getSizeInBits()) {
1780         // We should only get here if this is a pure integer.
1781         assert(!VA.getValVT().isVector() && VA.getValVT().isInteger() &&
1782                "Only integer extension supported!");
1783         ArgValue = DAG.getExtLoad(ISD::EXTLOAD, DL, VA.getValVT(), Chain, FIN,
1784                                   MachinePointerInfo::getFixedStack(FI),
1785                                   VA.getLocVT(),
1786                                   false, false, false, 0);
1787       } else {
1788         ArgValue = DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1789                                MachinePointerInfo::getFixedStack(FI), false,
1790                                false, false, 0);
1791       }
1792
1793       InVals.push_back(ArgValue);
1794     }
1795   }
1796
1797   // varargs
1798   if (isVarArg) {
1799     if (!Subtarget->isTargetDarwin()) {
1800       // The AAPCS variadic function ABI is identical to the non-variadic
1801       // one. As a result there may be more arguments in registers and we should
1802       // save them for future reference.
1803       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1804     }
1805
1806     ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1807     // This will point to the next argument passed via stack.
1808     unsigned StackOffset = CCInfo.getNextStackOffset();
1809     // We currently pass all varargs at 8-byte alignment.
1810     StackOffset = ((StackOffset + 7) & ~7);
1811     AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1812   }
1813
1814   return Chain;
1815 }
1816
1817 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1818                                               SelectionDAG &DAG, SDLoc DL,
1819                                               SDValue &Chain) const {
1820   MachineFunction &MF = DAG.getMachineFunction();
1821   MachineFrameInfo *MFI = MF.getFrameInfo();
1822   ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1823
1824   SmallVector<SDValue, 8> MemOps;
1825
1826   static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1827                                           ARM64::X3, ARM64::X4, ARM64::X5,
1828                                           ARM64::X6, ARM64::X7 };
1829   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1830   unsigned FirstVariadicGPR =
1831       CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1832
1833   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1834   int GPRIdx = 0;
1835   if (GPRSaveSize != 0) {
1836     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1837
1838     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1839
1840     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1841       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1842       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1843       SDValue Store =
1844           DAG.getStore(Val.getValue(1), DL, Val, FIN,
1845                        MachinePointerInfo::getStack(i * 8), false, false, 0);
1846       MemOps.push_back(Store);
1847       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1848                         DAG.getConstant(8, getPointerTy()));
1849     }
1850   }
1851   FuncInfo->setVarArgsGPRIndex(GPRIdx);
1852   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1853
1854   if (Subtarget->hasFPARMv8()) {
1855     static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1856                                             ARM64::Q3, ARM64::Q4, ARM64::Q5,
1857                                             ARM64::Q6, ARM64::Q7 };
1858     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1859     unsigned FirstVariadicFPR =
1860         CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1861
1862     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1863     int FPRIdx = 0;
1864     if (FPRSaveSize != 0) {
1865       FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1866
1867       SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1868
1869       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1870         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1871         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
1872
1873         SDValue Store =
1874             DAG.getStore(Val.getValue(1), DL, Val, FIN,
1875                          MachinePointerInfo::getStack(i * 16), false, false, 0);
1876         MemOps.push_back(Store);
1877         FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1878                           DAG.getConstant(16, getPointerTy()));
1879       }
1880     }
1881     FuncInfo->setVarArgsFPRIndex(FPRIdx);
1882     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1883   }
1884
1885   if (!MemOps.empty()) {
1886     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1887   }
1888 }
1889
1890 /// LowerCallResult - Lower the result values of a call into the
1891 /// appropriate copies out of appropriate physical registers.
1892 SDValue ARM64TargetLowering::LowerCallResult(
1893     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1894     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1895     SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1896     SDValue ThisVal) const {
1897   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1898                                                          : RetCC_ARM64_AAPCS;
1899   // Assign locations to each value returned by this call.
1900   SmallVector<CCValAssign, 16> RVLocs;
1901   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1902                  getTargetMachine(), RVLocs, *DAG.getContext());
1903   CCInfo.AnalyzeCallResult(Ins, RetCC);
1904
1905   // Copy all of the result registers out of their specified physreg.
1906   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1907     CCValAssign VA = RVLocs[i];
1908
1909     // Pass 'this' value directly from the argument to return value, to avoid
1910     // reg unit interference
1911     if (i == 0 && isThisReturn) {
1912       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1913              "unexpected return calling convention register assignment");
1914       InVals.push_back(ThisVal);
1915       continue;
1916     }
1917
1918     SDValue Val =
1919         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1920     Chain = Val.getValue(1);
1921     InFlag = Val.getValue(2);
1922
1923     switch (VA.getLocInfo()) {
1924     default:
1925       llvm_unreachable("Unknown loc info!");
1926     case CCValAssign::Full:
1927       break;
1928     case CCValAssign::BCvt:
1929       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1930       break;
1931     }
1932
1933     InVals.push_back(Val);
1934   }
1935
1936   return Chain;
1937 }
1938
1939 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1940     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1941     bool isCalleeStructRet, bool isCallerStructRet,
1942     const SmallVectorImpl<ISD::OutputArg> &Outs,
1943     const SmallVectorImpl<SDValue> &OutVals,
1944     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1945   // Look for obvious safe cases to perform tail call optimization that do not
1946   // require ABI changes. This is what gcc calls sibcall.
1947
1948   // Do not sibcall optimize vararg calls unless the call site is not passing
1949   // any arguments.
1950   if (isVarArg && !Outs.empty())
1951     return false;
1952
1953   // Also avoid sibcall optimization if either caller or callee uses struct
1954   // return semantics.
1955   if (isCalleeStructRet || isCallerStructRet)
1956     return false;
1957
1958   // Note that currently ARM64 "C" calling convention and "Fast" calling
1959   // convention are compatible. If/when that ever changes, we'll need to
1960   // add checks here to make sure any interactions are OK.
1961
1962   // If the callee takes no arguments then go on to check the results of the
1963   // call.
1964   if (!Outs.empty()) {
1965     // Check if stack adjustment is needed. For now, do not do this if any
1966     // argument is passed on the stack.
1967     SmallVector<CCValAssign, 16> ArgLocs;
1968     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1969                    getTargetMachine(), ArgLocs, *DAG.getContext());
1970     CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1971     CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1972     if (CCInfo.getNextStackOffset()) {
1973       // Check if the arguments are already laid out in the right way as
1974       // the caller's fixed stack objects.
1975       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1976            ++i, ++realArgIdx) {
1977         CCValAssign &VA = ArgLocs[i];
1978         if (VA.getLocInfo() == CCValAssign::Indirect)
1979           return false;
1980         if (VA.needsCustom()) {
1981           // Just don't handle anything that needs custom adjustments for now.
1982           // If need be, we can revisit later, but we shouldn't ever end up
1983           // here.
1984           return false;
1985         } else if (!VA.isRegLoc()) {
1986           // Likewise, don't try to handle stack based arguments for the
1987           // time being.
1988           return false;
1989         }
1990       }
1991     }
1992   }
1993
1994   return true;
1995 }
1996 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1997 /// and add input and output parameter nodes.
1998 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1999                                        SmallVectorImpl<SDValue> &InVals) const {
2000   SelectionDAG &DAG = CLI.DAG;
2001   SDLoc &DL = CLI.DL;
2002   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2003   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2004   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2005   SDValue Chain = CLI.Chain;
2006   SDValue Callee = CLI.Callee;
2007   bool &IsTailCall = CLI.IsTailCall;
2008   CallingConv::ID CallConv = CLI.CallConv;
2009   bool IsVarArg = CLI.IsVarArg;
2010
2011   MachineFunction &MF = DAG.getMachineFunction();
2012   bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2013   bool IsThisReturn = false;
2014
2015   // If tail calls are explicitly disabled, make sure not to use them.
2016   if (!EnableARM64TailCalls)
2017     IsTailCall = false;
2018
2019   if (IsTailCall) {
2020     // Check if it's really possible to do a tail call.
2021     IsTailCall = isEligibleForTailCallOptimization(
2022         Callee, CallConv, IsVarArg, IsStructRet,
2023         MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2024     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2025       report_fatal_error("failed to perform tail call elimination on a call "
2026                          "site marked musttail");
2027     // We don't support GuaranteedTailCallOpt, only automatically
2028     // detected sibcalls.
2029     // FIXME: Re-evaluate. Is this true? Should it be true?
2030     if (IsTailCall)
2031       ++NumTailCalls;
2032   }
2033
2034   // Analyze operands of the call, assigning locations to each operand.
2035   SmallVector<CCValAssign, 16> ArgLocs;
2036   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2037                  getTargetMachine(), ArgLocs, *DAG.getContext());
2038
2039   if (IsVarArg) {
2040     // Handle fixed and variable vector arguments differently.
2041     // Variable vector arguments always go into memory.
2042     unsigned NumArgs = Outs.size();
2043
2044     for (unsigned i = 0; i != NumArgs; ++i) {
2045       MVT ArgVT = Outs[i].VT;
2046       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2047       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2048                                                /*IsVarArg=*/ !Outs[i].IsFixed);
2049       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2050       assert(!Res && "Call operand has unhandled type");
2051       (void)Res;
2052     }
2053   } else {
2054     // At this point, Outs[].VT may already be promoted to i32. To correctly
2055     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2056     // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2057     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2058     // we use a special version of AnalyzeCallOperands to pass in ValVT and
2059     // LocVT.
2060     unsigned NumArgs = Outs.size();
2061     for (unsigned i = 0; i != NumArgs; ++i) {
2062       MVT ValVT = Outs[i].VT;
2063       // Get type of the original argument.
2064       EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2065                                   /*AllowUnknown*/ true);
2066       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2067       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2068       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2069       MVT LocVT = ValVT;
2070       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2071         LocVT = MVT::i8;
2072       else if (ActualMVT == MVT::i16)
2073         LocVT = MVT::i16;
2074
2075       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2076       bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2077       assert(!Res && "Call operand has unhandled type");
2078       (void)Res;
2079     }
2080   }
2081
2082   // Get a count of how many bytes are to be pushed on the stack.
2083   unsigned NumBytes = CCInfo.getNextStackOffset();
2084
2085   // Adjust the stack pointer for the new arguments...
2086   // These operations are automatically eliminated by the prolog/epilog pass
2087   if (!IsTailCall)
2088     Chain =
2089         DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2090
2091   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2092
2093   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2094   SmallVector<SDValue, 8> MemOpChains;
2095
2096   // Walk the register/memloc assignments, inserting copies/loads.
2097   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2098        ++i, ++realArgIdx) {
2099     CCValAssign &VA = ArgLocs[i];
2100     SDValue Arg = OutVals[realArgIdx];
2101     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2102
2103     // Promote the value if needed.
2104     switch (VA.getLocInfo()) {
2105     default:
2106       llvm_unreachable("Unknown loc info!");
2107     case CCValAssign::Full:
2108       break;
2109     case CCValAssign::SExt:
2110       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2111       break;
2112     case CCValAssign::ZExt:
2113       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2114       break;
2115     case CCValAssign::AExt:
2116       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2117       break;
2118     case CCValAssign::BCvt:
2119       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2120       break;
2121     case CCValAssign::FPExt:
2122       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2123       break;
2124     }
2125
2126     if (VA.isRegLoc()) {
2127       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2128         assert(VA.getLocVT() == MVT::i64 &&
2129                "unexpected calling convention register assignment");
2130         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2131                "unexpected use of 'returned'");
2132         IsThisReturn = true;
2133       }
2134       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2135     } else {
2136       assert(VA.isMemLoc());
2137       // There's no reason we can't support stack args w/ tailcall, but
2138       // we currently don't, so assert if we see one.
2139       assert(!IsTailCall && "stack argument with tail call!?");
2140
2141       // FIXME: This works on big-endian for composite byvals, which are the common
2142       // case. It should also work for fundamental types too.
2143       uint32_t BEAlign = 0;
2144       if (!Subtarget->isLittleEndian() && !Flags.isByVal()) {
2145         unsigned OpSize = (VA.getLocVT().getSizeInBits() + 7) / 8;
2146         if (OpSize < 8)
2147           BEAlign = 8 - OpSize;
2148       }
2149
2150       unsigned LocMemOffset = VA.getLocMemOffset();
2151       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset + BEAlign);
2152       PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2153
2154       if (Outs[i].Flags.isByVal()) {
2155         SDValue SizeNode =
2156             DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2157         SDValue Cpy = DAG.getMemcpy(
2158             Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2159             /*isVolatile = */ false,
2160             /*alwaysInline = */ false,
2161             MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2162
2163         MemOpChains.push_back(Cpy);
2164       } else {
2165         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2166         // promoted to a legal register type i32, we should truncate Arg back to
2167         // i1/i8/i16.
2168         if (Arg.getValueType().isSimple() &&
2169             Arg.getValueType().getSimpleVT() == MVT::i32 &&
2170             (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2171              VA.getLocVT() == MVT::i16))
2172           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2173
2174         SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2175                                      MachinePointerInfo::getStack(LocMemOffset),
2176                                      false, false, 0);
2177         MemOpChains.push_back(Store);
2178       }
2179     }
2180   }
2181
2182   if (!MemOpChains.empty())
2183     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2184
2185   // Build a sequence of copy-to-reg nodes chained together with token chain
2186   // and flag operands which copy the outgoing args into the appropriate regs.
2187   SDValue InFlag;
2188   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2189     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2190                              RegsToPass[i].second, InFlag);
2191     InFlag = Chain.getValue(1);
2192   }
2193
2194   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2195   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2196   // node so that legalize doesn't hack it.
2197   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2198       Subtarget->isTargetMachO()) {
2199     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2200       const GlobalValue *GV = G->getGlobal();
2201       bool InternalLinkage = GV->hasInternalLinkage();
2202       if (InternalLinkage)
2203         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2204       else {
2205         Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2206                                             ARM64II::MO_GOT);
2207         Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2208       }
2209     } else if (ExternalSymbolSDNode *S =
2210                    dyn_cast<ExternalSymbolSDNode>(Callee)) {
2211       const char *Sym = S->getSymbol();
2212       Callee =
2213           DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2214       Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2215     }
2216   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2217     const GlobalValue *GV = G->getGlobal();
2218     Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2219   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2220     const char *Sym = S->getSymbol();
2221     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2222   }
2223
2224   std::vector<SDValue> Ops;
2225   Ops.push_back(Chain);
2226   Ops.push_back(Callee);
2227
2228   // Add argument registers to the end of the list so that they are known live
2229   // into the call.
2230   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2231     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2232                                   RegsToPass[i].second.getValueType()));
2233
2234   // Add a register mask operand representing the call-preserved registers.
2235   const uint32_t *Mask;
2236   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2237   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2238   if (IsThisReturn) {
2239     // For 'this' returns, use the X0-preserving mask if applicable
2240     Mask = ARI->getThisReturnPreservedMask(CallConv);
2241     if (!Mask) {
2242       IsThisReturn = false;
2243       Mask = ARI->getCallPreservedMask(CallConv);
2244     }
2245   } else
2246     Mask = ARI->getCallPreservedMask(CallConv);
2247
2248   assert(Mask && "Missing call preserved mask for calling convention");
2249   Ops.push_back(DAG.getRegisterMask(Mask));
2250
2251   if (InFlag.getNode())
2252     Ops.push_back(InFlag);
2253
2254   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2255
2256   // If we're doing a tall call, use a TC_RETURN here rather than an
2257   // actual call instruction.
2258   if (IsTailCall)
2259     return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, Ops);
2260
2261   // Returns a chain and a flag for retval copy to use.
2262   Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, Ops);
2263   InFlag = Chain.getValue(1);
2264
2265   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2266                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2267   if (!Ins.empty())
2268     InFlag = Chain.getValue(1);
2269
2270   // Handle result values, copying them out of physregs into vregs that we
2271   // return.
2272   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2273                          InVals, IsThisReturn,
2274                          IsThisReturn ? OutVals[0] : SDValue());
2275 }
2276
2277 bool ARM64TargetLowering::CanLowerReturn(
2278     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2279     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2280   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2281                                                          : RetCC_ARM64_AAPCS;
2282   SmallVector<CCValAssign, 16> RVLocs;
2283   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2284   return CCInfo.CheckReturn(Outs, RetCC);
2285 }
2286
2287 SDValue
2288 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2289                                  bool isVarArg,
2290                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2291                                  const SmallVectorImpl<SDValue> &OutVals,
2292                                  SDLoc DL, SelectionDAG &DAG) const {
2293   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2294                                                          : RetCC_ARM64_AAPCS;
2295   SmallVector<CCValAssign, 16> RVLocs;
2296   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2297                  getTargetMachine(), RVLocs, *DAG.getContext());
2298   CCInfo.AnalyzeReturn(Outs, RetCC);
2299
2300   // Copy the result values into the output registers.
2301   SDValue Flag;
2302   SmallVector<SDValue, 4> RetOps(1, Chain);
2303   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2304        ++i, ++realRVLocIdx) {
2305     CCValAssign &VA = RVLocs[i];
2306     assert(VA.isRegLoc() && "Can only return in registers!");
2307     SDValue Arg = OutVals[realRVLocIdx];
2308
2309     switch (VA.getLocInfo()) {
2310     default:
2311       llvm_unreachable("Unknown loc info!");
2312     case CCValAssign::Full:
2313       break;
2314     case CCValAssign::BCvt:
2315       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2316       break;
2317     }
2318
2319     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2320     Flag = Chain.getValue(1);
2321     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2322   }
2323
2324   RetOps[0] = Chain; // Update chain.
2325
2326   // Add the flag if we have it.
2327   if (Flag.getNode())
2328     RetOps.push_back(Flag);
2329
2330   return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2331 }
2332
2333 //===----------------------------------------------------------------------===//
2334 //  Other Lowering Code
2335 //===----------------------------------------------------------------------===//
2336
2337 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2338                                                 SelectionDAG &DAG) const {
2339   EVT PtrVT = getPointerTy();
2340   SDLoc DL(Op);
2341   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2342   unsigned char OpFlags =
2343       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2344
2345   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2346          "unexpected offset in global node");
2347
2348   // This also catched the large code model case for Darwin.
2349   if ((OpFlags & ARM64II::MO_GOT) != 0) {
2350     SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2351     // FIXME: Once remat is capable of dealing with instructions with register
2352     // operands, expand this into two nodes instead of using a wrapper node.
2353     return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2354   }
2355
2356   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2357     const unsigned char MO_NC = ARM64II::MO_NC;
2358     return DAG.getNode(
2359         ARM64ISD::WrapperLarge, DL, PtrVT,
2360         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2361         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2362         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2363         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2364   } else {
2365     // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2366     // the only correct model on Darwin.
2367     SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2368                                             OpFlags | ARM64II::MO_PAGE);
2369     unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2370     SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2371
2372     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2373     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2374   }
2375 }
2376
2377 /// \brief Convert a TLS address reference into the correct sequence of loads
2378 /// and calls to compute the variable's address (for Darwin, currently) and
2379 /// return an SDValue containing the final node.
2380
2381 /// Darwin only has one TLS scheme which must be capable of dealing with the
2382 /// fully general situation, in the worst case. This means:
2383 ///     + "extern __thread" declaration.
2384 ///     + Defined in a possibly unknown dynamic library.
2385 ///
2386 /// The general system is that each __thread variable has a [3 x i64] descriptor
2387 /// which contains information used by the runtime to calculate the address. The
2388 /// only part of this the compiler needs to know about is the first xword, which
2389 /// contains a function pointer that must be called with the address of the
2390 /// entire descriptor in "x0".
2391 ///
2392 /// Since this descriptor may be in a different unit, in general even the
2393 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2394 /// is:
2395 ///     adrp x0, _var@TLVPPAGE
2396 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
2397 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
2398 ///                                      ; the function pointer
2399 ///     blr x1                           ; Uses descriptor address in x0
2400 ///     ; Address of _var is now in x0.
2401 ///
2402 /// If the address of _var's descriptor *is* known to the linker, then it can
2403 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2404 /// a slight efficiency gain.
2405 SDValue
2406 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2407                                                  SelectionDAG &DAG) const {
2408   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2409
2410   SDLoc DL(Op);
2411   MVT PtrVT = getPointerTy();
2412   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2413
2414   SDValue TLVPAddr =
2415       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2416   SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2417
2418   // The first entry in the descriptor is a function pointer that we must call
2419   // to obtain the address of the variable.
2420   SDValue Chain = DAG.getEntryNode();
2421   SDValue FuncTLVGet =
2422       DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2423                   false, true, true, 8);
2424   Chain = FuncTLVGet.getValue(1);
2425
2426   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2427   MFI->setAdjustsStack(true);
2428
2429   // TLS calls preserve all registers except those that absolutely must be
2430   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2431   // silly).
2432   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2433   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2434   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2435
2436   // Finally, we can make the call. This is just a degenerate version of a
2437   // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2438   // the address of the variable in this thread.
2439   Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2440   Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2441                       Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2442                       DAG.getRegisterMask(Mask), Chain.getValue(1));
2443   return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2444 }
2445
2446 /// When accessing thread-local variables under either the general-dynamic or
2447 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2448 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2449 /// is a function pointer to carry out the resolution. This function takes the
2450 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2451 /// other registers (except LR, NZCV) are preserved.
2452 ///
2453 /// Thus, the ideal call sequence on AArch64 is:
2454 ///
2455 ///     adrp x0, :tlsdesc:thread_var
2456 ///     ldr x8, [x0, :tlsdesc_lo12:thread_var]
2457 ///     add x0, x0, :tlsdesc_lo12:thread_var
2458 ///     .tlsdesccall thread_var
2459 ///     blr x8
2460 ///     (TPIDR_EL0 offset now in x0).
2461 ///
2462 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2463 /// relocation to help the linker relax this sequence if it turns out to be too
2464 /// conservative.
2465 ///
2466 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2467 /// is harmless.
2468 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2469                                                  SDValue DescAddr, SDLoc DL,
2470                                                  SelectionDAG &DAG) const {
2471   EVT PtrVT = getPointerTy();
2472
2473   // The function we need to call is simply the first entry in the GOT for this
2474   // descriptor, load it in preparation.
2475   SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2476
2477   // TLS calls preserve all registers except those that absolutely must be
2478   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2479   // silly).
2480   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2481   const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2482   const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2483
2484   // The function takes only one argument: the address of the descriptor itself
2485   // in X0.
2486   SDValue Glue, Chain;
2487   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2488   Glue = Chain.getValue(1);
2489
2490   // We're now ready to populate the argument list, as with a normal call:
2491   SmallVector<SDValue, 6> Ops;
2492   Ops.push_back(Chain);
2493   Ops.push_back(Func);
2494   Ops.push_back(SymAddr);
2495   Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2496   Ops.push_back(DAG.getRegisterMask(Mask));
2497   Ops.push_back(Glue);
2498
2499   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2500   Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2501   Glue = Chain.getValue(1);
2502
2503   return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2504 }
2505
2506 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2507                                                       SelectionDAG &DAG) const {
2508   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2509   assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2510          "ELF TLS only supported in small memory model");
2511   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2512
2513   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2514
2515   SDValue TPOff;
2516   EVT PtrVT = getPointerTy();
2517   SDLoc DL(Op);
2518   const GlobalValue *GV = GA->getGlobal();
2519
2520   SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2521
2522   if (Model == TLSModel::LocalExec) {
2523     SDValue HiVar = DAG.getTargetGlobalAddress(
2524         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2525     SDValue LoVar = DAG.getTargetGlobalAddress(
2526         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2527
2528     TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2529                                        DAG.getTargetConstant(16, MVT::i32)),
2530                     0);
2531     TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2532                                        DAG.getTargetConstant(0, MVT::i32)),
2533                     0);
2534   } else if (Model == TLSModel::InitialExec) {
2535     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2536     TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2537   } else if (Model == TLSModel::LocalDynamic) {
2538     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2539     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2540     // the beginning of the module's TLS region, followed by a DTPREL offset
2541     // calculation.
2542
2543     // These accesses will need deduplicating if there's more than one.
2544     ARM64FunctionInfo *MFI =
2545         DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2546     MFI->incNumLocalDynamicTLSAccesses();
2547
2548     // Accesses used in this sequence go via the TLS descriptor which lives in
2549     // the GOT. Prepare an address we can use to handle this.
2550     SDValue HiDesc = DAG.getTargetExternalSymbol(
2551         "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2552     SDValue LoDesc = DAG.getTargetExternalSymbol(
2553         "_TLS_MODULE_BASE_", PtrVT,
2554         ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2555
2556     // First argument to the descriptor call is the address of the descriptor
2557     // itself.
2558     SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2559     DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2560
2561     // The call needs a relocation too for linker relaxation. It doesn't make
2562     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2563     // the address.
2564     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2565                                                   ARM64II::MO_TLS);
2566
2567     // Now we can calculate the offset from TPIDR_EL0 to this module's
2568     // thread-local area.
2569     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2570
2571     // Now use :dtprel_whatever: operations to calculate this variable's offset
2572     // in its thread-storage area.
2573     SDValue HiVar = DAG.getTargetGlobalAddress(
2574         GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2575     SDValue LoVar = DAG.getTargetGlobalAddress(
2576         GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2577
2578     SDValue DTPOff =
2579         SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2580                                    DAG.getTargetConstant(16, MVT::i32)),
2581                 0);
2582     DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2583                                         DAG.getTargetConstant(0, MVT::i32)),
2584                      0);
2585
2586     TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2587   } else if (Model == TLSModel::GeneralDynamic) {
2588     // Accesses used in this sequence go via the TLS descriptor which lives in
2589     // the GOT. Prepare an address we can use to handle this.
2590     SDValue HiDesc = DAG.getTargetGlobalAddress(
2591         GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2592     SDValue LoDesc = DAG.getTargetGlobalAddress(
2593         GV, DL, PtrVT, 0,
2594         ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2595
2596     // First argument to the descriptor call is the address of the descriptor
2597     // itself.
2598     SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2599     DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2600
2601     // The call needs a relocation too for linker relaxation. It doesn't make
2602     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2603     // the address.
2604     SDValue SymAddr =
2605         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2606
2607     // Finally we can make a call to calculate the offset from tpidr_el0.
2608     TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2609   } else
2610     llvm_unreachable("Unsupported ELF TLS access model");
2611
2612   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2613 }
2614
2615 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2616                                                    SelectionDAG &DAG) const {
2617   if (Subtarget->isTargetDarwin())
2618     return LowerDarwinGlobalTLSAddress(Op, DAG);
2619   else if (Subtarget->isTargetELF())
2620     return LowerELFGlobalTLSAddress(Op, DAG);
2621
2622   llvm_unreachable("Unexpected platform trying to use TLS");
2623 }
2624 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2625   SDValue Chain = Op.getOperand(0);
2626   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2627   SDValue LHS = Op.getOperand(2);
2628   SDValue RHS = Op.getOperand(3);
2629   SDValue Dest = Op.getOperand(4);
2630   SDLoc dl(Op);
2631
2632   // Handle f128 first, since lowering it will result in comparing the return
2633   // value of a libcall against zero, which is just what the rest of LowerBR_CC
2634   // is expecting to deal with.
2635   if (LHS.getValueType() == MVT::f128) {
2636     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2637
2638     // If softenSetCCOperands returned a scalar, we need to compare the result
2639     // against zero to select between true and false values.
2640     if (!RHS.getNode()) {
2641       RHS = DAG.getConstant(0, LHS.getValueType());
2642       CC = ISD::SETNE;
2643     }
2644   }
2645
2646   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2647   // instruction.
2648   unsigned Opc = LHS.getOpcode();
2649   if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2650       cast<ConstantSDNode>(RHS)->isOne() &&
2651       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2652        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2653     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2654            "Unexpected condition code.");
2655     // Only lower legal XALUO ops.
2656     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2657       return SDValue();
2658
2659     // The actual operation with overflow check.
2660     ARM64CC::CondCode OFCC;
2661     SDValue Value, Overflow;
2662     std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2663
2664     if (CC == ISD::SETNE)
2665       OFCC = getInvertedCondCode(OFCC);
2666     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2667
2668     return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2669                        CCVal, Overflow);
2670   }
2671
2672   if (LHS.getValueType().isInteger()) {
2673     assert((LHS.getValueType() == RHS.getValueType()) &&
2674            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2675
2676     // If the RHS of the comparison is zero, we can potentially fold this
2677     // to a specialized branch.
2678     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2679     if (RHSC && RHSC->getZExtValue() == 0) {
2680       if (CC == ISD::SETEQ) {
2681         // See if we can use a TBZ to fold in an AND as well.
2682         // TBZ has a smaller branch displacement than CBZ.  If the offset is
2683         // out of bounds, a late MI-layer pass rewrites branches.
2684         // 403.gcc is an example that hits this case.
2685         if (LHS.getOpcode() == ISD::AND &&
2686             isa<ConstantSDNode>(LHS.getOperand(1)) &&
2687             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2688           SDValue Test = LHS.getOperand(0);
2689           uint64_t Mask = LHS.getConstantOperandVal(1);
2690
2691           // TBZ only operates on i64's, but the ext should be free.
2692           if (Test.getValueType() == MVT::i32)
2693             Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2694
2695           return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2696                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2697         }
2698
2699         return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2700       } else if (CC == ISD::SETNE) {
2701         // See if we can use a TBZ to fold in an AND as well.
2702         // TBZ has a smaller branch displacement than CBZ.  If the offset is
2703         // out of bounds, a late MI-layer pass rewrites branches.
2704         // 403.gcc is an example that hits this case.
2705         if (LHS.getOpcode() == ISD::AND &&
2706             isa<ConstantSDNode>(LHS.getOperand(1)) &&
2707             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2708           SDValue Test = LHS.getOperand(0);
2709           uint64_t Mask = LHS.getConstantOperandVal(1);
2710
2711           // TBNZ only operates on i64's, but the ext should be free.
2712           if (Test.getValueType() == MVT::i32)
2713             Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2714
2715           return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2716                              DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2717         }
2718
2719         return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2720       }
2721     }
2722
2723     SDValue CCVal;
2724     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2725     return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2726                        Cmp);
2727   }
2728
2729   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2730
2731   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2732   // clean.  Some of them require two branches to implement.
2733   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2734   ARM64CC::CondCode CC1, CC2;
2735   changeFPCCToARM64CC(CC, CC1, CC2);
2736   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2737   SDValue BR1 =
2738       DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2739   if (CC2 != ARM64CC::AL) {
2740     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2741     return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2742                        Cmp);
2743   }
2744
2745   return BR1;
2746 }
2747
2748 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2749                                             SelectionDAG &DAG) const {
2750   EVT VT = Op.getValueType();
2751   SDLoc DL(Op);
2752
2753   SDValue In1 = Op.getOperand(0);
2754   SDValue In2 = Op.getOperand(1);
2755   EVT SrcVT = In2.getValueType();
2756   if (SrcVT != VT) {
2757     if (SrcVT == MVT::f32 && VT == MVT::f64)
2758       In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2759     else if (SrcVT == MVT::f64 && VT == MVT::f32)
2760       In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2761     else
2762       // FIXME: Src type is different, bail out for now. Can VT really be a
2763       // vector type?
2764       return SDValue();
2765   }
2766
2767   EVT VecVT;
2768   EVT EltVT;
2769   SDValue EltMask, VecVal1, VecVal2;
2770   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2771     EltVT = MVT::i32;
2772     VecVT = MVT::v4i32;
2773     EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2774
2775     if (!VT.isVector()) {
2776       VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2777                                           DAG.getUNDEF(VecVT), In1);
2778       VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2779                                           DAG.getUNDEF(VecVT), In2);
2780     } else {
2781       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2782       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2783     }
2784   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2785     EltVT = MVT::i64;
2786     VecVT = MVT::v2i64;
2787
2788     // We want to materialize a mask with the the high bit set, but the AdvSIMD
2789     // immediate moves cannot materialize that in a single instruction for
2790     // 64-bit elements. Instead, materialize zero and then negate it.
2791     EltMask = DAG.getConstant(0, EltVT);
2792
2793     if (!VT.isVector()) {
2794       VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2795                                           DAG.getUNDEF(VecVT), In1);
2796       VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2797                                           DAG.getUNDEF(VecVT), In2);
2798     } else {
2799       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2800       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2801     }
2802   } else {
2803     llvm_unreachable("Invalid type for copysign!");
2804   }
2805
2806   std::vector<SDValue> BuildVectorOps;
2807   for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2808     BuildVectorOps.push_back(EltMask);
2809
2810   SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
2811
2812   // If we couldn't materialize the mask above, then the mask vector will be
2813   // the zero vector, and we need to negate it here.
2814   if (VT == MVT::f64 || VT == MVT::v2f64) {
2815     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2816     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2817     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2818   }
2819
2820   SDValue Sel =
2821       DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2822
2823   if (VT == MVT::f32)
2824     return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2825   else if (VT == MVT::f64)
2826     return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2827   else
2828     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2829 }
2830
2831 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2832   if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2833           AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2834     return SDValue();
2835
2836   // While there is no integer popcount instruction, it can
2837   // be more efficiently lowered to the following sequence that uses
2838   // AdvSIMD registers/instructions as long as the copies to/from
2839   // the AdvSIMD registers are cheap.
2840   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
2841   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
2842   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
2843   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
2844   SDValue Val = Op.getOperand(0);
2845   SDLoc DL(Op);
2846   EVT VT = Op.getValueType();
2847   SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2848
2849   SDValue VecVal;
2850   if (VT == MVT::i32) {
2851     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2852     VecVal =
2853         DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2854   } else {
2855     VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2856   }
2857
2858   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2859   SDValue UaddLV = DAG.getNode(
2860       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2861       DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2862
2863   if (VT == MVT::i64)
2864     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2865   return UaddLV;
2866 }
2867
2868 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2869
2870   if (Op.getValueType().isVector())
2871     return LowerVSETCC(Op, DAG);
2872
2873   SDValue LHS = Op.getOperand(0);
2874   SDValue RHS = Op.getOperand(1);
2875   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2876   SDLoc dl(Op);
2877
2878   // We chose ZeroOrOneBooleanContents, so use zero and one.
2879   EVT VT = Op.getValueType();
2880   SDValue TVal = DAG.getConstant(1, VT);
2881   SDValue FVal = DAG.getConstant(0, VT);
2882
2883   // Handle f128 first, since one possible outcome is a normal integer
2884   // comparison which gets picked up by the next if statement.
2885   if (LHS.getValueType() == MVT::f128) {
2886     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2887
2888     // If softenSetCCOperands returned a scalar, use it.
2889     if (!RHS.getNode()) {
2890       assert(LHS.getValueType() == Op.getValueType() &&
2891              "Unexpected setcc expansion!");
2892       return LHS;
2893     }
2894   }
2895
2896   if (LHS.getValueType().isInteger()) {
2897     SDValue CCVal;
2898     SDValue Cmp =
2899         getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2900
2901     // Note that we inverted the condition above, so we reverse the order of
2902     // the true and false operands here.  This will allow the setcc to be
2903     // matched to a single CSINC instruction.
2904     return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2905   }
2906
2907   // Now we know we're dealing with FP values.
2908   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2909
2910   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
2911   // and do the comparison.
2912   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2913
2914   ARM64CC::CondCode CC1, CC2;
2915   changeFPCCToARM64CC(CC, CC1, CC2);
2916   if (CC2 == ARM64CC::AL) {
2917     changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2918     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2919
2920     // Note that we inverted the condition above, so we reverse the order of
2921     // the true and false operands here.  This will allow the setcc to be
2922     // matched to a single CSINC instruction.
2923     return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2924   } else {
2925     // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2926     // clean.  Some of them require two CSELs to implement.  As is in this case,
2927     // we emit the first CSEL and then emit a second using the output of the
2928     // first as the RHS.  We're effectively OR'ing the two CC's together.
2929
2930     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2931     SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2932     SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2933
2934     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2935     return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2936   }
2937 }
2938
2939 /// A SELECT_CC operation is really some kind of max or min if both values being
2940 /// compared are, in some sense, equal to the results in either case. However,
2941 /// it is permissible to compare f32 values and produce directly extended f64
2942 /// values.
2943 ///
2944 /// Extending the comparison operands would also be allowed, but is less likely
2945 /// to happen in practice since their use is right here. Note that truncate
2946 /// operations would *not* be semantically equivalent.
2947 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2948   if (Cmp == Result)
2949     return true;
2950
2951   ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2952   ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2953   if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2954       Result.getValueType() == MVT::f64) {
2955     bool Lossy;
2956     APFloat CmpVal = CCmp->getValueAPF();
2957     CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2958     return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2959   }
2960
2961   return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2962 }
2963
2964 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2965   SDValue CC = Op->getOperand(0);
2966   SDValue TVal = Op->getOperand(1);
2967   SDValue FVal = Op->getOperand(2);
2968   SDLoc DL(Op);
2969
2970   unsigned Opc = CC.getOpcode();
2971   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2972   // instruction.
2973   if (CC.getResNo() == 1 &&
2974       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2975        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2976     // Only lower legal XALUO ops.
2977     if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2978       return SDValue();
2979
2980     ARM64CC::CondCode OFCC;
2981     SDValue Value, Overflow;
2982     std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2983     SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2984
2985     return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2986                        Overflow);
2987   }
2988
2989   if (CC.getOpcode() == ISD::SETCC)
2990     return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2991                            cast<CondCodeSDNode>(CC.getOperand(2))->get());
2992   else
2993     return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2994                            FVal, ISD::SETNE);
2995 }
2996
2997 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2998                                             SelectionDAG &DAG) const {
2999   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3000   SDValue LHS = Op.getOperand(0);
3001   SDValue RHS = Op.getOperand(1);
3002   SDValue TVal = Op.getOperand(2);
3003   SDValue FVal = Op.getOperand(3);
3004   SDLoc dl(Op);
3005
3006   // Handle f128 first, because it will result in a comparison of some RTLIB
3007   // call result against zero.
3008   if (LHS.getValueType() == MVT::f128) {
3009     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3010
3011     // If softenSetCCOperands returned a scalar, we need to compare the result
3012     // against zero to select between true and false values.
3013     if (!RHS.getNode()) {
3014       RHS = DAG.getConstant(0, LHS.getValueType());
3015       CC = ISD::SETNE;
3016     }
3017   }
3018
3019   // Handle integers first.
3020   if (LHS.getValueType().isInteger()) {
3021     assert((LHS.getValueType() == RHS.getValueType()) &&
3022            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3023
3024     unsigned Opcode = ARM64ISD::CSEL;
3025
3026     // If both the TVal and the FVal are constants, see if we can swap them in
3027     // order to for a CSINV or CSINC out of them.
3028     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3029     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3030
3031     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3032       std::swap(TVal, FVal);
3033       std::swap(CTVal, CFVal);
3034       CC = ISD::getSetCCInverse(CC, true);
3035     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3036       std::swap(TVal, FVal);
3037       std::swap(CTVal, CFVal);
3038       CC = ISD::getSetCCInverse(CC, true);
3039     } else if (TVal.getOpcode() == ISD::XOR) {
3040       // If TVal is a NOT we want to swap TVal and FVal so that we can match
3041       // with a CSINV rather than a CSEL.
3042       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3043
3044       if (CVal && CVal->isAllOnesValue()) {
3045         std::swap(TVal, FVal);
3046         std::swap(CTVal, CFVal);
3047         CC = ISD::getSetCCInverse(CC, true);
3048       }
3049     } else if (TVal.getOpcode() == ISD::SUB) {
3050       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3051       // that we can match with a CSNEG rather than a CSEL.
3052       ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3053
3054       if (CVal && CVal->isNullValue()) {
3055         std::swap(TVal, FVal);
3056         std::swap(CTVal, CFVal);
3057         CC = ISD::getSetCCInverse(CC, true);
3058       }
3059     } else if (CTVal && CFVal) {
3060       const int64_t TrueVal = CTVal->getSExtValue();
3061       const int64_t FalseVal = CFVal->getSExtValue();
3062       bool Swap = false;
3063
3064       // If both TVal and FVal are constants, see if FVal is the
3065       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3066       // instead of a CSEL in that case.
3067       if (TrueVal == ~FalseVal) {
3068         Opcode = ARM64ISD::CSINV;
3069       } else if (TrueVal == -FalseVal) {
3070         Opcode = ARM64ISD::CSNEG;
3071       } else if (TVal.getValueType() == MVT::i32) {
3072         // If our operands are only 32-bit wide, make sure we use 32-bit
3073         // arithmetic for the check whether we can use CSINC. This ensures that
3074         // the addition in the check will wrap around properly in case there is
3075         // an overflow (which would not be the case if we do the check with
3076         // 64-bit arithmetic).
3077         const uint32_t TrueVal32 = CTVal->getZExtValue();
3078         const uint32_t FalseVal32 = CFVal->getZExtValue();
3079
3080         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3081           Opcode = ARM64ISD::CSINC;
3082
3083           if (TrueVal32 > FalseVal32) {
3084             Swap = true;
3085           }
3086         }
3087         // 64-bit check whether we can use CSINC.
3088       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3089         Opcode = ARM64ISD::CSINC;
3090
3091         if (TrueVal > FalseVal) {
3092           Swap = true;
3093         }
3094       }
3095
3096       // Swap TVal and FVal if necessary.
3097       if (Swap) {
3098         std::swap(TVal, FVal);
3099         std::swap(CTVal, CFVal);
3100         CC = ISD::getSetCCInverse(CC, true);
3101       }
3102
3103       if (Opcode != ARM64ISD::CSEL) {
3104         // Drop FVal since we can get its value by simply inverting/negating
3105         // TVal.
3106         FVal = TVal;
3107       }
3108     }
3109
3110     SDValue CCVal;
3111     SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3112
3113     EVT VT = Op.getValueType();
3114     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3115   }
3116
3117   // Now we know we're dealing with FP values.
3118   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3119   assert(LHS.getValueType() == RHS.getValueType());
3120   EVT VT = Op.getValueType();
3121
3122   // Try to match this select into a max/min operation, which have dedicated
3123   // opcode in the instruction set.
3124   // NOTE: This is not correct in the presence of NaNs, so we only enable this
3125   // in no-NaNs mode.
3126   if (getTargetMachine().Options.NoNaNsFPMath) {
3127     if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3128         selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3129       CC = ISD::getSetCCSwappedOperands(CC);
3130       std::swap(TVal, FVal);
3131     }
3132
3133     if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3134         selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3135       switch (CC) {
3136       default:
3137         break;
3138       case ISD::SETGT:
3139       case ISD::SETGE:
3140       case ISD::SETUGT:
3141       case ISD::SETUGE:
3142       case ISD::SETOGT:
3143       case ISD::SETOGE:
3144         return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3145         break;
3146       case ISD::SETLT:
3147       case ISD::SETLE:
3148       case ISD::SETULT:
3149       case ISD::SETULE:
3150       case ISD::SETOLT:
3151       case ISD::SETOLE:
3152         return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3153         break;
3154       }
3155     }
3156   }
3157
3158   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
3159   // and do the comparison.
3160   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3161
3162   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3163   // clean.  Some of them require two CSELs to implement.
3164   ARM64CC::CondCode CC1, CC2;
3165   changeFPCCToARM64CC(CC, CC1, CC2);
3166   SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3167   SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3168
3169   // If we need a second CSEL, emit it, using the output of the first as the
3170   // RHS.  We're effectively OR'ing the two CC's together.
3171   if (CC2 != ARM64CC::AL) {
3172     SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3173     return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3174   }
3175
3176   // Otherwise, return the output of the first CSEL.
3177   return CS1;
3178 }
3179
3180 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3181                                             SelectionDAG &DAG) const {
3182   // Jump table entries as PC relative offsets. No additional tweaking
3183   // is necessary here. Just get the address of the jump table.
3184   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3185   EVT PtrVT = getPointerTy();
3186   SDLoc DL(Op);
3187
3188   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3189       !Subtarget->isTargetMachO()) {
3190     const unsigned char MO_NC = ARM64II::MO_NC;
3191     return DAG.getNode(
3192         ARM64ISD::WrapperLarge, DL, PtrVT,
3193         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3194         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3195         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3196         DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3197   }
3198
3199   SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3200   SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3201                                       ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3202   SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3203   return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3204 }
3205
3206 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3207                                                SelectionDAG &DAG) const {
3208   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3209   EVT PtrVT = getPointerTy();
3210   SDLoc DL(Op);
3211
3212   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3213     // Use the GOT for the large code model on iOS.
3214     if (Subtarget->isTargetMachO()) {
3215       SDValue GotAddr = DAG.getTargetConstantPool(
3216           CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3217           ARM64II::MO_GOT);
3218       return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3219     }
3220
3221     const unsigned char MO_NC = ARM64II::MO_NC;
3222     return DAG.getNode(
3223         ARM64ISD::WrapperLarge, DL, PtrVT,
3224         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3225                                   CP->getOffset(), ARM64II::MO_G3),
3226         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3227                                   CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3228         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3229                                   CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3230         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3231                                   CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3232   } else {
3233     // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3234     // ELF, the only valid one on Darwin.
3235     SDValue Hi =
3236         DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3237                                   CP->getOffset(), ARM64II::MO_PAGE);
3238     SDValue Lo = DAG.getTargetConstantPool(
3239         CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3240         ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3241
3242     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3243     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3244   }
3245 }
3246
3247 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3248                                                SelectionDAG &DAG) const {
3249   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3250   EVT PtrVT = getPointerTy();
3251   SDLoc DL(Op);
3252   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3253       !Subtarget->isTargetMachO()) {
3254     const unsigned char MO_NC = ARM64II::MO_NC;
3255     return DAG.getNode(
3256         ARM64ISD::WrapperLarge, DL, PtrVT,
3257         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3258         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3259         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3260         DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3261   } else {
3262     SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3263     SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3264                                                              ARM64II::MO_NC);
3265     SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3266     return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3267   }
3268 }
3269
3270 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3271                                                  SelectionDAG &DAG) const {
3272   ARM64FunctionInfo *FuncInfo =
3273       DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3274
3275   SDLoc DL(Op);
3276   SDValue FR =
3277       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3278   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3279   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3280                       MachinePointerInfo(SV), false, false, 0);
3281 }
3282
3283 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3284                                                 SelectionDAG &DAG) const {
3285   // The layout of the va_list struct is specified in the AArch64 Procedure Call
3286   // Standard, section B.3.
3287   MachineFunction &MF = DAG.getMachineFunction();
3288   ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3289   SDLoc DL(Op);
3290
3291   SDValue Chain = Op.getOperand(0);
3292   SDValue VAList = Op.getOperand(1);
3293   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3294   SmallVector<SDValue, 4> MemOps;
3295
3296   // void *__stack at offset 0
3297   SDValue Stack =
3298       DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3299   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3300                                 MachinePointerInfo(SV), false, false, 8));
3301
3302   // void *__gr_top at offset 8
3303   int GPRSize = FuncInfo->getVarArgsGPRSize();
3304   if (GPRSize > 0) {
3305     SDValue GRTop, GRTopAddr;
3306
3307     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3308                             DAG.getConstant(8, getPointerTy()));
3309
3310     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3311     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3312                         DAG.getConstant(GPRSize, getPointerTy()));
3313
3314     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3315                                   MachinePointerInfo(SV, 8), false, false, 8));
3316   }
3317
3318   // void *__vr_top at offset 16
3319   int FPRSize = FuncInfo->getVarArgsFPRSize();
3320   if (FPRSize > 0) {
3321     SDValue VRTop, VRTopAddr;
3322     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3323                             DAG.getConstant(16, getPointerTy()));
3324
3325     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3326     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3327                         DAG.getConstant(FPRSize, getPointerTy()));
3328
3329     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3330                                   MachinePointerInfo(SV, 16), false, false, 8));
3331   }
3332
3333   // int __gr_offs at offset 24
3334   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3335                                    DAG.getConstant(24, getPointerTy()));
3336   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3337                                 GROffsAddr, MachinePointerInfo(SV, 24), false,
3338                                 false, 4));
3339
3340   // int __vr_offs at offset 28
3341   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3342                                    DAG.getConstant(28, getPointerTy()));
3343   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3344                                 VROffsAddr, MachinePointerInfo(SV, 28), false,
3345                                 false, 4));
3346
3347   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3348 }
3349
3350 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3351   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3352                                      : LowerAAPCS_VASTART(Op, DAG);
3353 }
3354
3355 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3356   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3357   // pointer.
3358   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3359   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3360   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3361
3362   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3363                        Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3364                        8, false, false, MachinePointerInfo(DestSV),
3365                        MachinePointerInfo(SrcSV));
3366 }
3367
3368 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3369   assert(Subtarget->isTargetDarwin() &&
3370          "automatic va_arg instruction only works on Darwin");
3371
3372   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3373   EVT VT = Op.getValueType();
3374   SDLoc DL(Op);
3375   SDValue Chain = Op.getOperand(0);
3376   SDValue Addr = Op.getOperand(1);
3377   unsigned Align = Op.getConstantOperandVal(3);
3378
3379   SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3380                                MachinePointerInfo(V), false, false, false, 0);
3381   Chain = VAList.getValue(1);
3382
3383   if (Align > 8) {
3384     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3385     VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3386                          DAG.getConstant(Align - 1, getPointerTy()));
3387     VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3388                          DAG.getConstant(-(int64_t)Align, getPointerTy()));
3389   }
3390
3391   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3392   uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3393
3394   // Scalar integer and FP values smaller than 64 bits are implicitly extended
3395   // up to 64 bits.  At the very least, we have to increase the striding of the
3396   // vaargs list to match this, and for FP values we need to introduce
3397   // FP_ROUND nodes as well.
3398   if (VT.isInteger() && !VT.isVector())
3399     ArgSize = 8;
3400   bool NeedFPTrunc = false;
3401   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3402     ArgSize = 8;
3403     NeedFPTrunc = true;
3404   }
3405
3406   // Increment the pointer, VAList, to the next vaarg
3407   SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3408                                DAG.getConstant(ArgSize, getPointerTy()));
3409   // Store the incremented VAList to the legalized pointer
3410   SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3411                                  false, false, 0);
3412
3413   // Load the actual argument out of the pointer VAList
3414   if (NeedFPTrunc) {
3415     // Load the value as an f64.
3416     SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3417                                  MachinePointerInfo(), false, false, false, 0);
3418     // Round the value down to an f32.
3419     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3420                                    DAG.getIntPtrConstant(1));
3421     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3422     // Merge the rounded value with the chain output of the load.
3423     return DAG.getMergeValues(Ops, DL);
3424   }
3425
3426   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3427                      false, false, 0);
3428 }
3429
3430 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3431                                             SelectionDAG &DAG) const {
3432   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3433   MFI->setFrameAddressIsTaken(true);
3434
3435   EVT VT = Op.getValueType();
3436   SDLoc DL(Op);
3437   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3438   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3439   while (Depth--)
3440     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3441                             MachinePointerInfo(), false, false, false, 0);
3442   return FrameAddr;
3443 }
3444
3445 // FIXME? Maybe this could be a TableGen attribute on some registers and
3446 // this table could be generated automatically from RegInfo.
3447 unsigned ARM64TargetLowering::getRegisterByName(const char* RegName) const {
3448   unsigned Reg = StringSwitch<unsigned>(RegName)
3449                        .Case("sp", ARM64::SP)
3450                        .Default(0);
3451   if (Reg)
3452     return Reg;
3453   report_fatal_error("Invalid register name global variable");
3454 }
3455
3456 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3457                                              SelectionDAG &DAG) const {
3458   MachineFunction &MF = DAG.getMachineFunction();
3459   MachineFrameInfo *MFI = MF.getFrameInfo();
3460   MFI->setReturnAddressIsTaken(true);
3461
3462   EVT VT = Op.getValueType();
3463   SDLoc DL(Op);
3464   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3465   if (Depth) {
3466     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3467     SDValue Offset = DAG.getConstant(8, getPointerTy());
3468     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3469                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3470                        MachinePointerInfo(), false, false, false, 0);
3471   }
3472
3473   // Return LR, which contains the return address. Mark it an implicit live-in.
3474   unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3475   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3476 }
3477
3478 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3479 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3480 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3481                                                   SelectionDAG &DAG) const {
3482   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3483   EVT VT = Op.getValueType();
3484   unsigned VTBits = VT.getSizeInBits();
3485   SDLoc dl(Op);
3486   SDValue ShOpLo = Op.getOperand(0);
3487   SDValue ShOpHi = Op.getOperand(1);
3488   SDValue ShAmt = Op.getOperand(2);
3489   SDValue ARMcc;
3490   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3491
3492   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3493
3494   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3495                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3496   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3497   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3498                                    DAG.getConstant(VTBits, MVT::i64));
3499   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3500
3501   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3502                                ISD::SETGE, dl, DAG);
3503   SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3504
3505   SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3506   SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3507   SDValue Lo =
3508       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3509
3510   // ARM64 shifts larger than the register width are wrapped rather than
3511   // clamped, so we can't just emit "hi >> x".
3512   SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3513   SDValue TrueValHi = Opc == ISD::SRA
3514                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
3515                                         DAG.getConstant(VTBits - 1, MVT::i64))
3516                           : DAG.getConstant(0, VT);
3517   SDValue Hi =
3518       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3519
3520   SDValue Ops[2] = { Lo, Hi };
3521   return DAG.getMergeValues(Ops, dl);
3522 }
3523
3524 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3525 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3526 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3527                                                  SelectionDAG &DAG) const {
3528   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3529   EVT VT = Op.getValueType();
3530   unsigned VTBits = VT.getSizeInBits();
3531   SDLoc dl(Op);
3532   SDValue ShOpLo = Op.getOperand(0);
3533   SDValue ShOpHi = Op.getOperand(1);
3534   SDValue ShAmt = Op.getOperand(2);
3535   SDValue ARMcc;
3536
3537   assert(Op.getOpcode() == ISD::SHL_PARTS);
3538   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3539                                  DAG.getConstant(VTBits, MVT::i64), ShAmt);
3540   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3541   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3542                                    DAG.getConstant(VTBits, MVT::i64));
3543   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3544   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3545
3546   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3547
3548   SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3549                                ISD::SETGE, dl, DAG);
3550   SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3551   SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3552
3553   // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3554   // so we can't just emit "lo << a" if a is too big.
3555   SDValue TrueValLo = DAG.getConstant(0, VT);
3556   SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3557   SDValue Lo =
3558       DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3559
3560   SDValue Ops[2] = { Lo, Hi };
3561   return DAG.getMergeValues(Ops, dl);
3562 }
3563
3564 bool
3565 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3566   // The ARM64 target doesn't support folding offsets into global addresses.
3567   return false;
3568 }
3569
3570 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3571   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3572   // FIXME: We should be able to handle f128 as well with a clever lowering.
3573   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3574     return true;
3575
3576   if (VT == MVT::f64)
3577     return ARM64_AM::getFP64Imm(Imm) != -1;
3578   else if (VT == MVT::f32)
3579     return ARM64_AM::getFP32Imm(Imm) != -1;
3580   return false;
3581 }
3582
3583 //===----------------------------------------------------------------------===//
3584 //                          ARM64 Optimization Hooks
3585 //===----------------------------------------------------------------------===//
3586
3587 //===----------------------------------------------------------------------===//
3588 //                          ARM64 Inline Assembly Support
3589 //===----------------------------------------------------------------------===//
3590
3591 // Table of Constraints
3592 // TODO: This is the current set of constraints supported by ARM for the
3593 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3594 //
3595 // r - A general register
3596 // w - An FP/SIMD register of some size in the range v0-v31
3597 // x - An FP/SIMD register of some size in the range v0-v15
3598 // I - Constant that can be used with an ADD instruction
3599 // J - Constant that can be used with a SUB instruction
3600 // K - Constant that can be used with a 32-bit logical instruction
3601 // L - Constant that can be used with a 64-bit logical instruction
3602 // M - Constant that can be used as a 32-bit MOV immediate
3603 // N - Constant that can be used as a 64-bit MOV immediate
3604 // Q - A memory reference with base register and no offset
3605 // S - A symbolic address
3606 // Y - Floating point constant zero
3607 // Z - Integer constant zero
3608 //
3609 //   Note that general register operands will be output using their 64-bit x
3610 // register name, whatever the size of the variable, unless the asm operand
3611 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3612 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3613 // %q modifier.
3614
3615 /// getConstraintType - Given a constraint letter, return the type of
3616 /// constraint it is for this target.
3617 ARM64TargetLowering::ConstraintType
3618 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3619   if (Constraint.size() == 1) {
3620     switch (Constraint[0]) {
3621     default:
3622       break;
3623     case 'z':
3624       return C_Other;
3625     case 'x':
3626     case 'w':
3627       return C_RegisterClass;
3628     // An address with a single base register. Due to the way we
3629     // currently handle addresses it is the same as 'r'.
3630     case 'Q':
3631       return C_Memory;
3632     }
3633   }
3634   return TargetLowering::getConstraintType(Constraint);
3635 }
3636
3637 /// Examine constraint type and operand type and determine a weight value.
3638 /// This object must already have been set up with the operand type
3639 /// and the current alternative constraint selected.
3640 TargetLowering::ConstraintWeight
3641 ARM64TargetLowering::getSingleConstraintMatchWeight(
3642     AsmOperandInfo &info, const char *constraint) const {
3643   ConstraintWeight weight = CW_Invalid;
3644   Value *CallOperandVal = info.CallOperandVal;
3645   // If we don't have a value, we can't do a match,
3646   // but allow it at the lowest weight.
3647   if (!CallOperandVal)
3648     return CW_Default;
3649   Type *type = CallOperandVal->getType();
3650   // Look at the constraint type.
3651   switch (*constraint) {
3652   default:
3653     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3654     break;
3655   case 'x':
3656   case 'w':
3657     if (type->isFloatingPointTy() || type->isVectorTy())
3658       weight = CW_Register;
3659     break;
3660   case 'z':
3661     weight = CW_Constant;
3662     break;
3663   }
3664   return weight;
3665 }
3666
3667 std::pair<unsigned, const TargetRegisterClass *>
3668 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3669                                                   MVT VT) const {
3670   if (Constraint.size() == 1) {
3671     switch (Constraint[0]) {
3672     case 'r':
3673       if (VT.getSizeInBits() == 64)
3674         return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3675       return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3676     case 'w':
3677       if (VT == MVT::f32)
3678         return std::make_pair(0U, &ARM64::FPR32RegClass);
3679       if (VT.getSizeInBits() == 64)
3680         return std::make_pair(0U, &ARM64::FPR64RegClass);
3681       if (VT.getSizeInBits() == 128)
3682         return std::make_pair(0U, &ARM64::FPR128RegClass);
3683       break;
3684     // The instructions that this constraint is designed for can
3685     // only take 128-bit registers so just use that regclass.
3686     case 'x':
3687       if (VT.getSizeInBits() == 128)
3688         return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3689       break;
3690     }
3691   }
3692   if (StringRef("{cc}").equals_lower(Constraint))
3693     return std::make_pair(unsigned(ARM64::NZCV), &ARM64::CCRRegClass);
3694
3695   // Use the default implementation in TargetLowering to convert the register
3696   // constraint into a member of a register class.
3697   std::pair<unsigned, const TargetRegisterClass *> Res;
3698   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3699
3700   // Not found as a standard register?
3701   if (!Res.second) {
3702     unsigned Size = Constraint.size();
3703     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3704         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3705       const std::string Reg =
3706           std::string(&Constraint[2], &Constraint[Size - 1]);
3707       int RegNo = atoi(Reg.c_str());
3708       if (RegNo >= 0 && RegNo <= 31) {
3709         // v0 - v31 are aliases of q0 - q31.
3710         // By default we'll emit v0-v31 for this unless there's a modifier where
3711         // we'll emit the correct register as well.
3712         Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3713         Res.second = &ARM64::FPR128RegClass;
3714       }
3715     }
3716   }
3717
3718   return Res;
3719 }
3720
3721 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3722 /// vector.  If it is invalid, don't add anything to Ops.
3723 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3724     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3725     SelectionDAG &DAG) const {
3726   SDValue Result;
3727
3728   // Currently only support length 1 constraints.
3729   if (Constraint.length() != 1)
3730     return;
3731
3732   char ConstraintLetter = Constraint[0];
3733   switch (ConstraintLetter) {
3734   default:
3735     break;
3736
3737   // This set of constraints deal with valid constants for various instructions.
3738   // Validate and return a target constant for them if we can.
3739   case 'z': {
3740     // 'z' maps to xzr or wzr so it needs an input of 0.
3741     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3742     if (!C || C->getZExtValue() != 0)
3743       return;
3744
3745     if (Op.getValueType() == MVT::i64)
3746       Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3747     else
3748       Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3749     break;
3750   }
3751
3752   case 'I':
3753   case 'J':
3754   case 'K':
3755   case 'L':
3756   case 'M':
3757   case 'N':
3758     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3759     if (!C)
3760       return;
3761
3762     // Grab the value and do some validation.
3763     uint64_t CVal = C->getZExtValue();
3764     switch (ConstraintLetter) {
3765     // The I constraint applies only to simple ADD or SUB immediate operands:
3766     // i.e. 0 to 4095 with optional shift by 12
3767     // The J constraint applies only to ADD or SUB immediates that would be
3768     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3769     // instruction [or vice versa], in other words -1 to -4095 with optional
3770     // left shift by 12.
3771     case 'I':
3772       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3773         break;
3774       return;
3775     case 'J': {
3776       uint64_t NVal = -C->getSExtValue();
3777       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3778         break;
3779       return;
3780     }
3781     // The K and L constraints apply *only* to logical immediates, including
3782     // what used to be the MOVI alias for ORR (though the MOVI alias has now
3783     // been removed and MOV should be used). So these constraints have to
3784     // distinguish between bit patterns that are valid 32-bit or 64-bit
3785     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3786     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3787     // versa.
3788     case 'K':
3789       if (ARM64_AM::isLogicalImmediate(CVal, 32))
3790         break;
3791       return;
3792     case 'L':
3793       if (ARM64_AM::isLogicalImmediate(CVal, 64))
3794         break;
3795       return;
3796     // The M and N constraints are a superset of K and L respectively, for use
3797     // with the MOV (immediate) alias. As well as the logical immediates they
3798     // also match 32 or 64-bit immediates that can be loaded either using a
3799     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3800     // (M) or 64-bit 0x1234000000000000 (N) etc.
3801     // As a note some of this code is liberally stolen from the asm parser.
3802     case 'M': {
3803       if (!isUInt<32>(CVal))
3804         return;
3805       if (ARM64_AM::isLogicalImmediate(CVal, 32))
3806         break;
3807       if ((CVal & 0xFFFF) == CVal)
3808         break;
3809       if ((CVal & 0xFFFF0000ULL) == CVal)
3810         break;
3811       uint64_t NCVal = ~(uint32_t)CVal;
3812       if ((NCVal & 0xFFFFULL) == NCVal)
3813         break;
3814       if ((NCVal & 0xFFFF0000ULL) == NCVal)
3815         break;
3816       return;
3817     }
3818     case 'N': {
3819       if (ARM64_AM::isLogicalImmediate(CVal, 64))
3820         break;
3821       if ((CVal & 0xFFFFULL) == CVal)
3822         break;
3823       if ((CVal & 0xFFFF0000ULL) == CVal)
3824         break;
3825       if ((CVal & 0xFFFF00000000ULL) == CVal)
3826         break;
3827       if ((CVal & 0xFFFF000000000000ULL) == CVal)
3828         break;
3829       uint64_t NCVal = ~CVal;
3830       if ((NCVal & 0xFFFFULL) == NCVal)
3831         break;
3832       if ((NCVal & 0xFFFF0000ULL) == NCVal)
3833         break;
3834       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3835         break;
3836       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3837         break;
3838       return;
3839     }
3840     default:
3841       return;
3842     }
3843
3844     // All assembler immediates are 64-bit integers.
3845     Result = DAG.getTargetConstant(CVal, MVT::i64);
3846     break;
3847   }
3848
3849   if (Result.getNode()) {
3850     Ops.push_back(Result);
3851     return;
3852   }
3853
3854   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3855 }
3856
3857 //===----------------------------------------------------------------------===//
3858 //                     ARM64 Advanced SIMD Support
3859 //===----------------------------------------------------------------------===//
3860
3861 /// WidenVector - Given a value in the V64 register class, produce the
3862 /// equivalent value in the V128 register class.
3863 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3864   EVT VT = V64Reg.getValueType();
3865   unsigned NarrowSize = VT.getVectorNumElements();
3866   MVT EltTy = VT.getVectorElementType().getSimpleVT();
3867   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3868   SDLoc DL(V64Reg);
3869
3870   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3871                      V64Reg, DAG.getConstant(0, MVT::i32));
3872 }
3873
3874 /// getExtFactor - Determine the adjustment factor for the position when
3875 /// generating an "extract from vector registers" instruction.
3876 static unsigned getExtFactor(SDValue &V) {
3877   EVT EltType = V.getValueType().getVectorElementType();
3878   return EltType.getSizeInBits() / 8;
3879 }
3880
3881 /// NarrowVector - Given a value in the V128 register class, produce the
3882 /// equivalent value in the V64 register class.
3883 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3884   EVT VT = V128Reg.getValueType();
3885   unsigned WideSize = VT.getVectorNumElements();
3886   MVT EltTy = VT.getVectorElementType().getSimpleVT();
3887   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3888   SDLoc DL(V128Reg);
3889
3890   return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3891 }
3892
3893 // Gather data to see if the operation can be modelled as a
3894 // shuffle in combination with VEXTs.
3895 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3896                                                 SelectionDAG &DAG) const {
3897   SDLoc dl(Op);
3898   EVT VT = Op.getValueType();
3899   unsigned NumElts = VT.getVectorNumElements();
3900
3901   SmallVector<SDValue, 2> SourceVecs;
3902   SmallVector<unsigned, 2> MinElts;
3903   SmallVector<unsigned, 2> MaxElts;
3904
3905   for (unsigned i = 0; i < NumElts; ++i) {
3906     SDValue V = Op.getOperand(i);
3907     if (V.getOpcode() == ISD::UNDEF)
3908       continue;
3909     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3910       // A shuffle can only come from building a vector from various
3911       // elements of other vectors.
3912       return SDValue();
3913     }
3914
3915     // Record this extraction against the appropriate vector if possible...
3916     SDValue SourceVec = V.getOperand(0);
3917     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3918     bool FoundSource = false;
3919     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3920       if (SourceVecs[j] == SourceVec) {
3921         if (MinElts[j] > EltNo)
3922           MinElts[j] = EltNo;
3923         if (MaxElts[j] < EltNo)
3924           MaxElts[j] = EltNo;
3925         FoundSource = true;
3926         break;
3927       }
3928     }
3929
3930     // Or record a new source if not...
3931     if (!FoundSource) {
3932       SourceVecs.push_back(SourceVec);
3933       MinElts.push_back(EltNo);
3934       MaxElts.push_back(EltNo);
3935     }
3936   }
3937
3938   // Currently only do something sane when at most two source vectors
3939   // involved.
3940   if (SourceVecs.size() > 2)
3941     return SDValue();
3942
3943   SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3944   int VEXTOffsets[2] = { 0, 0 };
3945
3946   // This loop extracts the usage patterns of the source vectors
3947   // and prepares appropriate SDValues for a shuffle if possible.
3948   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3949     if (SourceVecs[i].getValueType() == VT) {
3950       // No VEXT necessary
3951       ShuffleSrcs[i] = SourceVecs[i];
3952       VEXTOffsets[i] = 0;
3953       continue;
3954     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3955       // We can pad out the smaller vector for free, so if it's part of a
3956       // shuffle...
3957       ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3958                                    DAG.getUNDEF(SourceVecs[i].getValueType()));
3959       continue;
3960     }
3961
3962     // Don't attempt to extract subvectors from BUILD_VECTOR sources
3963     // that expand or trunc the original value.
3964     // TODO: We can try to bitcast and ANY_EXTEND the result but
3965     // we need to consider the cost of vector ANY_EXTEND, and the
3966     // legality of all the types.
3967     if (SourceVecs[i].getValueType().getVectorElementType() !=
3968         VT.getVectorElementType())
3969       return SDValue();
3970
3971     // Since only 64-bit and 128-bit vectors are legal on ARM and
3972     // we've eliminated the other cases...
3973     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3974            "unexpected vector sizes in ReconstructShuffle");
3975
3976     if (MaxElts[i] - MinElts[i] >= NumElts) {
3977       // Span too large for a VEXT to cope
3978       return SDValue();
3979     }
3980
3981     if (MinElts[i] >= NumElts) {
3982       // The extraction can just take the second half
3983       VEXTOffsets[i] = NumElts;
3984       ShuffleSrcs[i] =
3985           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3986                       DAG.getIntPtrConstant(NumElts));
3987     } else if (MaxElts[i] < NumElts) {
3988       // The extraction can just take the first half
3989       VEXTOffsets[i] = 0;
3990       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3991                                    SourceVecs[i], DAG.getIntPtrConstant(0));
3992     } else {
3993       // An actual VEXT is needed
3994       VEXTOffsets[i] = MinElts[i];
3995       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3996                                      SourceVecs[i], DAG.getIntPtrConstant(0));
3997       SDValue VEXTSrc2 =
3998           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3999                       DAG.getIntPtrConstant(NumElts));
4000       unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
4001       ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
4002                                    DAG.getConstant(Imm, MVT::i32));
4003     }
4004   }
4005
4006   SmallVector<int, 8> Mask;
4007
4008   for (unsigned i = 0; i < NumElts; ++i) {
4009     SDValue Entry = Op.getOperand(i);
4010     if (Entry.getOpcode() == ISD::UNDEF) {
4011       Mask.push_back(-1);
4012       continue;
4013     }
4014
4015     SDValue ExtractVec = Entry.getOperand(0);
4016     int ExtractElt =
4017         cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
4018     if (ExtractVec == SourceVecs[0]) {
4019       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4020     } else {
4021       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4022     }
4023   }
4024
4025   // Final check before we try to produce nonsense...
4026   if (isShuffleMaskLegal(Mask, VT))
4027     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4028                                 &Mask[0]);
4029
4030   return SDValue();
4031 }
4032
4033 // check if an EXT instruction can handle the shuffle mask when the
4034 // vector sources of the shuffle are the same.
4035 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4036   unsigned NumElts = VT.getVectorNumElements();
4037
4038   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4039   if (M[0] < 0)
4040     return false;
4041
4042   Imm = M[0];
4043
4044   // If this is a VEXT shuffle, the immediate value is the index of the first
4045   // element.  The other shuffle indices must be the successive elements after
4046   // the first one.
4047   unsigned ExpectedElt = Imm;
4048   for (unsigned i = 1; i < NumElts; ++i) {
4049     // Increment the expected index.  If it wraps around, just follow it
4050     // back to index zero and keep going.
4051     ++ExpectedElt;
4052     if (ExpectedElt == NumElts)
4053       ExpectedElt = 0;
4054
4055     if (M[i] < 0)
4056       continue; // ignore UNDEF indices
4057     if (ExpectedElt != static_cast<unsigned>(M[i]))
4058       return false;
4059   }
4060
4061   return true;
4062 }
4063
4064 // check if an EXT instruction can handle the shuffle mask when the
4065 // vector sources of the shuffle are different.
4066 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4067                       unsigned &Imm) {
4068   // Look for the first non-undef element.
4069   const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4070       [](int Elt) {return Elt >= 0;});
4071
4072   // Benefit form APInt to handle overflow when calculating expected element.
4073   unsigned NumElts = VT.getVectorNumElements();
4074   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4075   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4076   // The following shuffle indices must be the successive elements after the
4077   // first real element.
4078   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4079       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4080   if (FirstWrongElt != M.end())
4081     return false;
4082
4083   // The index of an EXT is the first element if it is not UNDEF.
4084   // Watch out for the beginning UNDEFs. The EXT index should be the expected
4085   // value of the first element.
4086   // E.g. <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4087   //      <-1, -1, 0, 1, ...> is treated as <IDX, IDX+1, 0, 1, ...>. IDX is
4088   // equal to the ExpectedElt.
4089   Imm = (M[0] >= 0) ? static_cast<unsigned>(M[0]) : ExpectedElt.getZExtValue();
4090
4091   // If no beginning UNDEFs, do swap when M[0] >= NumElts.
4092   if (M[0] >= 0 && Imm >= NumElts) {
4093     ReverseEXT = true;
4094     Imm -= NumElts;
4095   } else if (M[0] < 0) {
4096     // Only do swap when beginning UNDEFs more than the first real element,
4097     if (*FirstRealElt < FirstRealElt - M.begin())
4098       ReverseEXT = true;
4099     if (Imm >= NumElts)
4100       Imm -= NumElts;
4101   }
4102
4103   return true;
4104 }
4105
4106 /// isREVMask - Check if a vector shuffle corresponds to a REV
4107 /// instruction with the specified blocksize.  (The order of the elements
4108 /// within each block of the vector is reversed.)
4109 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4110   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4111          "Only possible block sizes for REV are: 16, 32, 64");
4112
4113   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4114   if (EltSz == 64)
4115     return false;
4116
4117   unsigned NumElts = VT.getVectorNumElements();
4118   unsigned BlockElts = M[0] + 1;
4119   // If the first shuffle index is UNDEF, be optimistic.
4120   if (M[0] < 0)
4121     BlockElts = BlockSize / EltSz;
4122
4123   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4124     return false;
4125
4126   for (unsigned i = 0; i < NumElts; ++i) {
4127     if (M[i] < 0)
4128       continue; // ignore UNDEF indices
4129     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4130       return false;
4131   }
4132
4133   return true;
4134 }
4135
4136 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4137   unsigned NumElts = VT.getVectorNumElements();
4138   WhichResult = (M[0] == 0 ? 0 : 1);
4139   unsigned Idx = WhichResult * NumElts / 2;
4140   for (unsigned i = 0; i != NumElts; i += 2) {
4141     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4142         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4143       return false;
4144     Idx += 1;
4145   }
4146
4147   return true;
4148 }
4149
4150 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4151   unsigned NumElts = VT.getVectorNumElements();
4152   WhichResult = (M[0] == 0 ? 0 : 1);
4153   for (unsigned i = 0; i != NumElts; ++i) {
4154     if (M[i] < 0)
4155       continue; // ignore UNDEF indices
4156     if ((unsigned)M[i] != 2 * i + WhichResult)
4157       return false;
4158   }
4159
4160   return true;
4161 }
4162
4163 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4164   unsigned NumElts = VT.getVectorNumElements();
4165   WhichResult = (M[0] == 0 ? 0 : 1);
4166   for (unsigned i = 0; i < NumElts; i += 2) {
4167     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4168         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4169       return false;
4170   }
4171   return true;
4172 }
4173
4174 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4175 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4176 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4177 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4178   unsigned NumElts = VT.getVectorNumElements();
4179   WhichResult = (M[0] == 0 ? 0 : 1);
4180   unsigned Idx = WhichResult * NumElts / 2;
4181   for (unsigned i = 0; i != NumElts; i += 2) {
4182     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4183         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4184       return false;
4185     Idx += 1;
4186   }
4187
4188   return true;
4189 }
4190
4191 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4192 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4193 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4194 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4195   unsigned Half = VT.getVectorNumElements() / 2;
4196   WhichResult = (M[0] == 0 ? 0 : 1);
4197   for (unsigned j = 0; j != 2; ++j) {
4198     unsigned Idx = WhichResult;
4199     for (unsigned i = 0; i != Half; ++i) {
4200       int MIdx = M[i + j * Half];
4201       if (MIdx >= 0 && (unsigned)MIdx != Idx)
4202         return false;
4203       Idx += 2;
4204     }
4205   }
4206
4207   return true;
4208 }
4209
4210 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4211 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4212 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4213 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4214   unsigned NumElts = VT.getVectorNumElements();
4215   WhichResult = (M[0] == 0 ? 0 : 1);
4216   for (unsigned i = 0; i < NumElts; i += 2) {
4217     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4218         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4219       return false;
4220   }
4221   return true;
4222 }
4223
4224 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4225                       bool &DstIsLeft, int &Anomaly) {
4226   if (M.size() != static_cast<size_t>(NumInputElements))
4227     return false;
4228
4229   int NumLHSMatch = 0, NumRHSMatch = 0;
4230   int LastLHSMismatch = -1, LastRHSMismatch = -1;
4231
4232   for (int i = 0; i < NumInputElements; ++i) {
4233     if (M[i] == -1) {
4234       ++NumLHSMatch;
4235       ++NumRHSMatch;
4236       continue;
4237     }
4238
4239     if (M[i] == i)
4240       ++NumLHSMatch;
4241     else
4242       LastLHSMismatch = i;
4243
4244     if (M[i] == i + NumInputElements)
4245       ++NumRHSMatch;
4246     else
4247       LastRHSMismatch = i;
4248   }
4249
4250   if (NumLHSMatch == NumInputElements - 1) {
4251     DstIsLeft = true;
4252     Anomaly = LastLHSMismatch;
4253     return true;
4254   } else if (NumRHSMatch == NumInputElements - 1) {
4255     DstIsLeft = false;
4256     Anomaly = LastRHSMismatch;
4257     return true;
4258   }
4259
4260   return false;
4261 }
4262
4263 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4264   if (VT.getSizeInBits() != 128)
4265     return false;
4266
4267   unsigned NumElts = VT.getVectorNumElements();
4268
4269   for (int I = 0, E = NumElts / 2; I != E; I++) {
4270     if (Mask[I] != I)
4271       return false;
4272   }
4273
4274   int Offset = NumElts / 2;
4275   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4276     if (Mask[I] != I + SplitLHS * Offset)
4277       return false;
4278   }
4279
4280   return true;
4281 }
4282
4283 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4284   SDLoc DL(Op);
4285   EVT VT = Op.getValueType();
4286   SDValue V0 = Op.getOperand(0);
4287   SDValue V1 = Op.getOperand(1);
4288   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4289
4290   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4291       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4292     return SDValue();
4293
4294   bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4295
4296   if (!isConcatMask(Mask, VT, SplitV0))
4297     return SDValue();
4298
4299   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4300                                 VT.getVectorNumElements() / 2);
4301   if (SplitV0) {
4302     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4303                      DAG.getConstant(0, MVT::i64));
4304   }
4305   if (V1.getValueType().getSizeInBits() == 128) {
4306     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4307                      DAG.getConstant(0, MVT::i64));
4308   }
4309   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4310 }
4311
4312 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4313 /// the specified operations to build the shuffle.
4314 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4315                                       SDValue RHS, SelectionDAG &DAG,
4316                                       SDLoc dl) {
4317   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4318   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4319   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4320
4321   enum {
4322     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4323     OP_VREV,
4324     OP_VDUP0,
4325     OP_VDUP1,
4326     OP_VDUP2,
4327     OP_VDUP3,
4328     OP_VEXT1,
4329     OP_VEXT2,
4330     OP_VEXT3,
4331     OP_VUZPL, // VUZP, left result
4332     OP_VUZPR, // VUZP, right result
4333     OP_VZIPL, // VZIP, left result
4334     OP_VZIPR, // VZIP, right result
4335     OP_VTRNL, // VTRN, left result
4336     OP_VTRNR  // VTRN, right result
4337   };
4338
4339   if (OpNum == OP_COPY) {
4340     if (LHSID == (1 * 9 + 2) * 9 + 3)
4341       return LHS;
4342     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4343     return RHS;
4344   }
4345
4346   SDValue OpLHS, OpRHS;
4347   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4348   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4349   EVT VT = OpLHS.getValueType();
4350
4351   switch (OpNum) {
4352   default:
4353     llvm_unreachable("Unknown shuffle opcode!");
4354   case OP_VREV:
4355     // VREV divides the vector in half and swaps within the half.
4356     if (VT.getVectorElementType() == MVT::i32 ||
4357         VT.getVectorElementType() == MVT::f32)
4358       return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4359     // vrev <4 x i16> -> REV32
4360     if (VT.getVectorElementType() == MVT::i16)
4361       return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4362     // vrev <4 x i8> -> REV16
4363     assert(VT.getVectorElementType() == MVT::i8);
4364     return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4365   case OP_VDUP0:
4366   case OP_VDUP1:
4367   case OP_VDUP2:
4368   case OP_VDUP3: {
4369     EVT EltTy = VT.getVectorElementType();
4370     unsigned Opcode;
4371     if (EltTy == MVT::i8)
4372       Opcode = ARM64ISD::DUPLANE8;
4373     else if (EltTy == MVT::i16)
4374       Opcode = ARM64ISD::DUPLANE16;
4375     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4376       Opcode = ARM64ISD::DUPLANE32;
4377     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4378       Opcode = ARM64ISD::DUPLANE64;
4379     else
4380       llvm_unreachable("Invalid vector element type?");
4381
4382     if (VT.getSizeInBits() == 64)
4383       OpLHS = WidenVector(OpLHS, DAG);
4384     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4385     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4386   }
4387   case OP_VEXT1:
4388   case OP_VEXT2:
4389   case OP_VEXT3: {
4390     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4391     return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4392                        DAG.getConstant(Imm, MVT::i32));
4393   }
4394   case OP_VUZPL:
4395     return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4396   case OP_VUZPR:
4397     return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4398   case OP_VZIPL:
4399     return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4400   case OP_VZIPR:
4401     return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4402   case OP_VTRNL:
4403     return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4404   case OP_VTRNR:
4405     return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4406   }
4407 }
4408
4409 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4410                            SelectionDAG &DAG) {
4411   // Check to see if we can use the TBL instruction.
4412   SDValue V1 = Op.getOperand(0);
4413   SDValue V2 = Op.getOperand(1);
4414   SDLoc DL(Op);
4415
4416   EVT EltVT = Op.getValueType().getVectorElementType();
4417   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4418
4419   SmallVector<SDValue, 8> TBLMask;
4420   for (int Val : ShuffleMask) {
4421     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4422       unsigned Offset = Byte + Val * BytesPerElt;
4423       TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4424     }
4425   }
4426
4427   MVT IndexVT = MVT::v8i8;
4428   unsigned IndexLen = 8;
4429   if (Op.getValueType().getSizeInBits() == 128) {
4430     IndexVT = MVT::v16i8;
4431     IndexLen = 16;
4432   }
4433
4434   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4435   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4436
4437   SDValue Shuffle;
4438   if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4439     if (IndexLen == 8)
4440       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4441     Shuffle = DAG.getNode(
4442         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4443         DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4444         DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4445                     makeArrayRef(TBLMask.data(), IndexLen)));
4446   } else {
4447     if (IndexLen == 8) {
4448       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4449       Shuffle = DAG.getNode(
4450           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4451           DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4452           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4453                       makeArrayRef(TBLMask.data(), IndexLen)));
4454     } else {
4455       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4456       // cannot currently represent the register constraints on the input
4457       // table registers.
4458       //  Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4459       //                   DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4460       //                               &TBLMask[0], IndexLen));
4461       Shuffle = DAG.getNode(
4462           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4463           DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4464           DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4465                       makeArrayRef(TBLMask.data(), IndexLen)));
4466     }
4467   }
4468   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4469 }
4470
4471 static unsigned getDUPLANEOp(EVT EltType) {
4472   if (EltType == MVT::i8)
4473     return ARM64ISD::DUPLANE8;
4474   if (EltType == MVT::i16)
4475     return ARM64ISD::DUPLANE16;
4476   if (EltType == MVT::i32 || EltType == MVT::f32)
4477     return ARM64ISD::DUPLANE32;
4478   if (EltType == MVT::i64 || EltType == MVT::f64)
4479     return ARM64ISD::DUPLANE64;
4480
4481   llvm_unreachable("Invalid vector element type?");
4482 }
4483
4484 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4485                                                  SelectionDAG &DAG) const {
4486   SDLoc dl(Op);
4487   EVT VT = Op.getValueType();
4488
4489   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4490
4491   // Convert shuffles that are directly supported on NEON to target-specific
4492   // DAG nodes, instead of keeping them as shuffles and matching them again
4493   // during code selection.  This is more efficient and avoids the possibility
4494   // of inconsistencies between legalization and selection.
4495   ArrayRef<int> ShuffleMask = SVN->getMask();
4496
4497   SDValue V1 = Op.getOperand(0);
4498   SDValue V2 = Op.getOperand(1);
4499
4500   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4501                                        V1.getValueType().getSimpleVT())) {
4502     int Lane = SVN->getSplatIndex();
4503     // If this is undef splat, generate it via "just" vdup, if possible.
4504     if (Lane == -1)
4505       Lane = 0;
4506
4507     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4508       return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4509                          V1.getOperand(0));
4510     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4511     // constant. If so, we can just reference the lane's definition directly.
4512     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4513         !isa<ConstantSDNode>(V1.getOperand(Lane)))
4514       return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4515
4516     // Otherwise, duplicate from the lane of the input vector.
4517     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4518
4519     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4520     // to make a vector of the same size as this SHUFFLE. We can ignore the
4521     // extract entirely, and canonicalise the concat using WidenVector.
4522     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4523       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4524       V1 = V1.getOperand(0);
4525     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4526       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4527       Lane -= Idx * VT.getVectorNumElements() / 2;
4528       V1 = WidenVector(V1.getOperand(Idx), DAG);
4529     } else if (VT.getSizeInBits() == 64)
4530       V1 = WidenVector(V1, DAG);
4531
4532     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4533   }
4534
4535   if (isREVMask(ShuffleMask, VT, 64))
4536     return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4537   if (isREVMask(ShuffleMask, VT, 32))
4538     return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4539   if (isREVMask(ShuffleMask, VT, 16))
4540     return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4541
4542   bool ReverseEXT = false;
4543   unsigned Imm;
4544   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4545     if (ReverseEXT)
4546       std::swap(V1, V2);
4547     Imm *= getExtFactor(V1);
4548     return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4549                        DAG.getConstant(Imm, MVT::i32));
4550   } else if (V2->getOpcode() == ISD::UNDEF &&
4551              isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4552     Imm *= getExtFactor(V1);
4553     return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4554                        DAG.getConstant(Imm, MVT::i32));
4555   }
4556
4557   unsigned WhichResult;
4558   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4559     unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4560     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4561   }
4562   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4563     unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4564     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4565   }
4566   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4567     unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4568     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4569   }
4570
4571   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4572     unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4573     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4574   }
4575   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4576     unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4577     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4578   }
4579   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4580     unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4581     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4582   }
4583
4584   SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4585   if (Concat.getNode())
4586     return Concat;
4587
4588   bool DstIsLeft;
4589   int Anomaly;
4590   int NumInputElements = V1.getValueType().getVectorNumElements();
4591   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4592     SDValue DstVec = DstIsLeft ? V1 : V2;
4593     SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4594
4595     SDValue SrcVec = V1;
4596     int SrcLane = ShuffleMask[Anomaly];
4597     if (SrcLane >= NumInputElements) {
4598       SrcVec = V2;
4599       SrcLane -= VT.getVectorNumElements();
4600     }
4601     SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4602
4603     EVT ScalarVT = VT.getVectorElementType();
4604     if (ScalarVT.getSizeInBits() < 32)
4605       ScalarVT = MVT::i32;
4606
4607     return DAG.getNode(
4608         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4609         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4610         DstLaneV);
4611   }
4612
4613   // If the shuffle is not directly supported and it has 4 elements, use
4614   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4615   unsigned NumElts = VT.getVectorNumElements();
4616   if (NumElts == 4) {
4617     unsigned PFIndexes[4];
4618     for (unsigned i = 0; i != 4; ++i) {
4619       if (ShuffleMask[i] < 0)
4620         PFIndexes[i] = 8;
4621       else
4622         PFIndexes[i] = ShuffleMask[i];
4623     }
4624
4625     // Compute the index in the perfect shuffle table.
4626     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4627                             PFIndexes[2] * 9 + PFIndexes[3];
4628     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4629     unsigned Cost = (PFEntry >> 30);
4630
4631     if (Cost <= 4)
4632       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4633   }
4634
4635   return GenerateTBL(Op, ShuffleMask, DAG);
4636 }
4637
4638 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4639                                APInt &UndefBits) {
4640   EVT VT = BVN->getValueType(0);
4641   APInt SplatBits, SplatUndef;
4642   unsigned SplatBitSize;
4643   bool HasAnyUndefs;
4644   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4645     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4646
4647     for (unsigned i = 0; i < NumSplats; ++i) {
4648       CnstBits <<= SplatBitSize;
4649       UndefBits <<= SplatBitSize;
4650       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4651       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4652     }
4653
4654     return true;
4655   }
4656
4657   return false;
4658 }
4659
4660 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4661                                             SelectionDAG &DAG) const {
4662   BuildVectorSDNode *BVN =
4663       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4664   SDValue LHS = Op.getOperand(0);
4665   SDLoc dl(Op);
4666   EVT VT = Op.getValueType();
4667
4668   if (!BVN)
4669     return Op;
4670
4671   APInt CnstBits(VT.getSizeInBits(), 0);
4672   APInt UndefBits(VT.getSizeInBits(), 0);
4673   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4674     // We only have BIC vector immediate instruction, which is and-not.
4675     CnstBits = ~CnstBits;
4676
4677     // We make use of a little bit of goto ickiness in order to avoid having to
4678     // duplicate the immediate matching logic for the undef toggled case.
4679     bool SecondTry = false;
4680   AttemptModImm:
4681
4682     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4683       CnstBits = CnstBits.zextOrTrunc(64);
4684       uint64_t CnstVal = CnstBits.getZExtValue();
4685
4686       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4687         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4688         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4689         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4690                                   DAG.getConstant(CnstVal, MVT::i32),
4691                                   DAG.getConstant(0, MVT::i32));
4692         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4693       }
4694
4695       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4696         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4697         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4698         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4699                                   DAG.getConstant(CnstVal, MVT::i32),
4700                                   DAG.getConstant(8, MVT::i32));
4701         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4702       }
4703
4704       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4705         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4706         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4707         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4708                                   DAG.getConstant(CnstVal, MVT::i32),
4709                                   DAG.getConstant(16, MVT::i32));
4710         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4711       }
4712
4713       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4714         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4715         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4716         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4717                                   DAG.getConstant(CnstVal, MVT::i32),
4718                                   DAG.getConstant(24, MVT::i32));
4719         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4720       }
4721
4722       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4723         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4724         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4725         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4726                                   DAG.getConstant(CnstVal, MVT::i32),
4727                                   DAG.getConstant(0, MVT::i32));
4728         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4729       }
4730
4731       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4732         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4733         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4734         SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4735                                   DAG.getConstant(CnstVal, MVT::i32),
4736                                   DAG.getConstant(8, MVT::i32));
4737         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4738       }
4739     }
4740
4741     if (SecondTry)
4742       goto FailedModImm;
4743     SecondTry = true;
4744     CnstBits = ~UndefBits;
4745     goto AttemptModImm;
4746   }
4747
4748 // We can always fall back to a non-immediate AND.
4749 FailedModImm:
4750   return Op;
4751 }
4752
4753 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4754 // consists of only the same constant int value, returned in reference arg
4755 // ConstVal
4756 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4757                                      uint64_t &ConstVal) {
4758   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4759   if (!Bvec)
4760     return false;
4761   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4762   if (!FirstElt)
4763     return false;
4764   EVT VT = Bvec->getValueType(0);
4765   unsigned NumElts = VT.getVectorNumElements();
4766   for (unsigned i = 1; i < NumElts; ++i)
4767     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4768       return false;
4769   ConstVal = FirstElt->getZExtValue();
4770   return true;
4771 }
4772
4773 static unsigned getIntrinsicID(const SDNode *N) {
4774   unsigned Opcode = N->getOpcode();
4775   switch (Opcode) {
4776   default:
4777     return Intrinsic::not_intrinsic;
4778   case ISD::INTRINSIC_WO_CHAIN: {
4779     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4780     if (IID < Intrinsic::num_intrinsics)
4781       return IID;
4782     return Intrinsic::not_intrinsic;
4783   }
4784   }
4785 }
4786
4787 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4788 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4789 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4790 // Also, logical shift right -> sri, with the same structure.
4791 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4792   EVT VT = N->getValueType(0);
4793
4794   if (!VT.isVector())
4795     return SDValue();
4796
4797   SDLoc DL(N);
4798
4799   // Is the first op an AND?
4800   const SDValue And = N->getOperand(0);
4801   if (And.getOpcode() != ISD::AND)
4802     return SDValue();
4803
4804   // Is the second op an shl or lshr?
4805   SDValue Shift = N->getOperand(1);
4806   // This will have been turned into: ARM64ISD::VSHL vector, #shift
4807   // or ARM64ISD::VLSHR vector, #shift
4808   unsigned ShiftOpc = Shift.getOpcode();
4809   if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4810     return SDValue();
4811   bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4812
4813   // Is the shift amount constant?
4814   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4815   if (!C2node)
4816     return SDValue();
4817
4818   // Is the and mask vector all constant?
4819   uint64_t C1;
4820   if (!isAllConstantBuildVector(And.getOperand(1), C1))
4821     return SDValue();
4822
4823   // Is C1 == ~C2, taking into account how much one can shift elements of a
4824   // particular size?
4825   uint64_t C2 = C2node->getZExtValue();
4826   unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4827   if (C2 > ElemSizeInBits)
4828     return SDValue();
4829   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4830   if ((C1 & ElemMask) != (~C2 & ElemMask))
4831     return SDValue();
4832
4833   SDValue X = And.getOperand(0);
4834   SDValue Y = Shift.getOperand(0);
4835
4836   unsigned Intrin =
4837       IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4838   SDValue ResultSLI =
4839       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4840                   DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4841
4842   DEBUG(dbgs() << "arm64-lower: transformed: \n");
4843   DEBUG(N->dump(&DAG));
4844   DEBUG(dbgs() << "into: \n");
4845   DEBUG(ResultSLI->dump(&DAG));
4846
4847   ++NumShiftInserts;
4848   return ResultSLI;
4849 }
4850
4851 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4852                                            SelectionDAG &DAG) const {
4853   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4854   if (EnableARM64SlrGeneration) {
4855     SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4856     if (Res.getNode())
4857       return Res;
4858   }
4859
4860   BuildVectorSDNode *BVN =
4861       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4862   SDValue LHS = Op.getOperand(1);
4863   SDLoc dl(Op);
4864   EVT VT = Op.getValueType();
4865
4866   // OR commutes, so try swapping the operands.
4867   if (!BVN) {
4868     LHS = Op.getOperand(0);
4869     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4870   }
4871   if (!BVN)
4872     return Op;
4873
4874   APInt CnstBits(VT.getSizeInBits(), 0);
4875   APInt UndefBits(VT.getSizeInBits(), 0);
4876   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4877     // We make use of a little bit of goto ickiness in order to avoid having to
4878     // duplicate the immediate matching logic for the undef toggled case.
4879     bool SecondTry = false;
4880   AttemptModImm:
4881
4882     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4883       CnstBits = CnstBits.zextOrTrunc(64);
4884       uint64_t CnstVal = CnstBits.getZExtValue();
4885
4886       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4887         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4888         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4889         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4890                                   DAG.getConstant(CnstVal, MVT::i32),
4891                                   DAG.getConstant(0, MVT::i32));
4892         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4893       }
4894
4895       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4896         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4897         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4898         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4899                                   DAG.getConstant(CnstVal, MVT::i32),
4900                                   DAG.getConstant(8, MVT::i32));
4901         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4902       }
4903
4904       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4905         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4906         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4907         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4908                                   DAG.getConstant(CnstVal, MVT::i32),
4909                                   DAG.getConstant(16, MVT::i32));
4910         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4911       }
4912
4913       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4914         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4915         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4916         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4917                                   DAG.getConstant(CnstVal, MVT::i32),
4918                                   DAG.getConstant(24, MVT::i32));
4919         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4920       }
4921
4922       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4923         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4924         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4925         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4926                                   DAG.getConstant(CnstVal, MVT::i32),
4927                                   DAG.getConstant(0, MVT::i32));
4928         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4929       }
4930
4931       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4932         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4933         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4934         SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4935                                   DAG.getConstant(CnstVal, MVT::i32),
4936                                   DAG.getConstant(8, MVT::i32));
4937         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4938       }
4939     }
4940
4941     if (SecondTry)
4942       goto FailedModImm;
4943     SecondTry = true;
4944     CnstBits = UndefBits;
4945     goto AttemptModImm;
4946   }
4947
4948 // We can always fall back to a non-immediate OR.
4949 FailedModImm:
4950   return Op;
4951 }
4952
4953 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4954                                                SelectionDAG &DAG) const {
4955   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4956   SDLoc dl(Op);
4957   EVT VT = Op.getValueType();
4958
4959   APInt CnstBits(VT.getSizeInBits(), 0);
4960   APInt UndefBits(VT.getSizeInBits(), 0);
4961   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4962     // We make use of a little bit of goto ickiness in order to avoid having to
4963     // duplicate the immediate matching logic for the undef toggled case.
4964     bool SecondTry = false;
4965   AttemptModImm:
4966
4967     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4968       CnstBits = CnstBits.zextOrTrunc(64);
4969       uint64_t CnstVal = CnstBits.getZExtValue();
4970
4971       // Certain magic vector constants (used to express things like NOT
4972       // and NEG) are passed through unmodified.  This allows codegen patterns
4973       // for these operations to match.  Special-purpose patterns will lower
4974       // these immediates to MOVIs if it proves necessary.
4975       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4976         return Op;
4977
4978       // The many faces of MOVI...
4979       if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4980         CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4981         if (VT.getSizeInBits() == 128) {
4982           SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4983                                     DAG.getConstant(CnstVal, MVT::i32));
4984           return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4985         }
4986
4987         // Support the V64 version via subregister insertion.
4988         SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4989                                   DAG.getConstant(CnstVal, MVT::i32));
4990         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4991       }
4992
4993       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4994         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4995         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4996         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4997                                   DAG.getConstant(CnstVal, MVT::i32),
4998                                   DAG.getConstant(0, MVT::i32));
4999         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5000       }
5001
5002       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5003         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5004         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5005         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5006                                   DAG.getConstant(CnstVal, MVT::i32),
5007                                   DAG.getConstant(8, MVT::i32));
5008         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5009       }
5010
5011       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5012         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5013         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5014         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5015                                   DAG.getConstant(CnstVal, MVT::i32),
5016                                   DAG.getConstant(16, MVT::i32));
5017         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5018       }
5019
5020       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5021         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5022         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5023         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5024                                   DAG.getConstant(CnstVal, MVT::i32),
5025                                   DAG.getConstant(24, MVT::i32));
5026         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5027       }
5028
5029       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5030         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5031         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5032         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5033                                   DAG.getConstant(CnstVal, MVT::i32),
5034                                   DAG.getConstant(0, MVT::i32));
5035         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5036       }
5037
5038       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5039         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5040         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5041         SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
5042                                   DAG.getConstant(CnstVal, MVT::i32),
5043                                   DAG.getConstant(8, MVT::i32));
5044         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5045       }
5046
5047       if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5048         CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5049         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5050         SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5051                                   DAG.getConstant(CnstVal, MVT::i32),
5052                                   DAG.getConstant(264, MVT::i32));
5053         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5054       }
5055
5056       if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5057         CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5058         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5059         SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
5060                                   DAG.getConstant(CnstVal, MVT::i32),
5061                                   DAG.getConstant(272, MVT::i32));
5062         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5063       }
5064
5065       if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
5066         CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
5067         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5068         SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5069                                   DAG.getConstant(CnstVal, MVT::i32));
5070         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5071       }
5072
5073       // The few faces of FMOV...
5074       if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5075         CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5076         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5077         SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5078                                   DAG.getConstant(CnstVal, MVT::i32));
5079         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5080       }
5081
5082       if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5083           VT.getSizeInBits() == 128) {
5084         CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5085         SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5086                                   DAG.getConstant(CnstVal, MVT::i32));
5087         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5088       }
5089
5090       // The many faces of MVNI...
5091       CnstVal = ~CnstVal;
5092       if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5093         CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5094         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5095         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5096                                   DAG.getConstant(CnstVal, MVT::i32),
5097                                   DAG.getConstant(0, MVT::i32));
5098         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5099       }
5100
5101       if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5102         CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5103         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5104         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5105                                   DAG.getConstant(CnstVal, MVT::i32),
5106                                   DAG.getConstant(8, MVT::i32));
5107         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5108       }
5109
5110       if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5111         CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5112         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5113         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5114                                   DAG.getConstant(CnstVal, MVT::i32),
5115                                   DAG.getConstant(16, MVT::i32));
5116         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5117       }
5118
5119       if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5120         CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5121         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5122         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5123                                   DAG.getConstant(CnstVal, MVT::i32),
5124                                   DAG.getConstant(24, MVT::i32));
5125         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5126       }
5127
5128       if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5129         CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5130         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5131         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5132                                   DAG.getConstant(CnstVal, MVT::i32),
5133                                   DAG.getConstant(0, MVT::i32));
5134         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5135       }
5136
5137       if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5138         CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5139         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5140         SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5141                                   DAG.getConstant(CnstVal, MVT::i32),
5142                                   DAG.getConstant(8, MVT::i32));
5143         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5144       }
5145
5146       if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5147         CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5148         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5149         SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5150                                   DAG.getConstant(CnstVal, MVT::i32),
5151                                   DAG.getConstant(264, MVT::i32));
5152         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5153       }
5154
5155       if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5156         CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5157         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5158         SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5159                                   DAG.getConstant(CnstVal, MVT::i32),
5160                                   DAG.getConstant(272, MVT::i32));
5161         return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5162       }
5163     }
5164
5165     if (SecondTry)
5166       goto FailedModImm;
5167     SecondTry = true;
5168     CnstBits = UndefBits;
5169     goto AttemptModImm;
5170   }
5171 FailedModImm:
5172
5173   // Scan through the operands to find some interesting properties we can
5174   // exploit:
5175   //   1) If only one value is used, we can use a DUP, or
5176   //   2) if only the low element is not undef, we can just insert that, or
5177   //   3) if only one constant value is used (w/ some non-constant lanes),
5178   //      we can splat the constant value into the whole vector then fill
5179   //      in the non-constant lanes.
5180   //   4) FIXME: If different constant values are used, but we can intelligently
5181   //             select the values we'll be overwriting for the non-constant
5182   //             lanes such that we can directly materialize the vector
5183   //             some other way (MOVI, e.g.), we can be sneaky.
5184   unsigned NumElts = VT.getVectorNumElements();
5185   bool isOnlyLowElement = true;
5186   bool usesOnlyOneValue = true;
5187   bool usesOnlyOneConstantValue = true;
5188   bool isConstant = true;
5189   unsigned NumConstantLanes = 0;
5190   SDValue Value;
5191   SDValue ConstantValue;
5192   for (unsigned i = 0; i < NumElts; ++i) {
5193     SDValue V = Op.getOperand(i);
5194     if (V.getOpcode() == ISD::UNDEF)
5195       continue;
5196     if (i > 0)
5197       isOnlyLowElement = false;
5198     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5199       isConstant = false;
5200
5201     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5202       ++NumConstantLanes;
5203       if (!ConstantValue.getNode())
5204         ConstantValue = V;
5205       else if (ConstantValue != V)
5206         usesOnlyOneConstantValue = false;
5207     }
5208
5209     if (!Value.getNode())
5210       Value = V;
5211     else if (V != Value)
5212       usesOnlyOneValue = false;
5213   }
5214
5215   if (!Value.getNode())
5216     return DAG.getUNDEF(VT);
5217
5218   if (isOnlyLowElement)
5219     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5220
5221   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
5222   // i32 and try again.
5223   if (usesOnlyOneValue) {
5224     if (!isConstant) {
5225       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5226           Value.getValueType() != VT)
5227         return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5228
5229       // This is actually a DUPLANExx operation, which keeps everything vectory.
5230
5231       // DUPLANE works on 128-bit vectors, widen it if necessary.
5232       SDValue Lane = Value.getOperand(1);
5233       Value = Value.getOperand(0);
5234       if (Value.getValueType().getSizeInBits() == 64)
5235         Value = WidenVector(Value, DAG);
5236
5237       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5238       return DAG.getNode(Opcode, dl, VT, Value, Lane);
5239     }
5240
5241     if (VT.getVectorElementType().isFloatingPoint()) {
5242       SmallVector<SDValue, 8> Ops;
5243       MVT NewType =
5244           (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5245       for (unsigned i = 0; i < NumElts; ++i)
5246         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5247       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5248       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5249       Val = LowerBUILD_VECTOR(Val, DAG);
5250       if (Val.getNode())
5251         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5252     }
5253   }
5254
5255   // If there was only one constant value used and for more than one lane,
5256   // start by splatting that value, then replace the non-constant lanes. This
5257   // is better than the default, which will perform a separate initialization
5258   // for each lane.
5259   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5260     SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5261     // Now insert the non-constant lanes.
5262     for (unsigned i = 0; i < NumElts; ++i) {
5263       SDValue V = Op.getOperand(i);
5264       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5265       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5266         // Note that type legalization likely mucked about with the VT of the
5267         // source operand, so we may have to convert it here before inserting.
5268         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5269       }
5270     }
5271     return Val;
5272   }
5273
5274   // If all elements are constants and the case above didn't get hit, fall back
5275   // to the default expansion, which will generate a load from the constant
5276   // pool.
5277   if (isConstant)
5278     return SDValue();
5279
5280   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5281   if (NumElts >= 4) {
5282     SDValue shuffle = ReconstructShuffle(Op, DAG);
5283     if (shuffle != SDValue())
5284       return shuffle;
5285   }
5286
5287   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5288   // know the default expansion would otherwise fall back on something even
5289   // worse. For a vector with one or two non-undef values, that's
5290   // scalar_to_vector for the elements followed by a shuffle (provided the
5291   // shuffle is valid for the target) and materialization element by element
5292   // on the stack followed by a load for everything else.
5293   if (!isConstant && !usesOnlyOneValue) {
5294     SDValue Vec = DAG.getUNDEF(VT);
5295     SDValue Op0 = Op.getOperand(0);
5296     unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5297     unsigned i = 0;
5298     // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5299     // a) Avoid a RMW dependency on the full vector register, and
5300     // b) Allow the register coalescer to fold away the copy if the
5301     //    value is already in an S or D register.
5302     if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5303       unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5304       MachineSDNode *N =
5305           DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5306                              DAG.getTargetConstant(SubIdx, MVT::i32));
5307       Vec = SDValue(N, 0);
5308       ++i;
5309     }
5310     for (; i < NumElts; ++i) {
5311       SDValue V = Op.getOperand(i);
5312       if (V.getOpcode() == ISD::UNDEF)
5313         continue;
5314       SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5315       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5316     }
5317     return Vec;
5318   }
5319
5320   // Just use the default expansion. We failed to find a better alternative.
5321   return SDValue();
5322 }
5323
5324 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5325                                                     SelectionDAG &DAG) const {
5326   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5327
5328   // Check for non-constant lane.
5329   if (!isa<ConstantSDNode>(Op.getOperand(2)))
5330     return SDValue();
5331
5332   EVT VT = Op.getOperand(0).getValueType();
5333
5334   // Insertion/extraction are legal for V128 types.
5335   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5336       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5337     return Op;
5338
5339   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5340       VT != MVT::v1i64 && VT != MVT::v2f32)
5341     return SDValue();
5342
5343   // For V64 types, we perform insertion by expanding the value
5344   // to a V128 type and perform the insertion on that.
5345   SDLoc DL(Op);
5346   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5347   EVT WideTy = WideVec.getValueType();
5348
5349   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5350                              Op.getOperand(1), Op.getOperand(2));
5351   // Re-narrow the resultant vector.
5352   return NarrowVector(Node, DAG);
5353 }
5354
5355 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5356                                                      SelectionDAG &DAG) const {
5357   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5358
5359   // Check for non-constant lane.
5360   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5361     return SDValue();
5362
5363   EVT VT = Op.getOperand(0).getValueType();
5364
5365   // Insertion/extraction are legal for V128 types.
5366   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5367       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5368     return Op;
5369
5370   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5371       VT != MVT::v1i64 && VT != MVT::v2f32)
5372     return SDValue();
5373
5374   // For V64 types, we perform extraction by expanding the value
5375   // to a V128 type and perform the extraction on that.
5376   SDLoc DL(Op);
5377   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5378   EVT WideTy = WideVec.getValueType();
5379
5380   EVT ExtrTy = WideTy.getVectorElementType();
5381   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5382     ExtrTy = MVT::i32;
5383
5384   // For extractions, we just return the result directly.
5385   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5386                      Op.getOperand(1));
5387 }
5388
5389 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5390                                                     SelectionDAG &DAG) const {
5391   EVT VT = Op.getOperand(0).getValueType();
5392   SDLoc dl(Op);
5393   // Just in case...
5394   if (!VT.isVector())
5395     return SDValue();
5396
5397   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5398   if (!Cst)
5399     return SDValue();
5400   unsigned Val = Cst->getZExtValue();
5401
5402   unsigned Size = Op.getValueType().getSizeInBits();
5403   if (Val == 0) {
5404     switch (Size) {
5405     case 8:
5406       return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5407                                         Op.getOperand(0));
5408     case 16:
5409       return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5410                                         Op.getOperand(0));
5411     case 32:
5412       return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5413                                         Op.getOperand(0));
5414     case 64:
5415       return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5416                                         Op.getOperand(0));
5417     default:
5418       llvm_unreachable("Unexpected vector type in extract_subvector!");
5419     }
5420   }
5421   // If this is extracting the upper 64-bits of a 128-bit vector, we match
5422   // that directly.
5423   if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5424     return Op;
5425
5426   return SDValue();
5427 }
5428
5429 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5430                                              EVT VT) const {
5431   if (VT.getVectorNumElements() == 4 &&
5432       (VT.is128BitVector() || VT.is64BitVector())) {
5433     unsigned PFIndexes[4];
5434     for (unsigned i = 0; i != 4; ++i) {
5435       if (M[i] < 0)
5436         PFIndexes[i] = 8;
5437       else
5438         PFIndexes[i] = M[i];
5439     }
5440
5441     // Compute the index in the perfect shuffle table.
5442     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5443                             PFIndexes[2] * 9 + PFIndexes[3];
5444     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5445     unsigned Cost = (PFEntry >> 30);
5446
5447     if (Cost <= 4)
5448       return true;
5449   }
5450
5451   bool DummyBool;
5452   int DummyInt;
5453   unsigned DummyUnsigned;
5454
5455   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5456           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5457           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5458           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5459           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5460           isZIPMask(M, VT, DummyUnsigned) ||
5461           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5462           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5463           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5464           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5465           isConcatMask(M, VT, VT.getSizeInBits() == 128));
5466 }
5467
5468 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5469 /// operand of a vector shift operation, where all the elements of the
5470 /// build_vector must have the same constant integer value.
5471 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5472   // Ignore bit_converts.
5473   while (Op.getOpcode() == ISD::BITCAST)
5474     Op = Op.getOperand(0);
5475   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5476   APInt SplatBits, SplatUndef;
5477   unsigned SplatBitSize;
5478   bool HasAnyUndefs;
5479   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5480                                     HasAnyUndefs, ElementBits) ||
5481       SplatBitSize > ElementBits)
5482     return false;
5483   Cnt = SplatBits.getSExtValue();
5484   return true;
5485 }
5486
5487 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5488 /// operand of a vector shift left operation.  That value must be in the range:
5489 ///   0 <= Value < ElementBits for a left shift; or
5490 ///   0 <= Value <= ElementBits for a long left shift.
5491 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5492   assert(VT.isVector() && "vector shift count is not a vector type");
5493   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5494   if (!getVShiftImm(Op, ElementBits, Cnt))
5495     return false;
5496   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5497 }
5498
5499 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5500 /// operand of a vector shift right operation.  For a shift opcode, the value
5501 /// is positive, but for an intrinsic the value count must be negative. The
5502 /// absolute value must be in the range:
5503 ///   1 <= |Value| <= ElementBits for a right shift; or
5504 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
5505 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5506                          int64_t &Cnt) {
5507   assert(VT.isVector() && "vector shift count is not a vector type");
5508   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5509   if (!getVShiftImm(Op, ElementBits, Cnt))
5510     return false;
5511   if (isIntrinsic)
5512     Cnt = -Cnt;
5513   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5514 }
5515
5516 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5517                                                     SelectionDAG &DAG) const {
5518   EVT VT = Op.getValueType();
5519   SDLoc DL(Op);
5520   int64_t Cnt;
5521
5522   if (!Op.getOperand(1).getValueType().isVector())
5523     return Op;
5524   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5525
5526   switch (Op.getOpcode()) {
5527   default:
5528     llvm_unreachable("unexpected shift opcode");
5529
5530   case ISD::SHL:
5531     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5532       return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5533                          DAG.getConstant(Cnt, MVT::i32));
5534     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5535                        DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5536                        Op.getOperand(0), Op.getOperand(1));
5537   case ISD::SRA:
5538   case ISD::SRL:
5539     // Right shift immediate
5540     if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5541         Cnt < EltSize) {
5542       unsigned Opc =
5543           (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5544       return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5545                          DAG.getConstant(Cnt, MVT::i32));
5546     }
5547
5548     // Right shift register.  Note, there is not a shift right register
5549     // instruction, but the shift left register instruction takes a signed
5550     // value, where negative numbers specify a right shift.
5551     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5552                                                 : Intrinsic::arm64_neon_ushl;
5553     // negate the shift amount
5554     SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5555     SDValue NegShiftLeft =
5556         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5557                     DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5558     return NegShiftLeft;
5559   }
5560
5561   return SDValue();
5562 }
5563
5564 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5565                                     ARM64CC::CondCode CC, bool NoNans, EVT VT,
5566                                     SDLoc dl, SelectionDAG &DAG) {
5567   EVT SrcVT = LHS.getValueType();
5568
5569   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5570   APInt CnstBits(VT.getSizeInBits(), 0);
5571   APInt UndefBits(VT.getSizeInBits(), 0);
5572   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5573   bool IsZero = IsCnst && (CnstBits == 0);
5574
5575   if (SrcVT.getVectorElementType().isFloatingPoint()) {
5576     switch (CC) {
5577     default:
5578       return SDValue();
5579     case ARM64CC::NE: {
5580       SDValue Fcmeq;
5581       if (IsZero)
5582         Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5583       else
5584         Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5585       return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5586     }
5587     case ARM64CC::EQ:
5588       if (IsZero)
5589         return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5590       return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5591     case ARM64CC::GE:
5592       if (IsZero)
5593         return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5594       return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5595     case ARM64CC::GT:
5596       if (IsZero)
5597         return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5598       return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5599     case ARM64CC::LS:
5600       if (IsZero)
5601         return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5602       return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5603     case ARM64CC::LT:
5604       if (!NoNans)
5605         return SDValue();
5606     // If we ignore NaNs then we can use to the MI implementation.
5607     // Fallthrough.
5608     case ARM64CC::MI:
5609       if (IsZero)
5610         return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5611       return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5612     }
5613   }
5614
5615   switch (CC) {
5616   default:
5617     return SDValue();
5618   case ARM64CC::NE: {
5619     SDValue Cmeq;
5620     if (IsZero)
5621       Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5622     else
5623       Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5624     return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5625   }
5626   case ARM64CC::EQ:
5627     if (IsZero)
5628       return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5629     return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5630   case ARM64CC::GE:
5631     if (IsZero)
5632       return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5633     return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5634   case ARM64CC::GT:
5635     if (IsZero)
5636       return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5637     return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5638   case ARM64CC::LE:
5639     if (IsZero)
5640       return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5641     return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5642   case ARM64CC::LS:
5643     return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5644   case ARM64CC::LO:
5645     return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5646   case ARM64CC::LT:
5647     if (IsZero)
5648       return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5649     return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5650   case ARM64CC::HI:
5651     return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5652   case ARM64CC::HS:
5653     return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5654   }
5655 }
5656
5657 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5658   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5659   SDValue LHS = Op.getOperand(0);
5660   SDValue RHS = Op.getOperand(1);
5661   SDLoc dl(Op);
5662
5663   if (LHS.getValueType().getVectorElementType().isInteger()) {
5664     assert(LHS.getValueType() == RHS.getValueType());
5665     ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5666     return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5667                                 DAG);
5668   }
5669
5670   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5671          LHS.getValueType().getVectorElementType() == MVT::f64);
5672
5673   // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5674   // clean.  Some of them require two branches to implement.
5675   ARM64CC::CondCode CC1, CC2;
5676   bool ShouldInvert;
5677   changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5678
5679   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5680   SDValue Cmp =
5681       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5682   if (!Cmp.getNode())
5683     return SDValue();
5684
5685   if (CC2 != ARM64CC::AL) {
5686     SDValue Cmp2 =
5687         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5688     if (!Cmp2.getNode())
5689       return SDValue();
5690
5691     Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5692   }
5693
5694   if (ShouldInvert)
5695     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5696
5697   return Cmp;
5698 }
5699
5700 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5701 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
5702 /// specified in the intrinsic calls.
5703 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5704                                              const CallInst &I,
5705                                              unsigned Intrinsic) const {
5706   switch (Intrinsic) {
5707   case Intrinsic::arm64_neon_ld2:
5708   case Intrinsic::arm64_neon_ld3:
5709   case Intrinsic::arm64_neon_ld4:
5710   case Intrinsic::arm64_neon_ld1x2:
5711   case Intrinsic::arm64_neon_ld1x3:
5712   case Intrinsic::arm64_neon_ld1x4:
5713   case Intrinsic::arm64_neon_ld2lane:
5714   case Intrinsic::arm64_neon_ld3lane:
5715   case Intrinsic::arm64_neon_ld4lane:
5716   case Intrinsic::arm64_neon_ld2r:
5717   case Intrinsic::arm64_neon_ld3r:
5718   case Intrinsic::arm64_neon_ld4r: {
5719     Info.opc = ISD::INTRINSIC_W_CHAIN;
5720     // Conservatively set memVT to the entire set of vectors loaded.
5721     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5722     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5723     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5724     Info.offset = 0;
5725     Info.align = 0;
5726     Info.vol = false; // volatile loads with NEON intrinsics not supported
5727     Info.readMem = true;
5728     Info.writeMem = false;
5729     return true;
5730   }
5731   case Intrinsic::arm64_neon_st2:
5732   case Intrinsic::arm64_neon_st3:
5733   case Intrinsic::arm64_neon_st4:
5734   case Intrinsic::arm64_neon_st1x2:
5735   case Intrinsic::arm64_neon_st1x3:
5736   case Intrinsic::arm64_neon_st1x4:
5737   case Intrinsic::arm64_neon_st2lane:
5738   case Intrinsic::arm64_neon_st3lane:
5739   case Intrinsic::arm64_neon_st4lane: {
5740     Info.opc = ISD::INTRINSIC_VOID;
5741     // Conservatively set memVT to the entire set of vectors stored.
5742     unsigned NumElts = 0;
5743     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5744       Type *ArgTy = I.getArgOperand(ArgI)->getType();
5745       if (!ArgTy->isVectorTy())
5746         break;
5747       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5748     }
5749     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5750     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5751     Info.offset = 0;
5752     Info.align = 0;
5753     Info.vol = false; // volatile stores with NEON intrinsics not supported
5754     Info.readMem = false;
5755     Info.writeMem = true;
5756     return true;
5757   }
5758   case Intrinsic::arm64_ldaxr:
5759   case Intrinsic::arm64_ldxr: {
5760     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5761     Info.opc = ISD::INTRINSIC_W_CHAIN;
5762     Info.memVT = MVT::getVT(PtrTy->getElementType());
5763     Info.ptrVal = I.getArgOperand(0);
5764     Info.offset = 0;
5765     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5766     Info.vol = true;
5767     Info.readMem = true;
5768     Info.writeMem = false;
5769     return true;
5770   }
5771   case Intrinsic::arm64_stlxr:
5772   case Intrinsic::arm64_stxr: {
5773     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5774     Info.opc = ISD::INTRINSIC_W_CHAIN;
5775     Info.memVT = MVT::getVT(PtrTy->getElementType());
5776     Info.ptrVal = I.getArgOperand(1);
5777     Info.offset = 0;
5778     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5779     Info.vol = true;
5780     Info.readMem = false;
5781     Info.writeMem = true;
5782     return true;
5783   }
5784   case Intrinsic::arm64_ldaxp:
5785   case Intrinsic::arm64_ldxp: {
5786     Info.opc = ISD::INTRINSIC_W_CHAIN;
5787     Info.memVT = MVT::i128;
5788     Info.ptrVal = I.getArgOperand(0);
5789     Info.offset = 0;
5790     Info.align = 16;
5791     Info.vol = true;
5792     Info.readMem = true;
5793     Info.writeMem = false;
5794     return true;
5795   }
5796   case Intrinsic::arm64_stlxp:
5797   case Intrinsic::arm64_stxp: {
5798     Info.opc = ISD::INTRINSIC_W_CHAIN;
5799     Info.memVT = MVT::i128;
5800     Info.ptrVal = I.getArgOperand(2);
5801     Info.offset = 0;
5802     Info.align = 16;
5803     Info.vol = true;
5804     Info.readMem = false;
5805     Info.writeMem = true;
5806     return true;
5807   }
5808   default:
5809     break;
5810   }
5811
5812   return false;
5813 }
5814
5815 // Truncations from 64-bit GPR to 32-bit GPR is free.
5816 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5817   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5818     return false;
5819   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5820   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5821   if (NumBits1 <= NumBits2)
5822     return false;
5823   return true;
5824 }
5825 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5826   if (!VT1.isInteger() || !VT2.isInteger())
5827     return false;
5828   unsigned NumBits1 = VT1.getSizeInBits();
5829   unsigned NumBits2 = VT2.getSizeInBits();
5830   if (NumBits1 <= NumBits2)
5831     return false;
5832   return true;
5833 }
5834
5835 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5836 // 64-bit GPR.
5837 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5838   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5839     return false;
5840   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5841   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5842   if (NumBits1 == 32 && NumBits2 == 64)
5843     return true;
5844   return false;
5845 }
5846 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5847   if (!VT1.isInteger() || !VT2.isInteger())
5848     return false;
5849   unsigned NumBits1 = VT1.getSizeInBits();
5850   unsigned NumBits2 = VT2.getSizeInBits();
5851   if (NumBits1 == 32 && NumBits2 == 64)
5852     return true;
5853   return false;
5854 }
5855
5856 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5857   EVT VT1 = Val.getValueType();
5858   if (isZExtFree(VT1, VT2)) {
5859     return true;
5860   }
5861
5862   if (Val.getOpcode() != ISD::LOAD)
5863     return false;
5864
5865   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5866   return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5867           VT2.isInteger() && VT1.getSizeInBits() <= 32);
5868 }
5869
5870 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5871                                         unsigned &RequiredAligment) const {
5872   if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5873     return false;
5874   // Cyclone supports unaligned accesses.
5875   RequiredAligment = 0;
5876   unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5877   return NumBits == 32 || NumBits == 64;
5878 }
5879
5880 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5881                                         unsigned &RequiredAligment) const {
5882   if (!LoadedType.isSimple() ||
5883       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5884     return false;
5885   // Cyclone supports unaligned accesses.
5886   RequiredAligment = 0;
5887   unsigned NumBits = LoadedType.getSizeInBits();
5888   return NumBits == 32 || NumBits == 64;
5889 }
5890
5891 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5892                        unsigned AlignCheck) {
5893   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5894           (DstAlign == 0 || DstAlign % AlignCheck == 0));
5895 }
5896
5897 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5898                                              unsigned SrcAlign, bool IsMemset,
5899                                              bool ZeroMemset, bool MemcpyStrSrc,
5900                                              MachineFunction &MF) const {
5901   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5902   // instruction to materialize the v2i64 zero and one store (with restrictive
5903   // addressing mode). Just do two i64 store of zero-registers.
5904   bool Fast;
5905   const Function *F = MF.getFunction();
5906   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
5907       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5908                                        Attribute::NoImplicitFloat) &&
5909       (memOpAlign(SrcAlign, DstAlign, 16) ||
5910        (allowsUnalignedMemoryAccesses(MVT::f128, 0, &Fast) && Fast)))
5911     return MVT::f128;
5912
5913   return Size >= 8 ? MVT::i64 : MVT::i32;
5914 }
5915
5916 // 12-bit optionally shifted immediates are legal for adds.
5917 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5918   if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5919     return true;
5920   return false;
5921 }
5922
5923 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5924 // immediates is the same as for an add or a sub.
5925 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5926   if (Immed < 0)
5927     Immed *= -1;
5928   return isLegalAddImmediate(Immed);
5929 }
5930
5931 /// isLegalAddressingMode - Return true if the addressing mode represented
5932 /// by AM is legal for this target, for a load/store of the specified type.
5933 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5934                                                 Type *Ty) const {
5935   // ARM64 has five basic addressing modes:
5936   //  reg
5937   //  reg + 9-bit signed offset
5938   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
5939   //  reg1 + reg2
5940   //  reg + SIZE_IN_BYTES * reg
5941
5942   // No global is ever allowed as a base.
5943   if (AM.BaseGV)
5944     return false;
5945
5946   // No reg+reg+imm addressing.
5947   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5948     return false;
5949
5950   // check reg + imm case:
5951   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5952   uint64_t NumBytes = 0;
5953   if (Ty->isSized()) {
5954     uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5955     NumBytes = NumBits / 8;
5956     if (!isPowerOf2_64(NumBits))
5957       NumBytes = 0;
5958   }
5959
5960   if (!AM.Scale) {
5961     int64_t Offset = AM.BaseOffs;
5962
5963     // 9-bit signed offset
5964     if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5965       return true;
5966
5967     // 12-bit unsigned offset
5968     unsigned shift = Log2_64(NumBytes);
5969     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5970         // Must be a multiple of NumBytes (NumBytes is a power of 2)
5971         (Offset >> shift) << shift == Offset)
5972       return true;
5973     return false;
5974   }
5975
5976   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5977
5978   if (!AM.Scale || AM.Scale == 1 ||
5979       (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5980     return true;
5981   return false;
5982 }
5983
5984 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5985                                               Type *Ty) const {
5986   // Scaling factors are not free at all.
5987   // Operands                     | Rt Latency
5988   // -------------------------------------------
5989   // Rt, [Xn, Xm]                 | 4
5990   // -------------------------------------------
5991   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
5992   // Rt, [Xn, Wm, <extend> #imm]  |
5993   if (isLegalAddressingMode(AM, Ty))
5994     // Scale represents reg2 * scale, thus account for 1 if
5995     // it is not equal to 0 or 1.
5996     return AM.Scale != 0 && AM.Scale != 1;
5997   return -1;
5998 }
5999
6000 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6001   VT = VT.getScalarType();
6002
6003   if (!VT.isSimple())
6004     return false;
6005
6006   switch (VT.getSimpleVT().SimpleTy) {
6007   case MVT::f32:
6008   case MVT::f64:
6009     return true;
6010   default:
6011     break;
6012   }
6013
6014   return false;
6015 }
6016
6017 const MCPhysReg *
6018 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6019   // LR is a callee-save register, but we must treat it as clobbered by any call
6020   // site. Hence we include LR in the scratch registers, which are in turn added
6021   // as implicit-defs for stackmaps and patchpoints.
6022   static const MCPhysReg ScratchRegs[] = {
6023     ARM64::X16, ARM64::X17, ARM64::LR, 0
6024   };
6025   return ScratchRegs;
6026 }
6027
6028 bool ARM64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6029   EVT VT = N->getValueType(0);
6030     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6031     // it with shift to let it be lowered to UBFX.
6032   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6033       isa<ConstantSDNode>(N->getOperand(1))) {
6034     uint64_t TruncMask = N->getConstantOperandVal(1);
6035     if (isMask_64(TruncMask) &&
6036       N->getOperand(0).getOpcode() == ISD::SRL &&
6037       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6038       return false;
6039   }
6040   return true;
6041 }
6042
6043 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6044                                                             Type *Ty) const {
6045   assert(Ty->isIntegerTy());
6046
6047   unsigned BitSize = Ty->getPrimitiveSizeInBits();
6048   if (BitSize == 0)
6049     return false;
6050
6051   int64_t Val = Imm.getSExtValue();
6052   if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
6053     return true;
6054
6055   if ((int64_t)Val < 0)
6056     Val = ~Val;
6057   if (BitSize == 32)
6058     Val &= (1LL << 32) - 1;
6059
6060   unsigned LZ = countLeadingZeros((uint64_t)Val);
6061   unsigned Shift = (63 - LZ) / 16;
6062   // MOVZ is free so return true for one or fewer MOVK.
6063   return (Shift < 3) ? true : false;
6064 }
6065
6066 // Generate SUBS and CSEL for integer abs.
6067 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6068   EVT VT = N->getValueType(0);
6069
6070   SDValue N0 = N->getOperand(0);
6071   SDValue N1 = N->getOperand(1);
6072   SDLoc DL(N);
6073
6074   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6075   // and change it to SUB and CSEL.
6076   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6077       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6078       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6079     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6080       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6081         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6082                                   N0.getOperand(0));
6083         // Generate SUBS & CSEL.
6084         SDValue Cmp =
6085             DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6086                         N0.getOperand(0), DAG.getConstant(0, VT));
6087         return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6088                            DAG.getConstant(ARM64CC::PL, MVT::i32),
6089                            SDValue(Cmp.getNode(), 1));
6090       }
6091   return SDValue();
6092 }
6093
6094 // performXorCombine - Attempts to handle integer ABS.
6095 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6096                                  TargetLowering::DAGCombinerInfo &DCI,
6097                                  const ARM64Subtarget *Subtarget) {
6098   if (DCI.isBeforeLegalizeOps())
6099     return SDValue();
6100
6101   return performIntegerAbsCombine(N, DAG);
6102 }
6103
6104 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6105                                  TargetLowering::DAGCombinerInfo &DCI,
6106                                  const ARM64Subtarget *Subtarget) {
6107   if (DCI.isBeforeLegalizeOps())
6108     return SDValue();
6109
6110   // Multiplication of a power of two plus/minus one can be done more
6111   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6112   // future CPUs have a cheaper MADD instruction, this may need to be
6113   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6114   // 64-bit is 5 cycles, so this is always a win.
6115   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6116     APInt Value = C->getAPIntValue();
6117     EVT VT = N->getValueType(0);
6118     APInt VP1 = Value + 1;
6119     if (VP1.isPowerOf2()) {
6120       // Multiplying by one less than a power of two, replace with a shift
6121       // and a subtract.
6122       SDValue ShiftedVal =
6123           DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6124                       DAG.getConstant(VP1.logBase2(), MVT::i64));
6125       return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6126     }
6127     APInt VM1 = Value - 1;
6128     if (VM1.isPowerOf2()) {
6129       // Multiplying by one more than a power of two, replace with a shift
6130       // and an add.
6131       SDValue ShiftedVal =
6132           DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6133                       DAG.getConstant(VM1.logBase2(), MVT::i64));
6134       return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6135     }
6136   }
6137   return SDValue();
6138 }
6139
6140 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6141   EVT VT = N->getValueType(0);
6142   if (VT != MVT::f32 && VT != MVT::f64)
6143     return SDValue();
6144   // Only optimize when the source and destination types have the same width.
6145   if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6146     return SDValue();
6147
6148   // If the result of an integer load is only used by an integer-to-float
6149   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6150   // This eliminates an "integer-to-vector-move UOP and improve throughput.
6151   SDValue N0 = N->getOperand(0);
6152   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6153       // Do not change the width of a volatile load.
6154       !cast<LoadSDNode>(N0)->isVolatile()) {
6155     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6156     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6157                                LN0->getPointerInfo(), LN0->isVolatile(),
6158                                LN0->isNonTemporal(), LN0->isInvariant(),
6159                                LN0->getAlignment());
6160
6161     // Make sure successors of the original load stay after it by updating them
6162     // to use the new Chain.
6163     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6164
6165     unsigned Opcode =
6166         (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6167     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6168   }
6169
6170   return SDValue();
6171 }
6172
6173 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6174 /// searches for and classifies those shifts.
6175 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6176                          bool &FromHi) {
6177   if (N.getOpcode() == ISD::SHL)
6178     FromHi = false;
6179   else if (N.getOpcode() == ISD::SRL)
6180     FromHi = true;
6181   else
6182     return false;
6183
6184   if (!isa<ConstantSDNode>(N.getOperand(1)))
6185     return false;
6186
6187   ShiftAmount = N->getConstantOperandVal(1);
6188   Src = N->getOperand(0);
6189   return true;
6190 }
6191
6192 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6193 /// registers viewed as a high/low pair. This function looks for the pattern:
6194 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6195 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6196 /// independent.
6197 static SDValue tryCombineToEXTR(SDNode *N,
6198                                 TargetLowering::DAGCombinerInfo &DCI) {
6199   SelectionDAG &DAG = DCI.DAG;
6200   SDLoc DL(N);
6201   EVT VT = N->getValueType(0);
6202
6203   assert(N->getOpcode() == ISD::OR && "Unexpected root");
6204
6205   if (VT != MVT::i32 && VT != MVT::i64)
6206     return SDValue();
6207
6208   SDValue LHS;
6209   uint32_t ShiftLHS = 0;
6210   bool LHSFromHi = 0;
6211   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6212     return SDValue();
6213
6214   SDValue RHS;
6215   uint32_t ShiftRHS = 0;
6216   bool RHSFromHi = 0;
6217   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6218     return SDValue();
6219
6220   // If they're both trying to come from the high part of the register, they're
6221   // not really an EXTR.
6222   if (LHSFromHi == RHSFromHi)
6223     return SDValue();
6224
6225   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6226     return SDValue();
6227
6228   if (LHSFromHi) {
6229     std::swap(LHS, RHS);
6230     std::swap(ShiftLHS, ShiftRHS);
6231   }
6232
6233   return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6234                      DAG.getConstant(ShiftRHS, MVT::i64));
6235 }
6236
6237 static SDValue tryCombineToBSL(SDNode *N,
6238                                 TargetLowering::DAGCombinerInfo &DCI) {
6239   EVT VT = N->getValueType(0);
6240   SelectionDAG &DAG = DCI.DAG;
6241   SDLoc DL(N);
6242
6243   if (!VT.isVector())
6244     return SDValue();
6245
6246   SDValue N0 = N->getOperand(0);
6247   if (N0.getOpcode() != ISD::AND)
6248     return SDValue();
6249
6250   SDValue N1 = N->getOperand(1);
6251   if (N1.getOpcode() != ISD::AND)
6252     return SDValue();
6253
6254   // We only have to look for constant vectors here since the general, variable
6255   // case can be handled in TableGen.
6256   unsigned Bits = VT.getVectorElementType().getSizeInBits();
6257   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6258   for (int i = 1; i >= 0; --i)
6259     for (int j = 1; j >= 0; --j) {
6260       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6261       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6262       if (!BVN0 || !BVN1)
6263         continue;
6264
6265       bool FoundMatch = true;
6266       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6267         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6268         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6269         if (!CN0 || !CN1 ||
6270             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6271           FoundMatch = false;
6272           break;
6273         }
6274       }
6275
6276       if (FoundMatch)
6277         return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6278                            N0->getOperand(1 - i), N1->getOperand(1 - j));
6279     }
6280
6281   return SDValue();
6282 }
6283
6284 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6285                                 const ARM64Subtarget *Subtarget) {
6286   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6287   if (!EnableARM64ExtrGeneration)
6288     return SDValue();
6289   SelectionDAG &DAG = DCI.DAG;
6290   EVT VT = N->getValueType(0);
6291
6292   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6293     return SDValue();
6294
6295   SDValue Res = tryCombineToEXTR(N, DCI);
6296   if (Res.getNode())
6297     return Res;
6298
6299   Res = tryCombineToBSL(N, DCI);
6300   if (Res.getNode())
6301     return Res;
6302
6303   return SDValue();
6304 }
6305
6306 static SDValue performBitcastCombine(SDNode *N,
6307                                      TargetLowering::DAGCombinerInfo &DCI,
6308                                      SelectionDAG &DAG) {
6309   // Wait 'til after everything is legalized to try this. That way we have
6310   // legal vector types and such.
6311   if (DCI.isBeforeLegalizeOps())
6312     return SDValue();
6313
6314   // Remove extraneous bitcasts around an extract_subvector.
6315   // For example,
6316   //    (v4i16 (bitconvert
6317   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6318   //  becomes
6319   //    (extract_subvector ((v8i16 ...), (i64 4)))
6320
6321   // Only interested in 64-bit vectors as the ultimate result.
6322   EVT VT = N->getValueType(0);
6323   if (!VT.isVector())
6324     return SDValue();
6325   if (VT.getSimpleVT().getSizeInBits() != 64)
6326     return SDValue();
6327   // Is the operand an extract_subvector starting at the beginning or halfway
6328   // point of the vector? A low half may also come through as an
6329   // EXTRACT_SUBREG, so look for that, too.
6330   SDValue Op0 = N->getOperand(0);
6331   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6332       !(Op0->isMachineOpcode() &&
6333         Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6334     return SDValue();
6335   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6336   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6337     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6338       return SDValue();
6339   } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6340     if (idx != ARM64::dsub)
6341       return SDValue();
6342     // The dsub reference is equivalent to a lane zero subvector reference.
6343     idx = 0;
6344   }
6345   // Look through the bitcast of the input to the extract.
6346   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6347     return SDValue();
6348   SDValue Source = Op0->getOperand(0)->getOperand(0);
6349   // If the source type has twice the number of elements as our destination
6350   // type, we know this is an extract of the high or low half of the vector.
6351   EVT SVT = Source->getValueType(0);
6352   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6353     return SDValue();
6354
6355   DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6356
6357   // Create the simplified form to just extract the low or high half of the
6358   // vector directly rather than bothering with the bitcasts.
6359   SDLoc dl(N);
6360   unsigned NumElements = VT.getVectorNumElements();
6361   if (idx) {
6362     SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6363     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6364   } else {
6365     SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6366     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6367                                       Source, SubReg),
6368                    0);
6369   }
6370 }
6371
6372 static SDValue performConcatVectorsCombine(SDNode *N,
6373                                            TargetLowering::DAGCombinerInfo &DCI,
6374                                            SelectionDAG &DAG) {
6375   // Wait 'til after everything is legalized to try this. That way we have
6376   // legal vector types and such.
6377   if (DCI.isBeforeLegalizeOps())
6378     return SDValue();
6379
6380   SDLoc dl(N);
6381   EVT VT = N->getValueType(0);
6382
6383   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6384   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6385   // canonicalise to that.
6386   if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6387     assert(VT.getVectorElementType().getSizeInBits() == 64);
6388     return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6389                        WidenVector(N->getOperand(0), DAG),
6390                        DAG.getConstant(0, MVT::i64));
6391   }
6392
6393   // Canonicalise concat_vectors so that the right-hand vector has as few
6394   // bit-casts as possible before its real operation. The primary matching
6395   // destination for these operations will be the narrowing "2" instructions,
6396   // which depend on the operation being performed on this right-hand vector.
6397   // For example,
6398   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
6399   // becomes
6400   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6401
6402   SDValue Op1 = N->getOperand(1);
6403   if (Op1->getOpcode() != ISD::BITCAST)
6404     return SDValue();
6405   SDValue RHS = Op1->getOperand(0);
6406   MVT RHSTy = RHS.getValueType().getSimpleVT();
6407   // If the RHS is not a vector, this is not the pattern we're looking for.
6408   if (!RHSTy.isVector())
6409     return SDValue();
6410
6411   DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6412
6413   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6414                                   RHSTy.getVectorNumElements() * 2);
6415   return DAG.getNode(
6416       ISD::BITCAST, dl, VT,
6417       DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6418                   DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6419 }
6420
6421 static SDValue tryCombineFixedPointConvert(SDNode *N,
6422                                            TargetLowering::DAGCombinerInfo &DCI,
6423                                            SelectionDAG &DAG) {
6424   // Wait 'til after everything is legalized to try this. That way we have
6425   // legal vector types and such.
6426   if (DCI.isBeforeLegalizeOps())
6427     return SDValue();
6428   // Transform a scalar conversion of a value from a lane extract into a
6429   // lane extract of a vector conversion. E.g., from foo1 to foo2:
6430   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6431   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6432   //
6433   // The second form interacts better with instruction selection and the
6434   // register allocator to avoid cross-class register copies that aren't
6435   // coalescable due to a lane reference.
6436
6437   // Check the operand and see if it originates from a lane extract.
6438   SDValue Op1 = N->getOperand(1);
6439   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6440     // Yep, no additional predication needed. Perform the transform.
6441     SDValue IID = N->getOperand(0);
6442     SDValue Shift = N->getOperand(2);
6443     SDValue Vec = Op1.getOperand(0);
6444     SDValue Lane = Op1.getOperand(1);
6445     EVT ResTy = N->getValueType(0);
6446     EVT VecResTy;
6447     SDLoc DL(N);
6448
6449     // The vector width should be 128 bits by the time we get here, even
6450     // if it started as 64 bits (the extract_vector handling will have
6451     // done so).
6452     assert(Vec.getValueType().getSizeInBits() == 128 &&
6453            "unexpected vector size on extract_vector_elt!");
6454     if (Vec.getValueType() == MVT::v4i32)
6455       VecResTy = MVT::v4f32;
6456     else if (Vec.getValueType() == MVT::v2i64)
6457       VecResTy = MVT::v2f64;
6458     else
6459       assert(0 && "unexpected vector type!");
6460
6461     SDValue Convert =
6462         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6463     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6464   }
6465   return SDValue();
6466 }
6467
6468 // AArch64 high-vector "long" operations are formed by performing the non-high
6469 // version on an extract_subvector of each operand which gets the high half:
6470 //
6471 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6472 //
6473 // However, there are cases which don't have an extract_high explicitly, but
6474 // have another operation that can be made compatible with one for free. For
6475 // example:
6476 //
6477 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
6478 //
6479 // This routine does the actual conversion of such DUPs, once outer routines
6480 // have determined that everything else is in order.
6481 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6482   // We can handle most types of duplicate, but the lane ones have an extra
6483   // operand saying *which* lane, so we need to know.
6484   bool IsDUPLANE;
6485   switch (N.getOpcode()) {
6486   case ARM64ISD::DUP:
6487     IsDUPLANE = false;
6488     break;
6489   case ARM64ISD::DUPLANE8:
6490   case ARM64ISD::DUPLANE16:
6491   case ARM64ISD::DUPLANE32:
6492   case ARM64ISD::DUPLANE64:
6493     IsDUPLANE = true;
6494     break;
6495   default:
6496     return SDValue();
6497   }
6498
6499   MVT NarrowTy = N.getSimpleValueType();
6500   if (!NarrowTy.is64BitVector())
6501     return SDValue();
6502
6503   MVT ElementTy = NarrowTy.getVectorElementType();
6504   unsigned NumElems = NarrowTy.getVectorNumElements();
6505   MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6506
6507   SDValue NewDUP;
6508   if (IsDUPLANE)
6509     NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6510                          N.getOperand(1));
6511   else
6512     NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6513
6514   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6515                      NewDUP, DAG.getConstant(NumElems, MVT::i64));
6516 }
6517
6518 static bool isEssentiallyExtractSubvector(SDValue N) {
6519   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6520     return true;
6521
6522   return N.getOpcode() == ISD::BITCAST &&
6523          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6524 }
6525
6526 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6527 struct GenericSetCCInfo {
6528   const SDValue *Opnd0;
6529   const SDValue *Opnd1;
6530   ISD::CondCode CC;
6531 };
6532
6533 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6534 struct ARM64SetCCInfo {
6535   const SDValue *Cmp;
6536   ARM64CC::CondCode CC;
6537 };
6538
6539 /// \brief Helper structure to keep track of SetCC information.
6540 union SetCCInfo {
6541   GenericSetCCInfo Generic;
6542   ARM64SetCCInfo ARM64;
6543 };
6544
6545 /// \brief Helper structure to be able to read SetCC information.
6546 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6547 /// a GenericSetCCInfo.
6548 struct SetCCInfoAndKind {
6549   SetCCInfo Info;
6550   bool IsARM64;
6551 };
6552
6553 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6554 /// an
6555 /// ARM64 lowered one.
6556 /// \p SetCCInfo is filled accordingly.
6557 /// \post SetCCInfo is meanginfull only when this function returns true.
6558 /// \return True when Op is a kind of SET_CC operation.
6559 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6560   // If this is a setcc, this is straight forward.
6561   if (Op.getOpcode() == ISD::SETCC) {
6562     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6563     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6564     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6565     SetCCInfo.IsARM64 = false;
6566     return true;
6567   }
6568   // Otherwise, check if this is a matching csel instruction.
6569   // In other words:
6570   // - csel 1, 0, cc
6571   // - csel 0, 1, !cc
6572   if (Op.getOpcode() != ARM64ISD::CSEL)
6573     return false;
6574   // Set the information about the operands.
6575   // TODO: we want the operands of the Cmp not the csel
6576   SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6577   SetCCInfo.IsARM64 = true;
6578   SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6579       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6580
6581   // Check that the operands matches the constraints:
6582   // (1) Both operands must be constants.
6583   // (2) One must be 1 and the other must be 0.
6584   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6585   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6586
6587   // Check (1).
6588   if (!TValue || !FValue)
6589     return false;
6590
6591   // Check (2).
6592   if (!TValue->isOne()) {
6593     // Update the comparison when we are interested in !cc.
6594     std::swap(TValue, FValue);
6595     SetCCInfo.Info.ARM64.CC =
6596         ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6597   }
6598   return TValue->isOne() && FValue->isNullValue();
6599 }
6600
6601 // The folding we want to perform is:
6602 // (add x, (setcc cc ...) )
6603 //   -->
6604 // (csel x, (add x, 1), !cc ...)
6605 //
6606 // The latter will get matched to a CSINC instruction.
6607 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6608   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6609   SDValue LHS = Op->getOperand(0);
6610   SDValue RHS = Op->getOperand(1);
6611   SetCCInfoAndKind InfoAndKind;
6612
6613   // If neither operand is a SET_CC, give up.
6614   if (!isSetCC(LHS, InfoAndKind)) {
6615     std::swap(LHS, RHS);
6616     if (!isSetCC(LHS, InfoAndKind))
6617       return SDValue();
6618   }
6619
6620   // FIXME: This could be generatized to work for FP comparisons.
6621   EVT CmpVT = InfoAndKind.IsARM64
6622                   ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6623                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
6624   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6625     return SDValue();
6626
6627   SDValue CCVal;
6628   SDValue Cmp;
6629   SDLoc dl(Op);
6630   if (InfoAndKind.IsARM64) {
6631     CCVal = DAG.getConstant(
6632         ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6633     Cmp = *InfoAndKind.Info.ARM64.Cmp;
6634   } else
6635     Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6636                       *InfoAndKind.Info.Generic.Opnd1,
6637                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6638                       CCVal, DAG, dl);
6639
6640   EVT VT = Op->getValueType(0);
6641   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6642   return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6643 }
6644
6645 // The basic add/sub long vector instructions have variants with "2" on the end
6646 // which act on the high-half of their inputs. They are normally matched by
6647 // patterns like:
6648 //
6649 // (add (zeroext (extract_high LHS)),
6650 //      (zeroext (extract_high RHS)))
6651 // -> uaddl2 vD, vN, vM
6652 //
6653 // However, if one of the extracts is something like a duplicate, this
6654 // instruction can still be used profitably. This function puts the DAG into a
6655 // more appropriate form for those patterns to trigger.
6656 static SDValue performAddSubLongCombine(SDNode *N,
6657                                         TargetLowering::DAGCombinerInfo &DCI,
6658                                         SelectionDAG &DAG) {
6659   if (DCI.isBeforeLegalizeOps())
6660     return SDValue();
6661
6662   MVT VT = N->getSimpleValueType(0);
6663   if (!VT.is128BitVector()) {
6664     if (N->getOpcode() == ISD::ADD)
6665       return performSetccAddFolding(N, DAG);
6666     return SDValue();
6667   }
6668
6669   // Make sure both branches are extended in the same way.
6670   SDValue LHS = N->getOperand(0);
6671   SDValue RHS = N->getOperand(1);
6672   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6673        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6674       LHS.getOpcode() != RHS.getOpcode())
6675     return SDValue();
6676
6677   unsigned ExtType = LHS.getOpcode();
6678
6679   // It's not worth doing if at least one of the inputs isn't already an
6680   // extract, but we don't know which it'll be so we have to try both.
6681   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6682     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6683     if (!RHS.getNode())
6684       return SDValue();
6685
6686     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6687   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6688     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6689     if (!LHS.getNode())
6690       return SDValue();
6691
6692     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6693   }
6694
6695   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6696 }
6697
6698 // Massage DAGs which we can use the high-half "long" operations on into
6699 // something isel will recognize better. E.g.
6700 //
6701 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6702 //   (arm64_neon_umull (extract_high (v2i64 vec)))
6703 //                     (extract_high (v2i64 (dup128 scalar)))))
6704 //
6705 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6706                                        TargetLowering::DAGCombinerInfo &DCI,
6707                                        SelectionDAG &DAG) {
6708   if (DCI.isBeforeLegalizeOps())
6709     return SDValue();
6710
6711   SDValue LHS = N->getOperand(1);
6712   SDValue RHS = N->getOperand(2);
6713   assert(LHS.getValueType().is64BitVector() &&
6714          RHS.getValueType().is64BitVector() &&
6715          "unexpected shape for long operation");
6716
6717   // Either node could be a DUP, but it's not worth doing both of them (you'd
6718   // just as well use the non-high version) so look for a corresponding extract
6719   // operation on the other "wing".
6720   if (isEssentiallyExtractSubvector(LHS)) {
6721     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6722     if (!RHS.getNode())
6723       return SDValue();
6724   } else if (isEssentiallyExtractSubvector(RHS)) {
6725     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6726     if (!LHS.getNode())
6727       return SDValue();
6728   }
6729
6730   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6731                      N->getOperand(0), LHS, RHS);
6732 }
6733
6734 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6735   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6736   unsigned ElemBits = ElemTy.getSizeInBits();
6737
6738   int64_t ShiftAmount;
6739   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6740     APInt SplatValue, SplatUndef;
6741     unsigned SplatBitSize;
6742     bool HasAnyUndefs;
6743     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6744                               HasAnyUndefs, ElemBits) ||
6745         SplatBitSize != ElemBits)
6746       return SDValue();
6747
6748     ShiftAmount = SplatValue.getSExtValue();
6749   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6750     ShiftAmount = CVN->getSExtValue();
6751   } else
6752     return SDValue();
6753
6754   unsigned Opcode;
6755   bool IsRightShift;
6756   switch (IID) {
6757   default:
6758     llvm_unreachable("Unknown shift intrinsic");
6759   case Intrinsic::arm64_neon_sqshl:
6760     Opcode = ARM64ISD::SQSHL_I;
6761     IsRightShift = false;
6762     break;
6763   case Intrinsic::arm64_neon_uqshl:
6764     Opcode = ARM64ISD::UQSHL_I;
6765     IsRightShift = false;
6766     break;
6767   case Intrinsic::arm64_neon_srshl:
6768     Opcode = ARM64ISD::SRSHR_I;
6769     IsRightShift = true;
6770     break;
6771   case Intrinsic::arm64_neon_urshl:
6772     Opcode = ARM64ISD::URSHR_I;
6773     IsRightShift = true;
6774     break;
6775   case Intrinsic::arm64_neon_sqshlu:
6776     Opcode = ARM64ISD::SQSHLU_I;
6777     IsRightShift = false;
6778     break;
6779   }
6780
6781   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6782     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6783                        DAG.getConstant(-ShiftAmount, MVT::i32));
6784   else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6785     return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6786                        DAG.getConstant(ShiftAmount, MVT::i32));
6787
6788   return SDValue();
6789 }
6790
6791 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6792 // the intrinsics must be legal and take an i32, this means there's almost
6793 // certainly going to be a zext in the DAG which we can eliminate.
6794 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6795   SDValue AndN = N->getOperand(2);
6796   if (AndN.getOpcode() != ISD::AND)
6797     return SDValue();
6798
6799   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6800   if (!CMask || CMask->getZExtValue() != Mask)
6801     return SDValue();
6802
6803   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6804                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6805 }
6806
6807 static SDValue performIntrinsicCombine(SDNode *N,
6808                                        TargetLowering::DAGCombinerInfo &DCI,
6809                                        const ARM64Subtarget *Subtarget) {
6810   SelectionDAG &DAG = DCI.DAG;
6811   unsigned IID = getIntrinsicID(N);
6812   switch (IID) {
6813   default:
6814     break;
6815   case Intrinsic::arm64_neon_vcvtfxs2fp:
6816   case Intrinsic::arm64_neon_vcvtfxu2fp:
6817     return tryCombineFixedPointConvert(N, DCI, DAG);
6818     break;
6819   case Intrinsic::arm64_neon_fmax:
6820     return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6821                        N->getOperand(1), N->getOperand(2));
6822   case Intrinsic::arm64_neon_fmin:
6823     return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6824                        N->getOperand(1), N->getOperand(2));
6825   case Intrinsic::arm64_neon_smull:
6826   case Intrinsic::arm64_neon_umull:
6827   case Intrinsic::arm64_neon_pmull:
6828   case Intrinsic::arm64_neon_sqdmull:
6829     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6830   case Intrinsic::arm64_neon_sqshl:
6831   case Intrinsic::arm64_neon_uqshl:
6832   case Intrinsic::arm64_neon_sqshlu:
6833   case Intrinsic::arm64_neon_srshl:
6834   case Intrinsic::arm64_neon_urshl:
6835     return tryCombineShiftImm(IID, N, DAG);
6836   case Intrinsic::arm64_crc32b:
6837   case Intrinsic::arm64_crc32cb:
6838     return tryCombineCRC32(0xff, N, DAG);
6839   case Intrinsic::arm64_crc32h:
6840   case Intrinsic::arm64_crc32ch:
6841     return tryCombineCRC32(0xffff, N, DAG);
6842   }
6843   return SDValue();
6844 }
6845
6846 static SDValue performExtendCombine(SDNode *N,
6847                                     TargetLowering::DAGCombinerInfo &DCI,
6848                                     SelectionDAG &DAG) {
6849   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6850   // we can convert that DUP into another extract_high (of a bigger DUP), which
6851   // helps the backend to decide that an sabdl2 would be useful, saving a real
6852   // extract_high operation.
6853   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6854       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6855     SDNode *ABDNode = N->getOperand(0).getNode();
6856     unsigned IID = getIntrinsicID(ABDNode);
6857     if (IID == Intrinsic::arm64_neon_sabd ||
6858         IID == Intrinsic::arm64_neon_uabd) {
6859       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6860       if (!NewABD.getNode())
6861         return SDValue();
6862
6863       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6864                          NewABD);
6865     }
6866   }
6867
6868   // This is effectively a custom type legalization for ARM64.
6869   //
6870   // Type legalization will split an extend of a small, legal, type to a larger
6871   // illegal type by first splitting the destination type, often creating
6872   // illegal source types, which then get legalized in isel-confusing ways,
6873   // leading to really terrible codegen. E.g.,
6874   //   %result = v8i32 sext v8i8 %value
6875   // becomes
6876   //   %losrc = extract_subreg %value, ...
6877   //   %hisrc = extract_subreg %value, ...
6878   //   %lo = v4i32 sext v4i8 %losrc
6879   //   %hi = v4i32 sext v4i8 %hisrc
6880   // Things go rapidly downhill from there.
6881   //
6882   // For ARM64, the [sz]ext vector instructions can only go up one element
6883   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6884   // take two instructions.
6885   //
6886   // This implies that the most efficient way to do the extend from v8i8
6887   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6888   // the normal splitting to happen for the v8i16->v8i32.
6889
6890   // This is pre-legalization to catch some cases where the default
6891   // type legalization will create ill-tempered code.
6892   if (!DCI.isBeforeLegalizeOps())
6893     return SDValue();
6894
6895   // We're only interested in cleaning things up for non-legal vector types
6896   // here. If both the source and destination are legal, things will just
6897   // work naturally without any fiddling.
6898   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6899   EVT ResVT = N->getValueType(0);
6900   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6901     return SDValue();
6902   // If the vector type isn't a simple VT, it's beyond the scope of what
6903   // we're  worried about here. Let legalization do its thing and hope for
6904   // the best.
6905   if (!ResVT.isSimple())
6906     return SDValue();
6907
6908   SDValue Src = N->getOperand(0);
6909   MVT SrcVT = Src->getValueType(0).getSimpleVT();
6910   // If the source VT is a 64-bit vector, we can play games and get the
6911   // better results we want.
6912   if (SrcVT.getSizeInBits() != 64)
6913     return SDValue();
6914
6915   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6916   unsigned ElementCount = SrcVT.getVectorNumElements();
6917   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6918   SDLoc DL(N);
6919   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6920
6921   // Now split the rest of the operation into two halves, each with a 64
6922   // bit source.
6923   EVT LoVT, HiVT;
6924   SDValue Lo, Hi;
6925   unsigned NumElements = ResVT.getVectorNumElements();
6926   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6927   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6928                                  ResVT.getVectorElementType(), NumElements / 2);
6929
6930   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6931                                LoVT.getVectorNumElements());
6932   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6933                    DAG.getIntPtrConstant(0));
6934   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6935                    DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6936   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6937   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6938
6939   // Now combine the parts back together so we still have a single result
6940   // like the combiner expects.
6941   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6942 }
6943
6944 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6945 /// value. The load store optimizer pass will merge them to store pair stores.
6946 /// This has better performance than a splat of the scalar followed by a split
6947 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6948 /// followed by an ext.b and two stores.
6949 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6950   SDValue StVal = St->getValue();
6951   EVT VT = StVal.getValueType();
6952
6953   // Don't replace floating point stores, they possibly won't be transformed to
6954   // stp because of the store pair suppress pass.
6955   if (VT.isFloatingPoint())
6956     return SDValue();
6957
6958   // Check for insert vector elements.
6959   if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6960     return SDValue();
6961
6962   // We can express a splat as store pair(s) for 2 or 4 elements.
6963   unsigned NumVecElts = VT.getVectorNumElements();
6964   if (NumVecElts != 4 && NumVecElts != 2)
6965     return SDValue();
6966   SDValue SplatVal = StVal.getOperand(1);
6967   unsigned RemainInsertElts = NumVecElts - 1;
6968
6969   // Check that this is a splat.
6970   while (--RemainInsertElts) {
6971     SDValue NextInsertElt = StVal.getOperand(0);
6972     if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6973       return SDValue();
6974     if (NextInsertElt.getOperand(1) != SplatVal)
6975       return SDValue();
6976     StVal = NextInsertElt;
6977   }
6978   unsigned OrigAlignment = St->getAlignment();
6979   unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6980   unsigned Alignment = std::min(OrigAlignment, EltOffset);
6981
6982   // Create scalar stores. This is at least as good as the code sequence for a
6983   // split unaligned store wich is a dup.s, ext.b, and two stores.
6984   // Most of the time the three stores should be replaced by store pair
6985   // instructions (stp).
6986   SDLoc DL(St);
6987   SDValue BasePtr = St->getBasePtr();
6988   SDValue NewST1 =
6989       DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6990                    St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6991
6992   unsigned Offset = EltOffset;
6993   while (--NumVecElts) {
6994     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6995                                     DAG.getConstant(Offset, MVT::i64));
6996     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6997                           St->getPointerInfo(), St->isVolatile(),
6998                           St->isNonTemporal(), Alignment);
6999     Offset += EltOffset;
7000   }
7001   return NewST1;
7002 }
7003
7004 static SDValue performSTORECombine(SDNode *N,
7005                                    TargetLowering::DAGCombinerInfo &DCI,
7006                                    SelectionDAG &DAG,
7007                                    const ARM64Subtarget *Subtarget) {
7008   if (!DCI.isBeforeLegalize())
7009     return SDValue();
7010
7011   StoreSDNode *S = cast<StoreSDNode>(N);
7012   if (S->isVolatile())
7013     return SDValue();
7014
7015   // Cyclone has bad performance on unaligned 16B stores when crossing line and
7016   // page boundries. We want to split such stores.
7017   if (!Subtarget->isCyclone())
7018     return SDValue();
7019
7020   // Don't split at Oz.
7021   MachineFunction &MF = DAG.getMachineFunction();
7022   bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7023       AttributeSet::FunctionIndex, Attribute::MinSize);
7024   if (IsMinSize)
7025     return SDValue();
7026
7027   SDValue StVal = S->getValue();
7028   EVT VT = StVal.getValueType();
7029
7030   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7031   // those up regresses performance on micro-benchmarks and olden/bh.
7032   if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7033     return SDValue();
7034
7035   // Split unaligned 16B stores. They are terrible for performance.
7036   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7037   // extensions can use this to mark that it does not want splitting to happen
7038   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7039   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7040   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7041       S->getAlignment() <= 2)
7042     return SDValue();
7043
7044   // If we get a splat of a scalar convert this vector store to a store of
7045   // scalars. They will be merged into store pairs thereby removing two
7046   // instructions.
7047   SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7048   if (ReplacedSplat != SDValue())
7049     return ReplacedSplat;
7050
7051   SDLoc DL(S);
7052   unsigned NumElts = VT.getVectorNumElements() / 2;
7053   // Split VT into two.
7054   EVT HalfVT =
7055       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7056   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7057                                    DAG.getIntPtrConstant(0));
7058   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7059                                    DAG.getIntPtrConstant(NumElts));
7060   SDValue BasePtr = S->getBasePtr();
7061   SDValue NewST1 =
7062       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7063                    S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7064   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7065                                   DAG.getConstant(8, MVT::i64));
7066   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7067                       S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7068                       S->getAlignment());
7069 }
7070
7071 /// Target-specific DAG combine function for NEON load/store intrinsics
7072 /// to merge base address updates.
7073 static SDValue performNEONPostLDSTCombine(SDNode *N,
7074                                           TargetLowering::DAGCombinerInfo &DCI,
7075                                           SelectionDAG &DAG) {
7076   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7077     return SDValue();
7078
7079   unsigned AddrOpIdx = N->getNumOperands() - 1;
7080   SDValue Addr = N->getOperand(AddrOpIdx);
7081
7082   // Search for a use of the address operand that is an increment.
7083   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7084        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7085     SDNode *User = *UI;
7086     if (User->getOpcode() != ISD::ADD ||
7087         UI.getUse().getResNo() != Addr.getResNo())
7088       continue;
7089
7090     // Check that the add is independent of the load/store.  Otherwise, folding
7091     // it would create a cycle.
7092     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7093       continue;
7094
7095     // Find the new opcode for the updating load/store.
7096     bool IsStore = false;
7097     bool IsLaneOp = false;
7098     bool IsDupOp = false;
7099     unsigned NewOpc = 0;
7100     unsigned NumVecs = 0;
7101     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7102     switch (IntNo) {
7103     default: llvm_unreachable("unexpected intrinsic for Neon base update");
7104     case Intrinsic::arm64_neon_ld2:       NewOpc = ARM64ISD::LD2post;
7105       NumVecs = 2; break;
7106     case Intrinsic::arm64_neon_ld3:       NewOpc = ARM64ISD::LD3post;
7107       NumVecs = 3; break;
7108     case Intrinsic::arm64_neon_ld4:       NewOpc = ARM64ISD::LD4post;
7109       NumVecs = 4; break;
7110     case Intrinsic::arm64_neon_st2:       NewOpc = ARM64ISD::ST2post;
7111       NumVecs = 2; IsStore = true; break;
7112     case Intrinsic::arm64_neon_st3:       NewOpc = ARM64ISD::ST3post;
7113       NumVecs = 3; IsStore = true; break;
7114     case Intrinsic::arm64_neon_st4:       NewOpc = ARM64ISD::ST4post;
7115       NumVecs = 4; IsStore = true; break;
7116     case Intrinsic::arm64_neon_ld1x2:     NewOpc = ARM64ISD::LD1x2post;
7117       NumVecs = 2; break;
7118     case Intrinsic::arm64_neon_ld1x3:     NewOpc = ARM64ISD::LD1x3post;
7119       NumVecs = 3; break;
7120     case Intrinsic::arm64_neon_ld1x4:     NewOpc = ARM64ISD::LD1x4post;
7121       NumVecs = 4; break;
7122     case Intrinsic::arm64_neon_st1x2:     NewOpc = ARM64ISD::ST1x2post;
7123       NumVecs = 2; IsStore = true; break;
7124     case Intrinsic::arm64_neon_st1x3:     NewOpc = ARM64ISD::ST1x3post;
7125       NumVecs = 3; IsStore = true; break;
7126     case Intrinsic::arm64_neon_st1x4:     NewOpc = ARM64ISD::ST1x4post;
7127       NumVecs = 4; IsStore = true; break;
7128     case Intrinsic::arm64_neon_ld2r:      NewOpc = ARM64ISD::LD2DUPpost;
7129       NumVecs = 2; IsDupOp = true; break;
7130     case Intrinsic::arm64_neon_ld3r:      NewOpc = ARM64ISD::LD3DUPpost;
7131       NumVecs = 3; IsDupOp = true; break;
7132     case Intrinsic::arm64_neon_ld4r:      NewOpc = ARM64ISD::LD4DUPpost;
7133       NumVecs = 4; IsDupOp = true; break;
7134     case Intrinsic::arm64_neon_ld2lane:   NewOpc = ARM64ISD::LD2LANEpost;
7135       NumVecs = 2; IsLaneOp = true; break;
7136     case Intrinsic::arm64_neon_ld3lane:   NewOpc = ARM64ISD::LD3LANEpost;
7137       NumVecs = 3; IsLaneOp = true; break;
7138     case Intrinsic::arm64_neon_ld4lane:   NewOpc = ARM64ISD::LD4LANEpost;
7139       NumVecs = 4; IsLaneOp = true; break;
7140     case Intrinsic::arm64_neon_st2lane:   NewOpc = ARM64ISD::ST2LANEpost;
7141       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
7142     case Intrinsic::arm64_neon_st3lane:   NewOpc = ARM64ISD::ST3LANEpost;
7143       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
7144     case Intrinsic::arm64_neon_st4lane:   NewOpc = ARM64ISD::ST4LANEpost;
7145       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
7146     }
7147
7148     EVT VecTy;
7149     if (IsStore)
7150       VecTy = N->getOperand(2).getValueType();
7151     else
7152       VecTy = N->getValueType(0);
7153
7154     // If the increment is a constant, it must match the memory ref size.
7155     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7156     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7157       uint32_t IncVal = CInc->getZExtValue();
7158       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7159       if (IsLaneOp || IsDupOp)
7160         NumBytes /= VecTy.getVectorNumElements();
7161       if (IncVal != NumBytes)
7162         continue;
7163       Inc = DAG.getRegister(ARM64::XZR, MVT::i64);
7164     }
7165     SmallVector<SDValue, 8> Ops;
7166     Ops.push_back(N->getOperand(0)); // Incoming chain
7167     // Load lane and store have vector list as input.
7168     if (IsLaneOp || IsStore)
7169       for (unsigned i = 2; i < AddrOpIdx; ++i)
7170         Ops.push_back(N->getOperand(i));
7171     Ops.push_back(N->getOperand(AddrOpIdx)); // Base register
7172     Ops.push_back(Inc);
7173
7174     // Return Types.
7175     EVT Tys[6];
7176     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
7177     unsigned n;
7178     for (n = 0; n < NumResultVecs; ++n)
7179       Tys[n] = VecTy;
7180     Tys[n++] = MVT::i64;  // Type of write back register
7181     Tys[n] = MVT::Other;  // Type of the chain
7182     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs + 2));
7183
7184     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7185     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
7186                                            MemInt->getMemoryVT(),
7187                                            MemInt->getMemOperand());
7188
7189     // Update the uses.
7190     std::vector<SDValue> NewResults;
7191     for (unsigned i = 0; i < NumResultVecs; ++i) {
7192       NewResults.push_back(SDValue(UpdN.getNode(), i));
7193     }
7194     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
7195     DCI.CombineTo(N, NewResults);
7196     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7197
7198     break;
7199   }
7200   return SDValue();
7201 }
7202
7203 // Optimize compare with zero and branch.
7204 static SDValue performBRCONDCombine(SDNode *N,
7205                                     TargetLowering::DAGCombinerInfo &DCI,
7206                                     SelectionDAG &DAG) {
7207   SDValue Chain = N->getOperand(0);
7208   SDValue Dest = N->getOperand(1);
7209   SDValue CCVal = N->getOperand(2);
7210   SDValue Cmp = N->getOperand(3);
7211
7212   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7213   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7214   if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7215     return SDValue();
7216
7217   unsigned CmpOpc = Cmp.getOpcode();
7218   if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7219     return SDValue();
7220
7221   // Only attempt folding if there is only one use of the flag and no use of the
7222   // value.
7223   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7224     return SDValue();
7225
7226   SDValue LHS = Cmp.getOperand(0);
7227   SDValue RHS = Cmp.getOperand(1);
7228
7229   assert(LHS.getValueType() == RHS.getValueType() &&
7230          "Expected the value type to be the same for both operands!");
7231   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7232     return SDValue();
7233
7234   if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7235     std::swap(LHS, RHS);
7236
7237   if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7238     return SDValue();
7239
7240   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7241       LHS.getOpcode() == ISD::SRL)
7242     return SDValue();
7243
7244   // Fold the compare into the branch instruction.
7245   SDValue BR;
7246   if (CC == ARM64CC::EQ)
7247     BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7248   else
7249     BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7250
7251   // Do not add new nodes to DAG combiner worklist.
7252   DCI.CombineTo(N, BR, false);
7253
7254   return SDValue();
7255 }
7256
7257 // vselect (v1i1 setcc) ->
7258 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
7259 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7260 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7261 // such VSELECT.
7262 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7263   SDValue N0 = N->getOperand(0);
7264   EVT CCVT = N0.getValueType();
7265
7266   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7267       CCVT.getVectorElementType() != MVT::i1)
7268     return SDValue();
7269
7270   EVT ResVT = N->getValueType(0);
7271   EVT CmpVT = N0.getOperand(0).getValueType();
7272   // Only combine when the result type is of the same size as the compared
7273   // operands.
7274   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7275     return SDValue();
7276
7277   SDValue IfTrue = N->getOperand(1);
7278   SDValue IfFalse = N->getOperand(2);
7279   SDValue SetCC =
7280       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7281                    N0.getOperand(0), N0.getOperand(1),
7282                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
7283   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7284                      IfTrue, IfFalse);
7285 }
7286
7287 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
7288 /// the compare-mask instructions rather than going via NZCV, even if LHS and
7289 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
7290 /// with a vector one followed by a DUP shuffle on the result.
7291 static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
7292   SDValue N0 = N->getOperand(0);
7293   EVT ResVT = N->getValueType(0);
7294
7295   if (!N->getOperand(1).getValueType().isVector())
7296     return SDValue();
7297
7298   if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
7299     return SDValue();
7300
7301   SDLoc DL(N0);
7302
7303   EVT SrcVT = N0.getOperand(0).getValueType();
7304   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT,
7305                            ResVT.getSizeInBits() / SrcVT.getSizeInBits());
7306   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
7307
7308   // First perform a vector comparison, where lane 0 is the one we're interested
7309   // in.
7310   SDValue LHS =
7311       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
7312   SDValue RHS =
7313       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
7314   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
7315
7316   // Now duplicate the comparison mask we want across all other lanes.
7317   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
7318   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
7319   Mask = DAG.getNode(ISD::BITCAST, DL, ResVT.changeVectorElementTypeToInteger(),
7320                      Mask);
7321
7322   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
7323 }
7324
7325 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7326                                                DAGCombinerInfo &DCI) const {
7327   SelectionDAG &DAG = DCI.DAG;
7328   switch (N->getOpcode()) {
7329   default:
7330     break;
7331   case ISD::ADD:
7332   case ISD::SUB:
7333     return performAddSubLongCombine(N, DCI, DAG);
7334   case ISD::XOR:
7335     return performXorCombine(N, DAG, DCI, Subtarget);
7336   case ISD::MUL:
7337     return performMulCombine(N, DAG, DCI, Subtarget);
7338   case ISD::SINT_TO_FP:
7339   case ISD::UINT_TO_FP:
7340     return performIntToFpCombine(N, DAG);
7341   case ISD::OR:
7342     return performORCombine(N, DCI, Subtarget);
7343   case ISD::INTRINSIC_WO_CHAIN:
7344     return performIntrinsicCombine(N, DCI, Subtarget);
7345   case ISD::ANY_EXTEND:
7346   case ISD::ZERO_EXTEND:
7347   case ISD::SIGN_EXTEND:
7348     return performExtendCombine(N, DCI, DAG);
7349   case ISD::BITCAST:
7350     return performBitcastCombine(N, DCI, DAG);
7351   case ISD::CONCAT_VECTORS:
7352     return performConcatVectorsCombine(N, DCI, DAG);
7353   case ISD::SELECT:
7354     return performSelectCombine(N, DAG);
7355   case ISD::VSELECT:
7356     return performVSelectCombine(N, DCI.DAG);
7357   case ISD::STORE:
7358     return performSTORECombine(N, DCI, DAG, Subtarget);
7359   case ARM64ISD::BRCOND:
7360     return performBRCONDCombine(N, DCI, DAG);
7361   case ISD::INTRINSIC_VOID:
7362   case ISD::INTRINSIC_W_CHAIN:
7363     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7364     case Intrinsic::arm64_neon_ld2:
7365     case Intrinsic::arm64_neon_ld3:
7366     case Intrinsic::arm64_neon_ld4:
7367     case Intrinsic::arm64_neon_ld1x2:
7368     case Intrinsic::arm64_neon_ld1x3:
7369     case Intrinsic::arm64_neon_ld1x4:
7370     case Intrinsic::arm64_neon_ld2lane:
7371     case Intrinsic::arm64_neon_ld3lane:
7372     case Intrinsic::arm64_neon_ld4lane:
7373     case Intrinsic::arm64_neon_ld2r:
7374     case Intrinsic::arm64_neon_ld3r:
7375     case Intrinsic::arm64_neon_ld4r:
7376     case Intrinsic::arm64_neon_st2:
7377     case Intrinsic::arm64_neon_st3:
7378     case Intrinsic::arm64_neon_st4:
7379     case Intrinsic::arm64_neon_st1x2:
7380     case Intrinsic::arm64_neon_st1x3:
7381     case Intrinsic::arm64_neon_st1x4:
7382     case Intrinsic::arm64_neon_st2lane:
7383     case Intrinsic::arm64_neon_st3lane:
7384     case Intrinsic::arm64_neon_st4lane:
7385       return performNEONPostLDSTCombine(N, DCI, DAG);
7386     default:
7387       break;
7388     }
7389   }
7390   return SDValue();
7391 }
7392
7393 // Check if the return value is used as only a return value, as otherwise
7394 // we can't perform a tail-call. In particular, we need to check for
7395 // target ISD nodes that are returns and any other "odd" constructs
7396 // that the generic analysis code won't necessarily catch.
7397 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7398   if (N->getNumValues() != 1)
7399     return false;
7400   if (!N->hasNUsesOfValue(1, 0))
7401     return false;
7402
7403   SDValue TCChain = Chain;
7404   SDNode *Copy = *N->use_begin();
7405   if (Copy->getOpcode() == ISD::CopyToReg) {
7406     // If the copy has a glue operand, we conservatively assume it isn't safe to
7407     // perform a tail call.
7408     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7409         MVT::Glue)
7410       return false;
7411     TCChain = Copy->getOperand(0);
7412   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7413     return false;
7414
7415   bool HasRet = false;
7416   for (SDNode *Node : Copy->uses()) {
7417     if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7418       return false;
7419     HasRet = true;
7420   }
7421
7422   if (!HasRet)
7423     return false;
7424
7425   Chain = TCChain;
7426   return true;
7427 }
7428
7429 // Return whether the an instruction can potentially be optimized to a tail
7430 // call. This will cause the optimizers to attempt to move, or duplicate,
7431 // return instructions to help enable tail call optimizations for this
7432 // instruction.
7433 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7434   if (!EnableARM64TailCalls)
7435     return false;
7436
7437   if (!CI->isTailCall())
7438     return false;
7439
7440   return true;
7441 }
7442
7443 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7444                                                  SDValue &Offset,
7445                                                  ISD::MemIndexedMode &AM,
7446                                                  bool &IsInc,
7447                                                  SelectionDAG &DAG) const {
7448   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7449     return false;
7450
7451   Base = Op->getOperand(0);
7452   // All of the indexed addressing mode instructions take a signed
7453   // 9 bit immediate offset.
7454   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7455     int64_t RHSC = (int64_t)RHS->getZExtValue();
7456     if (RHSC >= 256 || RHSC <= -256)
7457       return false;
7458     IsInc = (Op->getOpcode() == ISD::ADD);
7459     Offset = Op->getOperand(1);
7460     return true;
7461   }
7462   return false;
7463 }
7464
7465 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7466                                                     SDValue &Offset,
7467                                                     ISD::MemIndexedMode &AM,
7468                                                     SelectionDAG &DAG) const {
7469   EVT VT;
7470   SDValue Ptr;
7471   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7472     VT = LD->getMemoryVT();
7473     Ptr = LD->getBasePtr();
7474   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7475     VT = ST->getMemoryVT();
7476     Ptr = ST->getBasePtr();
7477   } else
7478     return false;
7479
7480   bool IsInc;
7481   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7482     return false;
7483   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7484   return true;
7485 }
7486
7487 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7488                                                      SDValue &Base,
7489                                                      SDValue &Offset,
7490                                                      ISD::MemIndexedMode &AM,
7491                                                      SelectionDAG &DAG) const {
7492   EVT VT;
7493   SDValue Ptr;
7494   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7495     VT = LD->getMemoryVT();
7496     Ptr = LD->getBasePtr();
7497   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7498     VT = ST->getMemoryVT();
7499     Ptr = ST->getBasePtr();
7500   } else
7501     return false;
7502
7503   bool IsInc;
7504   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7505     return false;
7506   // Post-indexing updates the base, so it's not a valid transform
7507   // if that's not the same as the load's pointer.
7508   if (Ptr != Base)
7509     return false;
7510   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7511   return true;
7512 }
7513
7514 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7515                                              SmallVectorImpl<SDValue> &Results,
7516                                              SelectionDAG &DAG) const {
7517   switch (N->getOpcode()) {
7518   default:
7519     llvm_unreachable("Don't know how to custom expand this");
7520   case ISD::FP_TO_UINT:
7521   case ISD::FP_TO_SINT:
7522     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7523     // Let normal code take care of it by not adding anything to Results.
7524     return;
7525   }
7526 }
7527
7528 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7529   // Loads and stores less than 128-bits are already atomic; ones above that
7530   // are doomed anyway, so defer to the default libcall and blame the OS when
7531   // things go wrong:
7532   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7533     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7534   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7535     return LI->getType()->getPrimitiveSizeInBits() == 128;
7536
7537   // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7538   return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7539 }
7540
7541 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7542                                            AtomicOrdering Ord) const {
7543   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7544   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7545   bool IsAcquire =
7546       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7547
7548   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7549   // intrinsic must return {i64, i64} and we have to recombine them into a
7550   // single i128 here.
7551   if (ValTy->getPrimitiveSizeInBits() == 128) {
7552     Intrinsic::ID Int =
7553         IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7554     Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7555
7556     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7557     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7558
7559     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7560     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7561     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7562     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7563     return Builder.CreateOr(
7564         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7565   }
7566
7567   Type *Tys[] = { Addr->getType() };
7568   Intrinsic::ID Int =
7569       IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7570   Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7571
7572   return Builder.CreateTruncOrBitCast(
7573       Builder.CreateCall(Ldxr, Addr),
7574       cast<PointerType>(Addr->getType())->getElementType());
7575 }
7576
7577 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7578                                                  Value *Val, Value *Addr,
7579                                                  AtomicOrdering Ord) const {
7580   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7581   bool IsRelease =
7582       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7583
7584   // Since the intrinsics must have legal type, the i128 intrinsics take two
7585   // parameters: "i64, i64". We must marshal Val into the appropriate form
7586   // before the call.
7587   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7588     Intrinsic::ID Int =
7589         IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7590     Function *Stxr = Intrinsic::getDeclaration(M, Int);
7591     Type *Int64Ty = Type::getInt64Ty(M->getContext());
7592
7593     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7594     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7595     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7596     return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7597   }
7598
7599   Intrinsic::ID Int =
7600       IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7601   Type *Tys[] = { Addr->getType() };
7602   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7603
7604   return Builder.CreateCall2(
7605       Stxr, Builder.CreateZExtOrBitCast(
7606                 Val, Stxr->getFunctionType()->getParamType(0)),
7607       Addr);
7608 }