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