ARM64: add constraints to various FastISel operations
[oota-llvm.git] / lib / Target / ARM64 / ARM64ISelDAGToDAG.cpp
1 //===-- ARM64ISelDAGToDAG.cpp - A dag to dag inst selector for ARM64 ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the ARM64 target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "arm64-isel"
15 #include "ARM64TargetMachine.h"
16 #include "MCTargetDesc/ARM64AddressingModes.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/IR/Function.h" // To access function attributes.
19 #include "llvm/IR/GlobalValue.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 //===--------------------------------------------------------------------===//
29 /// ARM64DAGToDAGISel - ARM64 specific code to select ARM64 machine
30 /// instructions for SelectionDAG operations.
31 ///
32 namespace {
33
34 class ARM64DAGToDAGISel : public SelectionDAGISel {
35   ARM64TargetMachine &TM;
36
37   /// Subtarget - Keep a pointer to the ARM64Subtarget around so that we can
38   /// make the right decision when generating code for different targets.
39   const ARM64Subtarget *Subtarget;
40
41   bool ForCodeSize;
42
43 public:
44   explicit ARM64DAGToDAGISel(ARM64TargetMachine &tm, CodeGenOpt::Level OptLevel)
45       : SelectionDAGISel(tm, OptLevel), TM(tm),
46         Subtarget(&TM.getSubtarget<ARM64Subtarget>()), ForCodeSize(false) {}
47
48   virtual const char *getPassName() const {
49     return "ARM64 Instruction Selection";
50   }
51
52   virtual bool runOnMachineFunction(MachineFunction &MF) {
53     AttributeSet FnAttrs = MF.getFunction()->getAttributes();
54     ForCodeSize =
55         FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
56                              Attribute::OptimizeForSize) ||
57         FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
58     return SelectionDAGISel::runOnMachineFunction(MF);
59   }
60
61   SDNode *Select(SDNode *Node);
62
63   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
64   /// inline asm expressions.
65   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
66                                             char ConstraintCode,
67                                             std::vector<SDValue> &OutOps);
68
69   SDNode *SelectMLAV64LaneV128(SDNode *N);
70   SDNode *SelectMULLV64LaneV128(unsigned IntNo, SDNode *N);
71   bool SelectArithExtendedRegister(SDValue N, SDValue &Reg, SDValue &Shift);
72   bool SelectArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
73   bool SelectNegArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
74   bool SelectArithShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
75     return SelectShiftedRegister(N, false, Reg, Shift);
76   }
77   bool SelectLogicalShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
78     return SelectShiftedRegister(N, true, Reg, Shift);
79   }
80   bool SelectAddrModeIndexed8(SDValue N, SDValue &Base, SDValue &OffImm) {
81     return SelectAddrModeIndexed(N, 1, Base, OffImm);
82   }
83   bool SelectAddrModeIndexed16(SDValue N, SDValue &Base, SDValue &OffImm) {
84     return SelectAddrModeIndexed(N, 2, Base, OffImm);
85   }
86   bool SelectAddrModeIndexed32(SDValue N, SDValue &Base, SDValue &OffImm) {
87     return SelectAddrModeIndexed(N, 4, Base, OffImm);
88   }
89   bool SelectAddrModeIndexed64(SDValue N, SDValue &Base, SDValue &OffImm) {
90     return SelectAddrModeIndexed(N, 8, Base, OffImm);
91   }
92   bool SelectAddrModeIndexed128(SDValue N, SDValue &Base, SDValue &OffImm) {
93     return SelectAddrModeIndexed(N, 16, Base, OffImm);
94   }
95   bool SelectAddrModeUnscaled8(SDValue N, SDValue &Base, SDValue &OffImm) {
96     return SelectAddrModeUnscaled(N, 1, Base, OffImm);
97   }
98   bool SelectAddrModeUnscaled16(SDValue N, SDValue &Base, SDValue &OffImm) {
99     return SelectAddrModeUnscaled(N, 2, Base, OffImm);
100   }
101   bool SelectAddrModeUnscaled32(SDValue N, SDValue &Base, SDValue &OffImm) {
102     return SelectAddrModeUnscaled(N, 4, Base, OffImm);
103   }
104   bool SelectAddrModeUnscaled64(SDValue N, SDValue &Base, SDValue &OffImm) {
105     return SelectAddrModeUnscaled(N, 8, Base, OffImm);
106   }
107   bool SelectAddrModeUnscaled128(SDValue N, SDValue &Base, SDValue &OffImm) {
108     return SelectAddrModeUnscaled(N, 16, Base, OffImm);
109   }
110
111   bool SelectAddrModeRO8(SDValue N, SDValue &Base, SDValue &Offset,
112                          SDValue &Imm) {
113     return SelectAddrModeRO(N, 1, Base, Offset, Imm);
114   }
115   bool SelectAddrModeRO16(SDValue N, SDValue &Base, SDValue &Offset,
116                           SDValue &Imm) {
117     return SelectAddrModeRO(N, 2, Base, Offset, Imm);
118   }
119   bool SelectAddrModeRO32(SDValue N, SDValue &Base, SDValue &Offset,
120                           SDValue &Imm) {
121     return SelectAddrModeRO(N, 4, Base, Offset, Imm);
122   }
123   bool SelectAddrModeRO64(SDValue N, SDValue &Base, SDValue &Offset,
124                           SDValue &Imm) {
125     return SelectAddrModeRO(N, 8, Base, Offset, Imm);
126   }
127   bool SelectAddrModeRO128(SDValue N, SDValue &Base, SDValue &Offset,
128                            SDValue &Imm) {
129     return SelectAddrModeRO(N, 16, Base, Offset, Imm);
130   }
131   bool SelectAddrModeNoIndex(SDValue N, SDValue &Val);
132
133   /// Form sequences of consecutive 64/128-bit registers for use in NEON
134   /// instructions making use of a vector-list (e.g. ldN, tbl). Vecs must have
135   /// between 1 and 4 elements. If it contains a single element that is returned
136   /// unchanged; otherwise a REG_SEQUENCE value is returned.
137   SDValue createDTuple(ArrayRef<SDValue> Vecs);
138   SDValue createQTuple(ArrayRef<SDValue> Vecs);
139
140   /// Generic helper for the createDTuple/createQTuple
141   /// functions. Those should almost always be called instead.
142   SDValue createTuple(ArrayRef<SDValue> Vecs, unsigned RegClassIDs[],
143                       unsigned SubRegs[]);
144
145   SDNode *SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc, bool isExt);
146
147   SDNode *SelectIndexedLoad(SDNode *N, bool &Done);
148
149   SDNode *SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
150                      unsigned SubRegIdx);
151   SDNode *SelectLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
152
153   SDNode *SelectStore(SDNode *N, unsigned NumVecs, unsigned Opc);
154   SDNode *SelectStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
155
156   SDNode *SelectSIMDAddSubNarrowing(unsigned IntNo, SDNode *Node);
157   SDNode *SelectSIMDXtnNarrowing(unsigned IntNo, SDNode *Node);
158
159   SDNode *SelectAtomic(SDNode *Node, unsigned Op8, unsigned Op16, unsigned Op32,
160                        unsigned Op64);
161
162   SDNode *SelectBitfieldExtractOp(SDNode *N);
163   SDNode *SelectBitfieldInsertOp(SDNode *N);
164
165   SDNode *SelectLIBM(SDNode *N);
166
167 // Include the pieces autogenerated from the target description.
168 #include "ARM64GenDAGISel.inc"
169
170 private:
171   bool SelectShiftedRegister(SDValue N, bool AllowROR, SDValue &Reg,
172                              SDValue &Shift);
173   bool SelectAddrModeIndexed(SDValue N, unsigned Size, SDValue &Base,
174                              SDValue &OffImm);
175   bool SelectAddrModeUnscaled(SDValue N, unsigned Size, SDValue &Base,
176                               SDValue &OffImm);
177   bool SelectAddrModeRO(SDValue N, unsigned Size, SDValue &Base,
178                         SDValue &Offset, SDValue &Imm);
179   bool isWorthFolding(SDValue V) const;
180   bool SelectExtendedSHL(SDValue N, unsigned Size, SDValue &Offset,
181                          SDValue &Imm);
182 };
183 } // end anonymous namespace
184
185 /// isIntImmediate - This method tests to see if the node is a constant
186 /// operand. If so Imm will receive the 32-bit value.
187 static bool isIntImmediate(const SDNode *N, uint64_t &Imm) {
188   if (const ConstantSDNode *C = dyn_cast<const ConstantSDNode>(N)) {
189     Imm = C->getZExtValue();
190     return true;
191   }
192   return false;
193 }
194
195 // isIntImmediate - This method tests to see if a constant operand.
196 // If so Imm will receive the value.
197 static bool isIntImmediate(SDValue N, uint64_t &Imm) {
198   return isIntImmediate(N.getNode(), Imm);
199 }
200
201 // isOpcWithIntImmediate - This method tests to see if the node is a specific
202 // opcode and that it has a immediate integer right operand.
203 // If so Imm will receive the 32 bit value.
204 static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc,
205                                   uint64_t &Imm) {
206   return N->getOpcode() == Opc &&
207          isIntImmediate(N->getOperand(1).getNode(), Imm);
208 }
209
210 bool ARM64DAGToDAGISel::SelectAddrModeNoIndex(SDValue N, SDValue &Val) {
211   EVT ValTy = N.getValueType();
212   if (ValTy != MVT::i64)
213     return false;
214   Val = N;
215   return true;
216 }
217
218 bool ARM64DAGToDAGISel::SelectInlineAsmMemoryOperand(
219     const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) {
220   assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
221   // Require the address to be in a register.  That is safe for all ARM64
222   // variants and it is hard to do anything much smarter without knowing
223   // how the operand is used.
224   OutOps.push_back(Op);
225   return false;
226 }
227
228 /// SelectArithImmed - Select an immediate value that can be represented as
229 /// a 12-bit value shifted left by either 0 or 12.  If so, return true with
230 /// Val set to the 12-bit value and Shift set to the shifter operand.
231 bool ARM64DAGToDAGISel::SelectArithImmed(SDValue N, SDValue &Val,
232                                          SDValue &Shift) {
233   // This function is called from the addsub_shifted_imm ComplexPattern,
234   // which lists [imm] as the list of opcode it's interested in, however
235   // we still need to check whether the operand is actually an immediate
236   // here because the ComplexPattern opcode list is only used in
237   // root-level opcode matching.
238   if (!isa<ConstantSDNode>(N.getNode()))
239     return false;
240
241   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
242   unsigned ShiftAmt;
243
244   if (Immed >> 12 == 0) {
245     ShiftAmt = 0;
246   } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
247     ShiftAmt = 12;
248     Immed = Immed >> 12;
249   } else
250     return false;
251
252   unsigned ShVal = ARM64_AM::getShifterImm(ARM64_AM::LSL, ShiftAmt);
253   Val = CurDAG->getTargetConstant(Immed, MVT::i32);
254   Shift = CurDAG->getTargetConstant(ShVal, MVT::i32);
255   return true;
256 }
257
258 /// SelectNegArithImmed - As above, but negates the value before trying to
259 /// select it.
260 bool ARM64DAGToDAGISel::SelectNegArithImmed(SDValue N, SDValue &Val,
261                                             SDValue &Shift) {
262   // This function is called from the addsub_shifted_imm ComplexPattern,
263   // which lists [imm] as the list of opcode it's interested in, however
264   // we still need to check whether the operand is actually an immediate
265   // here because the ComplexPattern opcode list is only used in
266   // root-level opcode matching.
267   if (!isa<ConstantSDNode>(N.getNode()))
268     return false;
269
270   // The immediate operand must be a 24-bit zero-extended immediate.
271   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
272
273   // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
274   // have the opposite effect on the C flag, so this pattern mustn't match under
275   // those circumstances.
276   if (Immed == 0)
277     return false;
278
279   if (N.getValueType() == MVT::i32)
280     Immed = ~((uint32_t)Immed) + 1;
281   else
282     Immed = ~Immed + 1ULL;
283   if (Immed & 0xFFFFFFFFFF000000ULL)
284     return false;
285
286   Immed &= 0xFFFFFFULL;
287   return SelectArithImmed(CurDAG->getConstant(Immed, MVT::i32), Val, Shift);
288 }
289
290 /// getShiftTypeForNode - Translate a shift node to the corresponding
291 /// ShiftType value.
292 static ARM64_AM::ShiftType getShiftTypeForNode(SDValue N) {
293   switch (N.getOpcode()) {
294   default:
295     return ARM64_AM::InvalidShift;
296   case ISD::SHL:
297     return ARM64_AM::LSL;
298   case ISD::SRL:
299     return ARM64_AM::LSR;
300   case ISD::SRA:
301     return ARM64_AM::ASR;
302   case ISD::ROTR:
303     return ARM64_AM::ROR;
304   }
305 }
306
307 /// \brief Determine wether it is worth to fold V into an extended register.
308 bool ARM64DAGToDAGISel::isWorthFolding(SDValue V) const {
309   // it hurts if the a value is used at least twice, unless we are optimizing
310   // for code size.
311   if (ForCodeSize || V.hasOneUse())
312     return true;
313   return false;
314 }
315
316 /// SelectShiftedRegister - Select a "shifted register" operand.  If the value
317 /// is not shifted, set the Shift operand to default of "LSL 0".  The logical
318 /// instructions allow the shifted register to be rotated, but the arithmetic
319 /// instructions do not.  The AllowROR parameter specifies whether ROR is
320 /// supported.
321 bool ARM64DAGToDAGISel::SelectShiftedRegister(SDValue N, bool AllowROR,
322                                               SDValue &Reg, SDValue &Shift) {
323   ARM64_AM::ShiftType ShType = getShiftTypeForNode(N);
324   if (ShType == ARM64_AM::InvalidShift)
325     return false;
326   if (!AllowROR && ShType == ARM64_AM::ROR)
327     return false;
328
329   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
330     unsigned BitSize = N.getValueType().getSizeInBits();
331     unsigned Val = RHS->getZExtValue() & (BitSize - 1);
332     unsigned ShVal = ARM64_AM::getShifterImm(ShType, Val);
333
334     Reg = N.getOperand(0);
335     Shift = CurDAG->getTargetConstant(ShVal, MVT::i32);
336     return isWorthFolding(N);
337   }
338
339   return false;
340 }
341
342 /// getExtendTypeForNode - Translate an extend node to the corresponding
343 /// ExtendType value.
344 static ARM64_AM::ExtendType getExtendTypeForNode(SDValue N,
345                                                  bool IsLoadStore = false) {
346   if (N.getOpcode() == ISD::SIGN_EXTEND ||
347       N.getOpcode() == ISD::SIGN_EXTEND_INREG) {
348     EVT SrcVT;
349     if (N.getOpcode() == ISD::SIGN_EXTEND_INREG)
350       SrcVT = cast<VTSDNode>(N.getOperand(1))->getVT();
351     else
352       SrcVT = N.getOperand(0).getValueType();
353
354     if (!IsLoadStore && SrcVT == MVT::i8)
355       return ARM64_AM::SXTB;
356     else if (!IsLoadStore && SrcVT == MVT::i16)
357       return ARM64_AM::SXTH;
358     else if (SrcVT == MVT::i32)
359       return ARM64_AM::SXTW;
360     else if (SrcVT == MVT::i64)
361       return ARM64_AM::SXTX;
362
363     return ARM64_AM::InvalidExtend;
364   } else if (N.getOpcode() == ISD::ZERO_EXTEND ||
365              N.getOpcode() == ISD::ANY_EXTEND) {
366     EVT SrcVT = N.getOperand(0).getValueType();
367     if (!IsLoadStore && SrcVT == MVT::i8)
368       return ARM64_AM::UXTB;
369     else if (!IsLoadStore && SrcVT == MVT::i16)
370       return ARM64_AM::UXTH;
371     else if (SrcVT == MVT::i32)
372       return ARM64_AM::UXTW;
373     else if (SrcVT == MVT::i64)
374       return ARM64_AM::UXTX;
375
376     return ARM64_AM::InvalidExtend;
377   } else if (N.getOpcode() == ISD::AND) {
378     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
379     if (!CSD)
380       return ARM64_AM::InvalidExtend;
381     uint64_t AndMask = CSD->getZExtValue();
382
383     switch (AndMask) {
384     default:
385       return ARM64_AM::InvalidExtend;
386     case 0xFF:
387       return !IsLoadStore ? ARM64_AM::UXTB : ARM64_AM::InvalidExtend;
388     case 0xFFFF:
389       return !IsLoadStore ? ARM64_AM::UXTH : ARM64_AM::InvalidExtend;
390     case 0xFFFFFFFF:
391       return ARM64_AM::UXTW;
392     }
393   }
394
395   return ARM64_AM::InvalidExtend;
396 }
397
398 // Helper for SelectMLAV64LaneV128 - Recognize high lane extracts.
399 static bool checkHighLaneIndex(SDNode *DL, SDValue &LaneOp, int &LaneIdx) {
400   if (DL->getOpcode() != ARM64ISD::DUPLANE16 &&
401       DL->getOpcode() != ARM64ISD::DUPLANE32)
402     return false;
403
404   SDValue SV = DL->getOperand(0);
405   if (SV.getOpcode() != ISD::INSERT_SUBVECTOR)
406     return false;
407
408   SDValue EV = SV.getOperand(1);
409   if (EV.getOpcode() != ISD::EXTRACT_SUBVECTOR)
410     return false;
411
412   ConstantSDNode *DLidx = cast<ConstantSDNode>(DL->getOperand(1).getNode());
413   ConstantSDNode *EVidx = cast<ConstantSDNode>(EV.getOperand(1).getNode());
414   LaneIdx = DLidx->getSExtValue() + EVidx->getSExtValue();
415   LaneOp = EV.getOperand(0);
416
417   return true;
418 }
419
420 // Helper for SelectOpcV64LaneV128 - Recogzine operatinos where one operand is a
421 // high lane extract.
422 static bool checkV64LaneV128(SDValue Op0, SDValue Op1, SDValue &StdOp,
423                              SDValue &LaneOp, int &LaneIdx) {
424
425   if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx)) {
426     std::swap(Op0, Op1);
427     if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx))
428       return false;
429   }
430   StdOp = Op1;
431   return true;
432 }
433
434 /// SelectMLAV64LaneV128 - ARM64 supports vector MLAs where one multiplicand is
435 /// a lane in the upper half of a 128-bit vector.  Recognize and select this so
436 /// that we don't emit unnecessary lane extracts.
437 SDNode *ARM64DAGToDAGISel::SelectMLAV64LaneV128(SDNode *N) {
438   SDValue Op0 = N->getOperand(0);
439   SDValue Op1 = N->getOperand(1);
440   SDValue MLAOp1;   // Will hold ordinary multiplicand for MLA.
441   SDValue MLAOp2;   // Will hold lane-accessed multiplicand for MLA.
442   int LaneIdx = -1; // Will hold the lane index.
443
444   if (Op1.getOpcode() != ISD::MUL ||
445       !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
446                         LaneIdx)) {
447     std::swap(Op0, Op1);
448     if (Op1.getOpcode() != ISD::MUL ||
449         !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
450                           LaneIdx))
451       return 0;
452   }
453
454   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, MVT::i64);
455
456   SDValue Ops[] = { Op0, MLAOp1, MLAOp2, LaneIdxVal };
457
458   unsigned MLAOpc = ~0U;
459
460   switch (N->getSimpleValueType(0).SimpleTy) {
461   default:
462     llvm_unreachable("Unrecognized MLA.");
463   case MVT::v4i16:
464     MLAOpc = ARM64::MLAv4i16_indexed;
465     break;
466   case MVT::v8i16:
467     MLAOpc = ARM64::MLAv8i16_indexed;
468     break;
469   case MVT::v2i32:
470     MLAOpc = ARM64::MLAv2i32_indexed;
471     break;
472   case MVT::v4i32:
473     MLAOpc = ARM64::MLAv4i32_indexed;
474     break;
475   }
476
477   return CurDAG->getMachineNode(MLAOpc, SDLoc(N), N->getValueType(0), Ops);
478 }
479
480 SDNode *ARM64DAGToDAGISel::SelectMULLV64LaneV128(unsigned IntNo, SDNode *N) {
481   SDValue SMULLOp0;
482   SDValue SMULLOp1;
483   int LaneIdx;
484
485   if (!checkV64LaneV128(N->getOperand(1), N->getOperand(2), SMULLOp0, SMULLOp1,
486                         LaneIdx))
487     return 0;
488
489   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, MVT::i64);
490
491   SDValue Ops[] = { SMULLOp0, SMULLOp1, LaneIdxVal };
492
493   unsigned SMULLOpc = ~0U;
494
495   if (IntNo == Intrinsic::arm64_neon_smull) {
496     switch (N->getSimpleValueType(0).SimpleTy) {
497     default:
498       llvm_unreachable("Unrecognized SMULL.");
499     case MVT::v4i32:
500       SMULLOpc = ARM64::SMULLv4i16_indexed;
501       break;
502     case MVT::v2i64:
503       SMULLOpc = ARM64::SMULLv2i32_indexed;
504       break;
505     }
506   } else if (IntNo == Intrinsic::arm64_neon_umull) {
507     switch (N->getSimpleValueType(0).SimpleTy) {
508     default:
509       llvm_unreachable("Unrecognized SMULL.");
510     case MVT::v4i32:
511       SMULLOpc = ARM64::UMULLv4i16_indexed;
512       break;
513     case MVT::v2i64:
514       SMULLOpc = ARM64::UMULLv2i32_indexed;
515       break;
516     }
517   } else
518     llvm_unreachable("Unrecognized intrinsic.");
519
520   return CurDAG->getMachineNode(SMULLOpc, SDLoc(N), N->getValueType(0), Ops);
521 }
522
523 /// SelectArithExtendedRegister - Select a "extended register" operand.  This
524 /// operand folds in an extend followed by an optional left shift.
525 bool ARM64DAGToDAGISel::SelectArithExtendedRegister(SDValue N, SDValue &Reg,
526                                                     SDValue &Shift) {
527   unsigned ShiftVal = 0;
528   ARM64_AM::ExtendType Ext;
529
530   if (N.getOpcode() == ISD::SHL) {
531     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
532     if (!CSD)
533       return false;
534     ShiftVal = CSD->getZExtValue();
535     if (ShiftVal > 4)
536       return false;
537
538     Ext = getExtendTypeForNode(N.getOperand(0));
539     if (Ext == ARM64_AM::InvalidExtend)
540       return false;
541
542     Reg = N.getOperand(0).getOperand(0);
543   } else {
544     Ext = getExtendTypeForNode(N);
545     if (Ext == ARM64_AM::InvalidExtend)
546       return false;
547
548     Reg = N.getOperand(0);
549   }
550
551   // ARM64 mandates that the RHS of the operation must use the smallest
552   // register classs that could contain the size being extended from.  Thus,
553   // if we're folding a (sext i8), we need the RHS to be a GPR32, even though
554   // there might not be an actual 32-bit value in the program.  We can
555   // (harmlessly) synthesize one by injected an EXTRACT_SUBREG here.
556   if (Reg.getValueType() == MVT::i64 && Ext != ARM64_AM::UXTX &&
557       Ext != ARM64_AM::SXTX) {
558     SDValue SubReg = CurDAG->getTargetConstant(ARM64::sub_32, MVT::i32);
559     MachineSDNode *Node = CurDAG->getMachineNode(
560         TargetOpcode::EXTRACT_SUBREG, SDLoc(N), MVT::i32, Reg, SubReg);
561     Reg = SDValue(Node, 0);
562   }
563
564   Shift = CurDAG->getTargetConstant(getArithExtendImm(Ext, ShiftVal), MVT::i32);
565   return isWorthFolding(N);
566 }
567
568 /// SelectAddrModeIndexed - Select a "register plus scaled unsigned 12-bit
569 /// immediate" address.  The "Size" argument is the size in bytes of the memory
570 /// reference, which determines the scale.
571 bool ARM64DAGToDAGISel::SelectAddrModeIndexed(SDValue N, unsigned Size,
572                                               SDValue &Base, SDValue &OffImm) {
573   const TargetLowering *TLI = getTargetLowering();
574   if (N.getOpcode() == ISD::FrameIndex) {
575     int FI = cast<FrameIndexSDNode>(N)->getIndex();
576     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy());
577     OffImm = CurDAG->getTargetConstant(0, MVT::i64);
578     return true;
579   }
580
581   if (N.getOpcode() == ARM64ISD::ADDlow) {
582     GlobalAddressSDNode *GAN =
583         dyn_cast<GlobalAddressSDNode>(N.getOperand(1).getNode());
584     Base = N.getOperand(0);
585     OffImm = N.getOperand(1);
586     if (!GAN)
587       return true;
588
589     const GlobalValue *GV = GAN->getGlobal();
590     unsigned Alignment = GV->getAlignment();
591     const DataLayout *DL = TLI->getDataLayout();
592     if (Alignment == 0 && !Subtarget->isTargetDarwin())
593       Alignment = DL->getABITypeAlignment(GV->getType()->getElementType());
594
595     if (Alignment >= Size)
596       return true;
597   }
598
599   if (CurDAG->isBaseWithConstantOffset(N)) {
600     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
601       int64_t RHSC = (int64_t)RHS->getZExtValue();
602       unsigned Scale = Log2_32(Size);
603       if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
604         Base = N.getOperand(0);
605         if (Base.getOpcode() == ISD::FrameIndex) {
606           int FI = cast<FrameIndexSDNode>(Base)->getIndex();
607           Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy());
608         }
609         OffImm = CurDAG->getTargetConstant(RHSC >> Scale, MVT::i64);
610         return true;
611       }
612     }
613   }
614
615   // Before falling back to our general case, check if the unscaled
616   // instructions can handle this. If so, that's preferable.
617   if (SelectAddrModeUnscaled(N, Size, Base, OffImm))
618     return false;
619
620   // Base only. The address will be materialized into a register before
621   // the memory is accessed.
622   //    add x0, Xbase, #offset
623   //    ldr x0, [x0]
624   Base = N;
625   OffImm = CurDAG->getTargetConstant(0, MVT::i64);
626   return true;
627 }
628
629 /// SelectAddrModeUnscaled - Select a "register plus unscaled signed 9-bit
630 /// immediate" address.  This should only match when there is an offset that
631 /// is not valid for a scaled immediate addressing mode.  The "Size" argument
632 /// is the size in bytes of the memory reference, which is needed here to know
633 /// what is valid for a scaled immediate.
634 bool ARM64DAGToDAGISel::SelectAddrModeUnscaled(SDValue N, unsigned Size,
635                                                SDValue &Base, SDValue &OffImm) {
636   if (!CurDAG->isBaseWithConstantOffset(N))
637     return false;
638   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
639     int64_t RHSC = RHS->getSExtValue();
640     // If the offset is valid as a scaled immediate, don't match here.
641     if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 &&
642         RHSC < (0x1000 << Log2_32(Size)))
643       return false;
644     if (RHSC >= -256 && RHSC < 256) {
645       Base = N.getOperand(0);
646       if (Base.getOpcode() == ISD::FrameIndex) {
647         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
648         const TargetLowering *TLI = getTargetLowering();
649         Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy());
650       }
651       OffImm = CurDAG->getTargetConstant(RHSC, MVT::i64);
652       return true;
653     }
654   }
655   return false;
656 }
657
658 static SDValue Widen(SelectionDAG *CurDAG, SDValue N) {
659   SDValue SubReg = CurDAG->getTargetConstant(ARM64::sub_32, MVT::i32);
660   SDValue ImpDef = SDValue(
661       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, SDLoc(N), MVT::i64),
662       0);
663   MachineSDNode *Node = CurDAG->getMachineNode(
664       TargetOpcode::INSERT_SUBREG, SDLoc(N), MVT::i64, ImpDef, N, SubReg);
665   return SDValue(Node, 0);
666 }
667
668 static SDValue WidenIfNeeded(SelectionDAG *CurDAG, SDValue N) {
669   if (N.getValueType() == MVT::i32) {
670     return Widen(CurDAG, N);
671   }
672
673   return N;
674 }
675
676 /// \brief Check if the given SHL node (\p N), can be used to form an
677 /// extended register for an addressing mode.
678 bool ARM64DAGToDAGISel::SelectExtendedSHL(SDValue N, unsigned Size,
679                                           SDValue &Offset, SDValue &Imm) {
680   assert(N.getOpcode() == ISD::SHL && "Invalid opcode.");
681   ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
682   if (CSD && (CSD->getZExtValue() & 0x7) == CSD->getZExtValue()) {
683
684     ARM64_AM::ExtendType Ext = getExtendTypeForNode(N.getOperand(0), true);
685     if (Ext == ARM64_AM::InvalidExtend) {
686       Ext = ARM64_AM::UXTX;
687       Offset = WidenIfNeeded(CurDAG, N.getOperand(0));
688     } else {
689       Offset = WidenIfNeeded(CurDAG, N.getOperand(0).getOperand(0));
690     }
691
692     unsigned LegalShiftVal = Log2_32(Size);
693     unsigned ShiftVal = CSD->getZExtValue();
694
695     if (ShiftVal != 0 && ShiftVal != LegalShiftVal)
696       return false;
697
698     Imm = CurDAG->getTargetConstant(
699         ARM64_AM::getMemExtendImm(Ext, ShiftVal != 0), MVT::i32);
700     if (isWorthFolding(N))
701       return true;
702   }
703   return false;
704 }
705
706 bool ARM64DAGToDAGISel::SelectAddrModeRO(SDValue N, unsigned Size,
707                                          SDValue &Base, SDValue &Offset,
708                                          SDValue &Imm) {
709   if (N.getOpcode() != ISD::ADD)
710     return false;
711   SDValue LHS = N.getOperand(0);
712   SDValue RHS = N.getOperand(1);
713
714   // We don't want to match immediate adds here, because they are better lowered
715   // to the register-immediate addressing modes.
716   if (isa<ConstantSDNode>(LHS) || isa<ConstantSDNode>(RHS))
717     return false;
718
719   // Check if this particular node is reused in any non-memory related
720   // operation.  If yes, do not try to fold this node into the address
721   // computation, since the computation will be kept.
722   const SDNode *Node = N.getNode();
723   for (SDNode *UI : Node->uses()) {
724     if (!isa<MemSDNode>(*UI))
725       return false;
726   }
727
728   // Remember if it is worth folding N when it produces extended register.
729   bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
730
731   // Try to match a shifted extend on the RHS.
732   if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
733       SelectExtendedSHL(RHS, Size, Offset, Imm)) {
734     Base = LHS;
735     return true;
736   }
737
738   // Try to match a shifted extend on the LHS.
739   if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
740       SelectExtendedSHL(LHS, Size, Offset, Imm)) {
741     Base = RHS;
742     return true;
743   }
744
745   ARM64_AM::ExtendType Ext = ARM64_AM::UXTX;
746   // Try to match an unshifted extend on the LHS.
747   if (IsExtendedRegisterWorthFolding &&
748       (Ext = getExtendTypeForNode(LHS, true)) != ARM64_AM::InvalidExtend) {
749     Base = RHS;
750     Offset = WidenIfNeeded(CurDAG, LHS.getOperand(0));
751     Imm = CurDAG->getTargetConstant(ARM64_AM::getMemExtendImm(Ext, false),
752                                     MVT::i32);
753     if (isWorthFolding(LHS))
754       return true;
755   }
756
757   // Try to match an unshifted extend on the RHS.
758   if (IsExtendedRegisterWorthFolding &&
759       (Ext = getExtendTypeForNode(RHS, true)) != ARM64_AM::InvalidExtend) {
760     Base = LHS;
761     Offset = WidenIfNeeded(CurDAG, RHS.getOperand(0));
762     Imm = CurDAG->getTargetConstant(ARM64_AM::getMemExtendImm(Ext, false),
763                                     MVT::i32);
764     if (isWorthFolding(RHS))
765       return true;
766   }
767
768   // Match any non-shifted, non-extend, non-immediate add expression.
769   Base = LHS;
770   Offset = WidenIfNeeded(CurDAG, RHS);
771   Ext = ARM64_AM::UXTX;
772   Imm = CurDAG->getTargetConstant(ARM64_AM::getMemExtendImm(Ext, false),
773                                   MVT::i32);
774   // Reg1 + Reg2 is free: no check needed.
775   return true;
776 }
777
778 SDValue ARM64DAGToDAGISel::createDTuple(ArrayRef<SDValue> Regs) {
779   static unsigned RegClassIDs[] = { ARM64::DDRegClassID, ARM64::DDDRegClassID,
780                                     ARM64::DDDDRegClassID };
781   static unsigned SubRegs[] = { ARM64::dsub0, ARM64::dsub1,
782                                 ARM64::dsub2, ARM64::dsub3 };
783
784   return createTuple(Regs, RegClassIDs, SubRegs);
785 }
786
787 SDValue ARM64DAGToDAGISel::createQTuple(ArrayRef<SDValue> Regs) {
788   static unsigned RegClassIDs[] = { ARM64::QQRegClassID, ARM64::QQQRegClassID,
789                                     ARM64::QQQQRegClassID };
790   static unsigned SubRegs[] = { ARM64::qsub0, ARM64::qsub1,
791                                 ARM64::qsub2, ARM64::qsub3 };
792
793   return createTuple(Regs, RegClassIDs, SubRegs);
794 }
795
796 SDValue ARM64DAGToDAGISel::createTuple(ArrayRef<SDValue> Regs,
797                                        unsigned RegClassIDs[],
798                                        unsigned SubRegs[]) {
799   // There's no special register-class for a vector-list of 1 element: it's just
800   // a vector.
801   if (Regs.size() == 1)
802     return Regs[0];
803
804   assert(Regs.size() >= 2 && Regs.size() <= 4);
805
806   SDLoc DL(Regs[0].getNode());
807
808   SmallVector<SDValue, 4> Ops;
809
810   // First operand of REG_SEQUENCE is the desired RegClass.
811   Ops.push_back(
812       CurDAG->getTargetConstant(RegClassIDs[Regs.size() - 2], MVT::i32));
813
814   // Then we get pairs of source & subregister-position for the components.
815   for (unsigned i = 0; i < Regs.size(); ++i) {
816     Ops.push_back(Regs[i]);
817     Ops.push_back(CurDAG->getTargetConstant(SubRegs[i], MVT::i32));
818   }
819
820   SDNode *N =
821       CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, MVT::Untyped, Ops);
822   return SDValue(N, 0);
823 }
824
825 SDNode *ARM64DAGToDAGISel::SelectTable(SDNode *N, unsigned NumVecs,
826                                        unsigned Opc, bool isExt) {
827   SDLoc dl(N);
828   EVT VT = N->getValueType(0);
829
830   unsigned ExtOff = isExt;
831
832   // Form a REG_SEQUENCE to force register allocation.
833   unsigned Vec0Off = ExtOff + 1;
834   SmallVector<SDValue, 4> Regs(N->op_begin() + Vec0Off,
835                                N->op_begin() + Vec0Off + NumVecs);
836   SDValue RegSeq = createQTuple(Regs);
837
838   SmallVector<SDValue, 6> Ops;
839   if (isExt)
840     Ops.push_back(N->getOperand(1));
841   Ops.push_back(RegSeq);
842   Ops.push_back(N->getOperand(NumVecs + ExtOff + 1));
843   return CurDAG->getMachineNode(Opc, dl, VT, Ops);
844 }
845
846 SDNode *ARM64DAGToDAGISel::SelectIndexedLoad(SDNode *N, bool &Done) {
847   LoadSDNode *LD = cast<LoadSDNode>(N);
848   if (LD->isUnindexed())
849     return NULL;
850   EVT VT = LD->getMemoryVT();
851   EVT DstVT = N->getValueType(0);
852   ISD::MemIndexedMode AM = LD->getAddressingMode();
853   bool IsPre = AM == ISD::PRE_INC || AM == ISD::PRE_DEC;
854
855   // We're not doing validity checking here. That was done when checking
856   // if we should mark the load as indexed or not. We're just selecting
857   // the right instruction.
858   unsigned Opcode = 0;
859
860   ISD::LoadExtType ExtType = LD->getExtensionType();
861   bool InsertTo64 = false;
862   if (VT == MVT::i64)
863     Opcode = IsPre ? ARM64::LDRXpre_isel : ARM64::LDRXpost_isel;
864   else if (VT == MVT::i32) {
865     if (ExtType == ISD::NON_EXTLOAD)
866       Opcode = IsPre ? ARM64::LDRWpre_isel : ARM64::LDRWpost_isel;
867     else if (ExtType == ISD::SEXTLOAD)
868       Opcode = IsPre ? ARM64::LDRSWpre_isel : ARM64::LDRSWpost_isel;
869     else {
870       Opcode = IsPre ? ARM64::LDRWpre_isel : ARM64::LDRWpost_isel;
871       InsertTo64 = true;
872       // The result of the load is only i32. It's the subreg_to_reg that makes
873       // it into an i64.
874       DstVT = MVT::i32;
875     }
876   } else if (VT == MVT::i16) {
877     if (ExtType == ISD::SEXTLOAD) {
878       if (DstVT == MVT::i64)
879         Opcode = IsPre ? ARM64::LDRSHXpre_isel : ARM64::LDRSHXpost_isel;
880       else
881         Opcode = IsPre ? ARM64::LDRSHWpre_isel : ARM64::LDRSHWpost_isel;
882     } else {
883       Opcode = IsPre ? ARM64::LDRHHpre_isel : ARM64::LDRHHpost_isel;
884       InsertTo64 = DstVT == MVT::i64;
885       // The result of the load is only i32. It's the subreg_to_reg that makes
886       // it into an i64.
887       DstVT = MVT::i32;
888     }
889   } else if (VT == MVT::i8) {
890     if (ExtType == ISD::SEXTLOAD) {
891       if (DstVT == MVT::i64)
892         Opcode = IsPre ? ARM64::LDRSBXpre_isel : ARM64::LDRSBXpost_isel;
893       else
894         Opcode = IsPre ? ARM64::LDRSBWpre_isel : ARM64::LDRSBWpost_isel;
895     } else {
896       Opcode = IsPre ? ARM64::LDRBBpre_isel : ARM64::LDRBBpost_isel;
897       InsertTo64 = DstVT == MVT::i64;
898       // The result of the load is only i32. It's the subreg_to_reg that makes
899       // it into an i64.
900       DstVT = MVT::i32;
901     }
902   } else if (VT == MVT::f32) {
903     Opcode = IsPre ? ARM64::LDRSpre_isel : ARM64::LDRSpost_isel;
904   } else if (VT == MVT::f64) {
905     Opcode = IsPre ? ARM64::LDRDpre_isel : ARM64::LDRDpost_isel;
906   } else
907     return NULL;
908   SDValue Chain = LD->getChain();
909   SDValue Base = LD->getBasePtr();
910   ConstantSDNode *OffsetOp = cast<ConstantSDNode>(LD->getOffset());
911   int OffsetVal = (int)OffsetOp->getZExtValue();
912   SDValue Offset = CurDAG->getTargetConstant(OffsetVal, MVT::i64);
913   SDValue Ops[] = { Base, Offset, Chain };
914   SDNode *Res = CurDAG->getMachineNode(Opcode, SDLoc(N), DstVT, MVT::i64,
915                                        MVT::Other, Ops);
916   // Either way, we're replacing the node, so tell the caller that.
917   Done = true;
918   if (InsertTo64) {
919     SDValue SubReg = CurDAG->getTargetConstant(ARM64::sub_32, MVT::i32);
920     SDNode *Sub = CurDAG->getMachineNode(
921         ARM64::SUBREG_TO_REG, SDLoc(N), MVT::i64,
922         CurDAG->getTargetConstant(0, MVT::i64), SDValue(Res, 0), SubReg);
923     ReplaceUses(SDValue(N, 0), SDValue(Sub, 0));
924     ReplaceUses(SDValue(N, 1), SDValue(Res, 1));
925     ReplaceUses(SDValue(N, 2), SDValue(Res, 2));
926     return 0;
927   }
928   return Res;
929 }
930
931 SDNode *ARM64DAGToDAGISel::SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
932                                       unsigned SubRegIdx) {
933   SDLoc dl(N);
934   EVT VT = N->getValueType(0);
935   SDValue Chain = N->getOperand(0);
936
937   SmallVector<SDValue, 6> Ops;
938   Ops.push_back(N->getOperand(2)); // Mem operand;
939   Ops.push_back(Chain);
940
941   std::vector<EVT> ResTys;
942   ResTys.push_back(MVT::Untyped);
943   ResTys.push_back(MVT::Other);
944
945   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
946   SDValue SuperReg = SDValue(Ld, 0);
947
948   // MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
949   // MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
950   // cast<MachineSDNode>(Ld)->setMemRefs(MemOp, MemOp + 1);
951
952   switch (NumVecs) {
953   case 4:
954     ReplaceUses(SDValue(N, 3), CurDAG->getTargetExtractSubreg(SubRegIdx + 3, dl,
955                                                               VT, SuperReg));
956   // FALLTHROUGH
957   case 3:
958     ReplaceUses(SDValue(N, 2), CurDAG->getTargetExtractSubreg(SubRegIdx + 2, dl,
959                                                               VT, SuperReg));
960   // FALLTHROUGH
961   case 2:
962     ReplaceUses(SDValue(N, 1), CurDAG->getTargetExtractSubreg(SubRegIdx + 1, dl,
963                                                               VT, SuperReg));
964     ReplaceUses(SDValue(N, 0),
965                 CurDAG->getTargetExtractSubreg(SubRegIdx, dl, VT, SuperReg));
966     break;
967   case 1:
968     ReplaceUses(SDValue(N, 0), SuperReg);
969     break;
970   }
971
972   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
973
974   return 0;
975 }
976
977 SDNode *ARM64DAGToDAGISel::SelectStore(SDNode *N, unsigned NumVecs,
978                                        unsigned Opc) {
979   SDLoc dl(N);
980   EVT VT = N->getOperand(2)->getValueType(0);
981
982   // Form a REG_SEQUENCE to force register allocation.
983   bool Is128Bit = VT.getSizeInBits() == 128;
984   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
985   SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
986
987   SmallVector<SDValue, 6> Ops;
988   Ops.push_back(RegSeq);
989   Ops.push_back(N->getOperand(NumVecs + 2));
990   Ops.push_back(N->getOperand(0));
991   SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
992
993   return St;
994 }
995
996 /// WidenVector - Given a value in the V64 register class, produce the
997 /// equivalent value in the V128 register class.
998 class WidenVector {
999   SelectionDAG &DAG;
1000
1001 public:
1002   WidenVector(SelectionDAG &DAG) : DAG(DAG) {}
1003
1004   SDValue operator()(SDValue V64Reg) {
1005     EVT VT = V64Reg.getValueType();
1006     unsigned NarrowSize = VT.getVectorNumElements();
1007     MVT EltTy = VT.getVectorElementType().getSimpleVT();
1008     MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
1009     SDLoc DL(V64Reg);
1010
1011     SDValue Undef =
1012         SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, WideTy), 0);
1013     return DAG.getTargetInsertSubreg(ARM64::dsub, DL, WideTy, Undef, V64Reg);
1014   }
1015 };
1016
1017 /// NarrowVector - Given a value in the V128 register class, produce the
1018 /// equivalent value in the V64 register class.
1019 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
1020   EVT VT = V128Reg.getValueType();
1021   unsigned WideSize = VT.getVectorNumElements();
1022   MVT EltTy = VT.getVectorElementType().getSimpleVT();
1023   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
1024
1025   return DAG.getTargetExtractSubreg(ARM64::dsub, SDLoc(V128Reg), NarrowTy,
1026                                     V128Reg);
1027 }
1028
1029 SDNode *ARM64DAGToDAGISel::SelectLoadLane(SDNode *N, unsigned NumVecs,
1030                                           unsigned Opc) {
1031   SDLoc dl(N);
1032   EVT VT = N->getValueType(0);
1033   bool Narrow = VT.getSizeInBits() == 64;
1034
1035   // Form a REG_SEQUENCE to force register allocation.
1036   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1037
1038   if (Narrow)
1039     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1040                    WidenVector(*CurDAG));
1041
1042   SDValue RegSeq = createQTuple(Regs);
1043
1044   std::vector<EVT> ResTys;
1045   ResTys.push_back(MVT::Untyped);
1046   ResTys.push_back(MVT::Other);
1047
1048   unsigned LaneNo =
1049       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1050
1051   SmallVector<SDValue, 6> Ops;
1052   Ops.push_back(RegSeq);
1053   Ops.push_back(CurDAG->getTargetConstant(LaneNo, MVT::i64));
1054   Ops.push_back(N->getOperand(NumVecs + 3));
1055   Ops.push_back(N->getOperand(0));
1056   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1057   SDValue SuperReg = SDValue(Ld, 0);
1058
1059   EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
1060   switch (NumVecs) {
1061   case 4: {
1062     SDValue NV3 =
1063         CurDAG->getTargetExtractSubreg(ARM64::qsub3, dl, WideVT, SuperReg);
1064     if (Narrow)
1065       ReplaceUses(SDValue(N, 3), NarrowVector(NV3, *CurDAG));
1066     else
1067       ReplaceUses(SDValue(N, 3), NV3);
1068   }
1069   // FALLTHROUGH
1070   case 3: {
1071     SDValue NV2 =
1072         CurDAG->getTargetExtractSubreg(ARM64::qsub2, dl, WideVT, SuperReg);
1073     if (Narrow)
1074       ReplaceUses(SDValue(N, 2), NarrowVector(NV2, *CurDAG));
1075     else
1076       ReplaceUses(SDValue(N, 2), NV2);
1077   }
1078   // FALLTHROUGH
1079   case 2: {
1080     SDValue NV1 =
1081         CurDAG->getTargetExtractSubreg(ARM64::qsub1, dl, WideVT, SuperReg);
1082     SDValue NV0 =
1083         CurDAG->getTargetExtractSubreg(ARM64::qsub0, dl, WideVT, SuperReg);
1084     if (Narrow) {
1085       ReplaceUses(SDValue(N, 1), NarrowVector(NV1, *CurDAG));
1086       ReplaceUses(SDValue(N, 0), NarrowVector(NV0, *CurDAG));
1087     } else {
1088       ReplaceUses(SDValue(N, 1), NV1);
1089       ReplaceUses(SDValue(N, 0), NV0);
1090     }
1091     break;
1092   }
1093   }
1094
1095   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
1096
1097   return Ld;
1098 }
1099
1100 SDNode *ARM64DAGToDAGISel::SelectStoreLane(SDNode *N, unsigned NumVecs,
1101                                            unsigned Opc) {
1102   SDLoc dl(N);
1103   EVT VT = N->getOperand(2)->getValueType(0);
1104   bool Narrow = VT.getSizeInBits() == 64;
1105
1106   // Form a REG_SEQUENCE to force register allocation.
1107   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1108
1109   if (Narrow)
1110     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1111                    WidenVector(*CurDAG));
1112
1113   SDValue RegSeq = createQTuple(Regs);
1114
1115   unsigned LaneNo =
1116       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1117
1118   SmallVector<SDValue, 6> Ops;
1119   Ops.push_back(RegSeq);
1120   Ops.push_back(CurDAG->getTargetConstant(LaneNo, MVT::i64));
1121   Ops.push_back(N->getOperand(NumVecs + 3));
1122   Ops.push_back(N->getOperand(0));
1123   SDNode *St = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
1124
1125   // Transfer memoperands.
1126   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1127   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1128   cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
1129
1130   return St;
1131 }
1132
1133 SDNode *ARM64DAGToDAGISel::SelectAtomic(SDNode *Node, unsigned Op8,
1134                                         unsigned Op16, unsigned Op32,
1135                                         unsigned Op64) {
1136   // Mostly direct translation to the given operations, except that we preserve
1137   // the AtomicOrdering for use later on.
1138   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
1139   EVT VT = AN->getMemoryVT();
1140
1141   unsigned Op;
1142   if (VT == MVT::i8)
1143     Op = Op8;
1144   else if (VT == MVT::i16)
1145     Op = Op16;
1146   else if (VT == MVT::i32)
1147     Op = Op32;
1148   else if (VT == MVT::i64)
1149     Op = Op64;
1150   else
1151     llvm_unreachable("Unexpected atomic operation");
1152
1153   SmallVector<SDValue, 4> Ops;
1154   for (unsigned i = 1; i < AN->getNumOperands(); ++i)
1155     Ops.push_back(AN->getOperand(i));
1156
1157   Ops.push_back(CurDAG->getTargetConstant(AN->getOrdering(), MVT::i32));
1158   Ops.push_back(AN->getOperand(0)); // Chain moves to the end
1159
1160   return CurDAG->SelectNodeTo(Node, Op, AN->getValueType(0), MVT::Other,
1161                               &Ops[0], Ops.size());
1162 }
1163
1164 static bool isBitfieldExtractOpFromAnd(SelectionDAG *CurDAG, SDNode *N,
1165                                        unsigned &Opc, SDValue &Opd0,
1166                                        unsigned &LSB, unsigned &MSB,
1167                                        unsigned NumberOfIgnoredLowBits,
1168                                        bool BiggerPattern) {
1169   assert(N->getOpcode() == ISD::AND &&
1170          "N must be a AND operation to call this function");
1171
1172   EVT VT = N->getValueType(0);
1173
1174   // Here we can test the type of VT and return false when the type does not
1175   // match, but since it is done prior to that call in the current context
1176   // we turned that into an assert to avoid redundant code.
1177   assert((VT == MVT::i32 || VT == MVT::i64) &&
1178          "Type checking must have been done before calling this function");
1179
1180   // FIXME: simplify-demanded-bits in DAGCombine will probably have
1181   // changed the AND node to a 32-bit mask operation. We'll have to
1182   // undo that as part of the transform here if we want to catch all
1183   // the opportunities.
1184   // Currently the NumberOfIgnoredLowBits argument helps to recover
1185   // form these situations when matching bigger pattern (bitfield insert).
1186
1187   // For unsigned extracts, check for a shift right and mask
1188   uint64_t And_imm = 0;
1189   if (!isOpcWithIntImmediate(N, ISD::AND, And_imm))
1190     return false;
1191
1192   const SDNode *Op0 = N->getOperand(0).getNode();
1193
1194   // Because of simplify-demanded-bits in DAGCombine, the mask may have been
1195   // simplified. Try to undo that
1196   And_imm |= (1 << NumberOfIgnoredLowBits) - 1;
1197
1198   // The immediate is a mask of the low bits iff imm & (imm+1) == 0
1199   if (And_imm & (And_imm + 1))
1200     return false;
1201
1202   bool ClampMSB = false;
1203   uint64_t Srl_imm = 0;
1204   // Handle the SRL + ANY_EXTEND case.
1205   if (VT == MVT::i64 && Op0->getOpcode() == ISD::ANY_EXTEND &&
1206       isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL, Srl_imm)) {
1207     // Extend the incoming operand of the SRL to 64-bit.
1208     Opd0 = Widen(CurDAG, Op0->getOperand(0).getOperand(0));
1209     // Make sure to clamp the MSB so that we preserve the semantics of the
1210     // original operations.
1211     ClampMSB = true;
1212   } else if (isOpcWithIntImmediate(Op0, ISD::SRL, Srl_imm)) {
1213     Opd0 = Op0->getOperand(0);
1214   } else if (BiggerPattern) {
1215     // Let's pretend a 0 shift right has been performed.
1216     // The resulting code will be at least as good as the original one
1217     // plus it may expose more opportunities for bitfield insert pattern.
1218     // FIXME: Currently we limit this to the bigger pattern, because
1219     // some optimizations expect AND and not UBFM
1220     Opd0 = N->getOperand(0);
1221   } else
1222     return false;
1223
1224   assert((BiggerPattern || (Srl_imm > 0 && Srl_imm < VT.getSizeInBits())) &&
1225          "bad amount in shift node!");
1226
1227   LSB = Srl_imm;
1228   MSB = Srl_imm + (VT == MVT::i32 ? CountTrailingOnes_32(And_imm)
1229                                   : CountTrailingOnes_64(And_imm)) -
1230         1;
1231   if (ClampMSB)
1232     // Since we're moving the extend before the right shift operation, we need
1233     // to clamp the MSB to make sure we don't shift in undefined bits instead of
1234     // the zeros which would get shifted in with the original right shift
1235     // operation.
1236     MSB = MSB > 31 ? 31 : MSB;
1237
1238   Opc = VT == MVT::i32 ? ARM64::UBFMWri : ARM64::UBFMXri;
1239   return true;
1240 }
1241
1242 static bool isOneBitExtractOpFromShr(SDNode *N, unsigned &Opc, SDValue &Opd0,
1243                                      unsigned &LSB, unsigned &MSB) {
1244   // We are looking for the following pattern which basically extracts a single
1245   // bit from the source value and places it in the LSB of the destination
1246   // value, all other bits of the destination value or set to zero:
1247   //
1248   // Value2 = AND Value, MaskImm
1249   // SRL Value2, ShiftImm
1250   //
1251   // with MaskImm >> ShiftImm == 1.
1252   //
1253   // This gets selected into a single UBFM:
1254   //
1255   // UBFM Value, ShiftImm, ShiftImm
1256   //
1257
1258   if (N->getOpcode() != ISD::SRL)
1259     return false;
1260
1261   uint64_t And_mask = 0;
1262   if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, And_mask))
1263     return false;
1264
1265   Opd0 = N->getOperand(0).getOperand(0);
1266
1267   uint64_t Srl_imm = 0;
1268   if (!isIntImmediate(N->getOperand(1), Srl_imm))
1269     return false;
1270
1271   // Check whether we really have a one bit extract here.
1272   if (And_mask >> Srl_imm == 0x1) {
1273     if (N->getValueType(0) == MVT::i32)
1274       Opc = ARM64::UBFMWri;
1275     else
1276       Opc = ARM64::UBFMXri;
1277
1278     LSB = MSB = Srl_imm;
1279
1280     return true;
1281   }
1282
1283   return false;
1284 }
1285
1286 static bool isBitfieldExtractOpFromShr(SDNode *N, unsigned &Opc, SDValue &Opd0,
1287                                        unsigned &LSB, unsigned &MSB,
1288                                        bool BiggerPattern) {
1289   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
1290          "N must be a SHR/SRA operation to call this function");
1291
1292   EVT VT = N->getValueType(0);
1293
1294   // Here we can test the type of VT and return false when the type does not
1295   // match, but since it is done prior to that call in the current context
1296   // we turned that into an assert to avoid redundant code.
1297   assert((VT == MVT::i32 || VT == MVT::i64) &&
1298          "Type checking must have been done before calling this function");
1299
1300   // Check for AND + SRL doing a one bit extract.
1301   if (isOneBitExtractOpFromShr(N, Opc, Opd0, LSB, MSB))
1302     return true;
1303
1304   // we're looking for a shift of a shift
1305   uint64_t Shl_imm = 0;
1306   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, Shl_imm)) {
1307     Opd0 = N->getOperand(0).getOperand(0);
1308   } else if (BiggerPattern) {
1309     // Let's pretend a 0 shift left has been performed.
1310     // FIXME: Currently we limit this to the bigger pattern case,
1311     // because some optimizations expect AND and not UBFM
1312     Opd0 = N->getOperand(0);
1313   } else
1314     return false;
1315
1316   assert(Shl_imm < VT.getSizeInBits() && "bad amount in shift node!");
1317   uint64_t Srl_imm = 0;
1318   if (!isIntImmediate(N->getOperand(1), Srl_imm))
1319     return false;
1320
1321   assert(Srl_imm > 0 && Srl_imm < VT.getSizeInBits() &&
1322          "bad amount in shift node!");
1323   // Note: The width operand is encoded as width-1.
1324   unsigned Width = VT.getSizeInBits() - Srl_imm - 1;
1325   int sLSB = Srl_imm - Shl_imm;
1326   if (sLSB < 0)
1327     return false;
1328   LSB = sLSB;
1329   MSB = LSB + Width;
1330   // SRA requires a signed extraction
1331   if (VT == MVT::i32)
1332     Opc = N->getOpcode() == ISD::SRA ? ARM64::SBFMWri : ARM64::UBFMWri;
1333   else
1334     Opc = N->getOpcode() == ISD::SRA ? ARM64::SBFMXri : ARM64::UBFMXri;
1335   return true;
1336 }
1337
1338 static bool isBitfieldExtractOp(SelectionDAG *CurDAG, SDNode *N, unsigned &Opc,
1339                                 SDValue &Opd0, unsigned &LSB, unsigned &MSB,
1340                                 unsigned NumberOfIgnoredLowBits = 0,
1341                                 bool BiggerPattern = false) {
1342   if (N->getValueType(0) != MVT::i32 && N->getValueType(0) != MVT::i64)
1343     return false;
1344
1345   switch (N->getOpcode()) {
1346   default:
1347     if (!N->isMachineOpcode())
1348       return false;
1349     break;
1350   case ISD::AND:
1351     return isBitfieldExtractOpFromAnd(CurDAG, N, Opc, Opd0, LSB, MSB,
1352                                       NumberOfIgnoredLowBits, BiggerPattern);
1353   case ISD::SRL:
1354   case ISD::SRA:
1355     return isBitfieldExtractOpFromShr(N, Opc, Opd0, LSB, MSB, BiggerPattern);
1356   }
1357
1358   unsigned NOpc = N->getMachineOpcode();
1359   switch (NOpc) {
1360   default:
1361     return false;
1362   case ARM64::SBFMWri:
1363   case ARM64::UBFMWri:
1364   case ARM64::SBFMXri:
1365   case ARM64::UBFMXri:
1366     Opc = NOpc;
1367     Opd0 = N->getOperand(0);
1368     LSB = cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
1369     MSB = cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
1370     return true;
1371   }
1372   // Unreachable
1373   return false;
1374 }
1375
1376 SDNode *ARM64DAGToDAGISel::SelectBitfieldExtractOp(SDNode *N) {
1377   unsigned Opc, LSB, MSB;
1378   SDValue Opd0;
1379   if (!isBitfieldExtractOp(CurDAG, N, Opc, Opd0, LSB, MSB))
1380     return NULL;
1381
1382   EVT VT = N->getValueType(0);
1383   SDValue Ops[] = { Opd0, CurDAG->getTargetConstant(LSB, VT),
1384                     CurDAG->getTargetConstant(MSB, VT) };
1385   return CurDAG->SelectNodeTo(N, Opc, VT, Ops, 3);
1386 }
1387
1388 // Is mask a i32 or i64 binary sequence 1..10..0 and
1389 // CountTrailingZeros(mask) == ExpectedTrailingZeros
1390 static bool isHighMask(uint64_t Mask, unsigned ExpectedTrailingZeros,
1391                        unsigned NumberOfIgnoredHighBits, EVT VT) {
1392   assert((VT == MVT::i32 || VT == MVT::i64) &&
1393          "i32 or i64 mask type expected!");
1394
1395   uint64_t ExpectedMask;
1396   if (VT == MVT::i32) {
1397     uint32_t ExpectedMaski32 = ~0 << ExpectedTrailingZeros;
1398     ExpectedMask = ExpectedMaski32;
1399     if (NumberOfIgnoredHighBits) {
1400       uint32_t highMask = ~0 << (32 - NumberOfIgnoredHighBits);
1401       Mask |= highMask;
1402     }
1403   } else {
1404     ExpectedMask = ((uint64_t) ~0) << ExpectedTrailingZeros;
1405     if (NumberOfIgnoredHighBits)
1406       Mask |= ((uint64_t) ~0) << (64 - NumberOfIgnoredHighBits);
1407   }
1408
1409   return Mask == ExpectedMask;
1410 }
1411
1412 // Look for bits that will be useful for later uses.
1413 // A bit is consider useless as soon as it is dropped and never used
1414 // before it as been dropped.
1415 // E.g., looking for useful bit of x
1416 // 1. y = x & 0x7
1417 // 2. z = y >> 2
1418 // After #1, x useful bits are 0x7, then the useful bits of x, live through
1419 // y.
1420 // After #2, the useful bits of x are 0x4.
1421 // However, if x is used on an unpredicatable instruction, then all its bits
1422 // are useful.
1423 // E.g.
1424 // 1. y = x & 0x7
1425 // 2. z = y >> 2
1426 // 3. str x, [@x]
1427 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth = 0);
1428
1429 static void getUsefulBitsFromAndWithImmediate(SDValue Op, APInt &UsefulBits,
1430                                               unsigned Depth) {
1431   uint64_t Imm =
1432       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
1433   Imm = ARM64_AM::decodeLogicalImmediate(Imm, UsefulBits.getBitWidth());
1434   UsefulBits &= APInt(UsefulBits.getBitWidth(), Imm);
1435   getUsefulBits(Op, UsefulBits, Depth + 1);
1436 }
1437
1438 static void getUsefulBitsFromBitfieldMoveOpd(SDValue Op, APInt &UsefulBits,
1439                                              uint64_t Imm, uint64_t MSB,
1440                                              unsigned Depth) {
1441   // inherit the bitwidth value
1442   APInt OpUsefulBits(UsefulBits);
1443   OpUsefulBits = 1;
1444
1445   if (MSB >= Imm) {
1446     OpUsefulBits = OpUsefulBits.shl(MSB - Imm + 1);
1447     --OpUsefulBits;
1448     // The interesting part will be in the lower part of the result
1449     getUsefulBits(Op, OpUsefulBits, Depth + 1);
1450     // The interesting part was starting at Imm in the argument
1451     OpUsefulBits = OpUsefulBits.shl(Imm);
1452   } else {
1453     OpUsefulBits = OpUsefulBits.shl(MSB + 1);
1454     --OpUsefulBits;
1455     // The interesting part will be shifted in the result
1456     OpUsefulBits = OpUsefulBits.shl(OpUsefulBits.getBitWidth() - Imm);
1457     getUsefulBits(Op, OpUsefulBits, Depth + 1);
1458     // The interesting part was at zero in the argument
1459     OpUsefulBits = OpUsefulBits.lshr(OpUsefulBits.getBitWidth() - Imm);
1460   }
1461
1462   UsefulBits &= OpUsefulBits;
1463 }
1464
1465 static void getUsefulBitsFromUBFM(SDValue Op, APInt &UsefulBits,
1466                                   unsigned Depth) {
1467   uint64_t Imm =
1468       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
1469   uint64_t MSB =
1470       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1471
1472   getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
1473 }
1474
1475 static void getUsefulBitsFromOrWithShiftedReg(SDValue Op, APInt &UsefulBits,
1476                                               unsigned Depth) {
1477   uint64_t ShiftTypeAndValue =
1478       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1479   APInt Mask(UsefulBits);
1480   Mask.clearAllBits();
1481   Mask.flipAllBits();
1482
1483   if (ARM64_AM::getShiftType(ShiftTypeAndValue) == ARM64_AM::LSL) {
1484     // Shift Left
1485     uint64_t ShiftAmt = ARM64_AM::getShiftValue(ShiftTypeAndValue);
1486     Mask = Mask.shl(ShiftAmt);
1487     getUsefulBits(Op, Mask, Depth + 1);
1488     Mask = Mask.lshr(ShiftAmt);
1489   } else if (ARM64_AM::getShiftType(ShiftTypeAndValue) == ARM64_AM::LSR) {
1490     // Shift Right
1491     // We do not handle ARM64_AM::ASR, because the sign will change the
1492     // number of useful bits
1493     uint64_t ShiftAmt = ARM64_AM::getShiftValue(ShiftTypeAndValue);
1494     Mask = Mask.lshr(ShiftAmt);
1495     getUsefulBits(Op, Mask, Depth + 1);
1496     Mask = Mask.shl(ShiftAmt);
1497   } else
1498     return;
1499
1500   UsefulBits &= Mask;
1501 }
1502
1503 static void getUsefulBitsFromBFM(SDValue Op, SDValue Orig, APInt &UsefulBits,
1504                                  unsigned Depth) {
1505   uint64_t Imm =
1506       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1507   uint64_t MSB =
1508       cast<const ConstantSDNode>(Op.getOperand(3).getNode())->getZExtValue();
1509
1510   if (Op.getOperand(1) == Orig)
1511     return getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
1512
1513   APInt OpUsefulBits(UsefulBits);
1514   OpUsefulBits = 1;
1515
1516   if (MSB >= Imm) {
1517     OpUsefulBits = OpUsefulBits.shl(MSB - Imm + 1);
1518     --OpUsefulBits;
1519     UsefulBits &= ~OpUsefulBits;
1520     getUsefulBits(Op, UsefulBits, Depth + 1);
1521   } else {
1522     OpUsefulBits = OpUsefulBits.shl(MSB + 1);
1523     --OpUsefulBits;
1524     UsefulBits = ~(OpUsefulBits.shl(OpUsefulBits.getBitWidth() - Imm));
1525     getUsefulBits(Op, UsefulBits, Depth + 1);
1526   }
1527 }
1528
1529 static void getUsefulBitsForUse(SDNode *UserNode, APInt &UsefulBits,
1530                                 SDValue Orig, unsigned Depth) {
1531
1532   // Users of this node should have already been instruction selected
1533   // FIXME: Can we turn that into an assert?
1534   if (!UserNode->isMachineOpcode())
1535     return;
1536
1537   switch (UserNode->getMachineOpcode()) {
1538   default:
1539     return;
1540   case ARM64::ANDSWri:
1541   case ARM64::ANDSXri:
1542   case ARM64::ANDWri:
1543   case ARM64::ANDXri:
1544     // We increment Depth only when we call the getUsefulBits
1545     return getUsefulBitsFromAndWithImmediate(SDValue(UserNode, 0), UsefulBits,
1546                                              Depth);
1547   case ARM64::UBFMWri:
1548   case ARM64::UBFMXri:
1549     return getUsefulBitsFromUBFM(SDValue(UserNode, 0), UsefulBits, Depth);
1550
1551   case ARM64::ORRWrs:
1552   case ARM64::ORRXrs:
1553     if (UserNode->getOperand(1) != Orig)
1554       return;
1555     return getUsefulBitsFromOrWithShiftedReg(SDValue(UserNode, 0), UsefulBits,
1556                                              Depth);
1557   case ARM64::BFMWri:
1558   case ARM64::BFMXri:
1559     return getUsefulBitsFromBFM(SDValue(UserNode, 0), Orig, UsefulBits, Depth);
1560   }
1561 }
1562
1563 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth) {
1564   if (Depth >= 6)
1565     return;
1566   // Initialize UsefulBits
1567   if (!Depth) {
1568     unsigned Bitwidth = Op.getValueType().getScalarType().getSizeInBits();
1569     // At the beginning, assume every produced bits is useful
1570     UsefulBits = APInt(Bitwidth, 0);
1571     UsefulBits.flipAllBits();
1572   }
1573   APInt UsersUsefulBits(UsefulBits.getBitWidth(), 0);
1574
1575   for (SDNode *Node : Op.getNode()->uses()) {
1576     // A use cannot produce useful bits
1577     APInt UsefulBitsForUse = APInt(UsefulBits);
1578     getUsefulBitsForUse(Node, UsefulBitsForUse, Op, Depth);
1579     UsersUsefulBits |= UsefulBitsForUse;
1580   }
1581   // UsefulBits contains the produced bits that are meaningful for the
1582   // current definition, thus a user cannot make a bit meaningful at
1583   // this point
1584   UsefulBits &= UsersUsefulBits;
1585 }
1586
1587 // Given a OR operation, check if we have the following pattern
1588 // ubfm c, b, imm, imm2 (or something that does the same jobs, see
1589 //                       isBitfieldExtractOp)
1590 // d = e & mask2 ; where mask is a binary sequence of 1..10..0 and
1591 //                 countTrailingZeros(mask2) == imm2 - imm + 1
1592 // f = d | c
1593 // if yes, given reference arguments will be update so that one can replace
1594 // the OR instruction with:
1595 // f = Opc Opd0, Opd1, LSB, MSB ; where Opc is a BFM, LSB = imm, and MSB = imm2
1596 static bool isBitfieldInsertOpFromOr(SDNode *N, unsigned &Opc, SDValue &Opd0,
1597                                      SDValue &Opd1, unsigned &LSB,
1598                                      unsigned &MSB, SelectionDAG *CurDAG) {
1599   assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
1600
1601   // Set Opc
1602   EVT VT = N->getValueType(0);
1603   if (VT == MVT::i32)
1604     Opc = ARM64::BFMWri;
1605   else if (VT == MVT::i64)
1606     Opc = ARM64::BFMXri;
1607   else
1608     return false;
1609
1610   // Because of simplify-demanded-bits in DAGCombine, involved masks may not
1611   // have the expected shape. Try to undo that.
1612   APInt UsefulBits;
1613   getUsefulBits(SDValue(N, 0), UsefulBits);
1614
1615   unsigned NumberOfIgnoredLowBits = UsefulBits.countTrailingZeros();
1616   unsigned NumberOfIgnoredHighBits = UsefulBits.countLeadingZeros();
1617
1618   // OR is commutative, check both possibilities (does llvm provide a
1619   // way to do that directely, e.g., via code matcher?)
1620   SDValue OrOpd1Val = N->getOperand(1);
1621   SDNode *OrOpd0 = N->getOperand(0).getNode();
1622   SDNode *OrOpd1 = N->getOperand(1).getNode();
1623   for (int i = 0; i < 2;
1624        ++i, std::swap(OrOpd0, OrOpd1), OrOpd1Val = N->getOperand(0)) {
1625     unsigned BFXOpc;
1626     // Set Opd1, LSB and MSB arguments by looking for
1627     // c = ubfm b, imm, imm2
1628     if (!isBitfieldExtractOp(CurDAG, OrOpd0, BFXOpc, Opd1, LSB, MSB,
1629                              NumberOfIgnoredLowBits, true))
1630       continue;
1631
1632     // Check that the returned opcode is compatible with the pattern,
1633     // i.e., same type and zero extended (U and not S)
1634     if ((BFXOpc != ARM64::UBFMXri && VT == MVT::i64) ||
1635         (BFXOpc != ARM64::UBFMWri && VT == MVT::i32))
1636       continue;
1637
1638     // Compute the width of the bitfield insertion
1639     int sMSB = MSB - LSB + 1;
1640     // FIXME: This constraints is to catch bitfield insertion we may
1641     // want to widen the pattern if we want to grab general bitfied
1642     // move case
1643     if (sMSB <= 0)
1644       continue;
1645
1646     // Check the second part of the pattern
1647     EVT VT = OrOpd1->getValueType(0);
1648     if (VT != MVT::i32 && VT != MVT::i64)
1649       continue;
1650
1651     // Compute the Known Zero for the candidate of the first operand.
1652     // This allows to catch more general case than just looking for
1653     // AND with imm. Indeed, simplify-demanded-bits may have removed
1654     // the AND instruction because it proves it was useless.
1655     APInt KnownZero, KnownOne;
1656     CurDAG->ComputeMaskedBits(OrOpd1Val, KnownZero, KnownOne);
1657
1658     // Check if there is enough room for the second operand to appear
1659     // in the first one
1660     if (KnownZero.countTrailingOnes() < (unsigned)sMSB)
1661       continue;
1662
1663     // Set the first operand
1664     uint64_t Imm;
1665     if (isOpcWithIntImmediate(OrOpd1, ISD::AND, Imm) &&
1666         isHighMask(Imm, sMSB, NumberOfIgnoredHighBits, VT))
1667       // In that case, we can eliminate the AND
1668       Opd0 = OrOpd1->getOperand(0);
1669     else
1670       // Maybe the AND has been removed by simplify-demanded-bits
1671       // or is useful because it discards more bits
1672       Opd0 = OrOpd1Val;
1673
1674     // both parts match
1675     return true;
1676   }
1677
1678   return false;
1679 }
1680
1681 SDNode *ARM64DAGToDAGISel::SelectBitfieldInsertOp(SDNode *N) {
1682   if (N->getOpcode() != ISD::OR)
1683     return NULL;
1684
1685   unsigned Opc;
1686   unsigned LSB, MSB;
1687   SDValue Opd0, Opd1;
1688
1689   if (!isBitfieldInsertOpFromOr(N, Opc, Opd0, Opd1, LSB, MSB, CurDAG))
1690     return NULL;
1691
1692   EVT VT = N->getValueType(0);
1693   SDValue Ops[] = { Opd0,
1694                     Opd1,
1695                     CurDAG->getTargetConstant(LSB, VT),
1696                     CurDAG->getTargetConstant(MSB, VT) };
1697   return CurDAG->SelectNodeTo(N, Opc, VT, Ops, 4);
1698 }
1699
1700 SDNode *ARM64DAGToDAGISel::SelectLIBM(SDNode *N) {
1701   EVT VT = N->getValueType(0);
1702   unsigned Variant;
1703   unsigned Opc;
1704   unsigned FRINTXOpcs[] = { ARM64::FRINTXSr, ARM64::FRINTXDr };
1705
1706   if (VT == MVT::f32) {
1707     Variant = 0;
1708   } else if (VT == MVT::f64) {
1709     Variant = 1;
1710   } else
1711     return 0; // Unrecognized argument type. Fall back on default codegen.
1712
1713   // Pick the FRINTX variant needed to set the flags.
1714   unsigned FRINTXOpc = FRINTXOpcs[Variant];
1715
1716   switch (N->getOpcode()) {
1717   default:
1718     return 0; // Unrecognized libm ISD node. Fall back on default codegen.
1719   case ISD::FCEIL: {
1720     unsigned FRINTPOpcs[] = { ARM64::FRINTPSr, ARM64::FRINTPDr };
1721     Opc = FRINTPOpcs[Variant];
1722     break;
1723   }
1724   case ISD::FFLOOR: {
1725     unsigned FRINTMOpcs[] = { ARM64::FRINTMSr, ARM64::FRINTMDr };
1726     Opc = FRINTMOpcs[Variant];
1727     break;
1728   }
1729   case ISD::FTRUNC: {
1730     unsigned FRINTZOpcs[] = { ARM64::FRINTZSr, ARM64::FRINTZDr };
1731     Opc = FRINTZOpcs[Variant];
1732     break;
1733   }
1734   case ISD::FROUND: {
1735     unsigned FRINTAOpcs[] = { ARM64::FRINTASr, ARM64::FRINTADr };
1736     Opc = FRINTAOpcs[Variant];
1737     break;
1738   }
1739   }
1740
1741   SDLoc dl(N);
1742   SDValue In = N->getOperand(0);
1743   SmallVector<SDValue, 2> Ops;
1744   Ops.push_back(In);
1745
1746   if (!TM.Options.UnsafeFPMath) {
1747     SDNode *FRINTX = CurDAG->getMachineNode(FRINTXOpc, dl, VT, MVT::Glue, In);
1748     Ops.push_back(SDValue(FRINTX, 1));
1749   }
1750
1751   return CurDAG->getMachineNode(Opc, dl, VT, Ops);
1752 }
1753
1754 SDNode *ARM64DAGToDAGISel::Select(SDNode *Node) {
1755   // Dump information about the Node being selected
1756   DEBUG(errs() << "Selecting: ");
1757   DEBUG(Node->dump(CurDAG));
1758   DEBUG(errs() << "\n");
1759
1760   // If we have a custom node, we already have selected!
1761   if (Node->isMachineOpcode()) {
1762     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
1763     Node->setNodeId(-1);
1764     return NULL;
1765   }
1766
1767   // Few custom selection stuff.
1768   SDNode *ResNode = 0;
1769   EVT VT = Node->getValueType(0);
1770
1771   switch (Node->getOpcode()) {
1772   default:
1773     break;
1774
1775   case ISD::ADD:
1776     if (SDNode *I = SelectMLAV64LaneV128(Node))
1777       return I;
1778     break;
1779
1780   case ISD::ATOMIC_LOAD_ADD:
1781     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_ADD_I8,
1782                         ARM64::ATOMIC_LOAD_ADD_I16, ARM64::ATOMIC_LOAD_ADD_I32,
1783                         ARM64::ATOMIC_LOAD_ADD_I64);
1784   case ISD::ATOMIC_LOAD_SUB:
1785     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_SUB_I8,
1786                         ARM64::ATOMIC_LOAD_SUB_I16, ARM64::ATOMIC_LOAD_SUB_I32,
1787                         ARM64::ATOMIC_LOAD_SUB_I64);
1788   case ISD::ATOMIC_LOAD_AND:
1789     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_AND_I8,
1790                         ARM64::ATOMIC_LOAD_AND_I16, ARM64::ATOMIC_LOAD_AND_I32,
1791                         ARM64::ATOMIC_LOAD_AND_I64);
1792   case ISD::ATOMIC_LOAD_OR:
1793     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_OR_I8,
1794                         ARM64::ATOMIC_LOAD_OR_I16, ARM64::ATOMIC_LOAD_OR_I32,
1795                         ARM64::ATOMIC_LOAD_OR_I64);
1796   case ISD::ATOMIC_LOAD_XOR:
1797     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_XOR_I8,
1798                         ARM64::ATOMIC_LOAD_XOR_I16, ARM64::ATOMIC_LOAD_XOR_I32,
1799                         ARM64::ATOMIC_LOAD_XOR_I64);
1800   case ISD::ATOMIC_LOAD_NAND:
1801     return SelectAtomic(
1802         Node, ARM64::ATOMIC_LOAD_NAND_I8, ARM64::ATOMIC_LOAD_NAND_I16,
1803         ARM64::ATOMIC_LOAD_NAND_I32, ARM64::ATOMIC_LOAD_NAND_I64);
1804   case ISD::ATOMIC_LOAD_MIN:
1805     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_MIN_I8,
1806                         ARM64::ATOMIC_LOAD_MIN_I16, ARM64::ATOMIC_LOAD_MIN_I32,
1807                         ARM64::ATOMIC_LOAD_MIN_I64);
1808   case ISD::ATOMIC_LOAD_MAX:
1809     return SelectAtomic(Node, ARM64::ATOMIC_LOAD_MAX_I8,
1810                         ARM64::ATOMIC_LOAD_MAX_I16, ARM64::ATOMIC_LOAD_MAX_I32,
1811                         ARM64::ATOMIC_LOAD_MAX_I64);
1812   case ISD::ATOMIC_LOAD_UMIN:
1813     return SelectAtomic(
1814         Node, ARM64::ATOMIC_LOAD_UMIN_I8, ARM64::ATOMIC_LOAD_UMIN_I16,
1815         ARM64::ATOMIC_LOAD_UMIN_I32, ARM64::ATOMIC_LOAD_UMIN_I64);
1816   case ISD::ATOMIC_LOAD_UMAX:
1817     return SelectAtomic(
1818         Node, ARM64::ATOMIC_LOAD_UMAX_I8, ARM64::ATOMIC_LOAD_UMAX_I16,
1819         ARM64::ATOMIC_LOAD_UMAX_I32, ARM64::ATOMIC_LOAD_UMAX_I64);
1820   case ISD::ATOMIC_SWAP:
1821     return SelectAtomic(Node, ARM64::ATOMIC_SWAP_I8, ARM64::ATOMIC_SWAP_I16,
1822                         ARM64::ATOMIC_SWAP_I32, ARM64::ATOMIC_SWAP_I64);
1823   case ISD::ATOMIC_CMP_SWAP:
1824     return SelectAtomic(Node, ARM64::ATOMIC_CMP_SWAP_I8,
1825                         ARM64::ATOMIC_CMP_SWAP_I16, ARM64::ATOMIC_CMP_SWAP_I32,
1826                         ARM64::ATOMIC_CMP_SWAP_I64);
1827
1828   case ISD::LOAD: {
1829     // Try to select as an indexed load. Fall through to normal processing
1830     // if we can't.
1831     bool Done = false;
1832     SDNode *I = SelectIndexedLoad(Node, Done);
1833     if (Done)
1834       return I;
1835     break;
1836   }
1837
1838   case ISD::SRL:
1839   case ISD::AND:
1840   case ISD::SRA:
1841     if (SDNode *I = SelectBitfieldExtractOp(Node))
1842       return I;
1843     break;
1844
1845   case ISD::OR:
1846     if (SDNode *I = SelectBitfieldInsertOp(Node))
1847       return I;
1848     break;
1849
1850   case ISD::EXTRACT_VECTOR_ELT: {
1851     // Extracting lane zero is a special case where we can just use a plain
1852     // EXTRACT_SUBREG instruction, which will become FMOV. This is easier for
1853     // the rest of the compiler, especially the register allocator and copyi
1854     // propagation, to reason about, so is preferred when it's possible to
1855     // use it.
1856     ConstantSDNode *LaneNode = cast<ConstantSDNode>(Node->getOperand(1));
1857     // Bail and use the default Select() for non-zero lanes.
1858     if (LaneNode->getZExtValue() != 0)
1859       break;
1860     // If the element type is not the same as the result type, likewise
1861     // bail and use the default Select(), as there's more to do than just
1862     // a cross-class COPY. This catches extracts of i8 and i16 elements
1863     // since they will need an explicit zext.
1864     if (VT != Node->getOperand(0).getValueType().getVectorElementType())
1865       break;
1866     unsigned SubReg;
1867     switch (Node->getOperand(0)
1868                 .getValueType()
1869                 .getVectorElementType()
1870                 .getSizeInBits()) {
1871     default:
1872       assert(0 && "Unexpected vector element type!");
1873     case 64:
1874       SubReg = ARM64::dsub;
1875       break;
1876     case 32:
1877       SubReg = ARM64::ssub;
1878       break;
1879     case 16: // FALLTHROUGH
1880     case 8:
1881       llvm_unreachable("unexpected zext-requiring extract element!");
1882     }
1883     SDValue Extract = CurDAG->getTargetExtractSubreg(SubReg, SDLoc(Node), VT,
1884                                                      Node->getOperand(0));
1885     DEBUG(dbgs() << "ISEL: Custom selection!\n=> ");
1886     DEBUG(Extract->dumpr(CurDAG));
1887     DEBUG(dbgs() << "\n");
1888     return Extract.getNode();
1889   }
1890   case ISD::Constant: {
1891     // Materialize zero constants as copies from WZR/XZR.  This allows
1892     // the coalescer to propagate these into other instructions.
1893     ConstantSDNode *ConstNode = cast<ConstantSDNode>(Node);
1894     if (ConstNode->isNullValue()) {
1895       if (VT == MVT::i32)
1896         return CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node),
1897                                       ARM64::WZR, MVT::i32).getNode();
1898       else if (VT == MVT::i64)
1899         return CurDAG->getCopyFromReg(CurDAG->getEntryNode(), SDLoc(Node),
1900                                       ARM64::XZR, MVT::i64).getNode();
1901     }
1902     break;
1903   }
1904
1905   case ISD::FrameIndex: {
1906     // Selects to ADDXri FI, 0 which in turn will become ADDXri SP, imm.
1907     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
1908     unsigned Shifter = ARM64_AM::getShifterImm(ARM64_AM::LSL, 0);
1909     const TargetLowering *TLI = getTargetLowering();
1910     SDValue TFI = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy());
1911     SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, MVT::i32),
1912                       CurDAG->getTargetConstant(Shifter, MVT::i32) };
1913     return CurDAG->SelectNodeTo(Node, ARM64::ADDXri, MVT::i64, Ops, 3);
1914   }
1915   case ISD::INTRINSIC_W_CHAIN: {
1916     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
1917     switch (IntNo) {
1918     default:
1919       break;
1920     case Intrinsic::arm64_ldxp: {
1921       SDValue MemAddr = Node->getOperand(2);
1922       SDLoc DL(Node);
1923       SDValue Chain = Node->getOperand(0);
1924
1925       SDNode *Ld = CurDAG->getMachineNode(ARM64::LDXPX, DL, MVT::i64, MVT::i64,
1926                                           MVT::Other, MemAddr, Chain);
1927
1928       // Transfer memoperands.
1929       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1930       MemOp[0] = cast<MemIntrinsicSDNode>(Node)->getMemOperand();
1931       cast<MachineSDNode>(Ld)->setMemRefs(MemOp, MemOp + 1);
1932       return Ld;
1933     }
1934     case Intrinsic::arm64_stxp: {
1935       SDLoc DL(Node);
1936       SDValue Chain = Node->getOperand(0);
1937       SDValue ValLo = Node->getOperand(2);
1938       SDValue ValHi = Node->getOperand(3);
1939       SDValue MemAddr = Node->getOperand(4);
1940
1941       // Place arguments in the right order.
1942       SmallVector<SDValue, 7> Ops;
1943       Ops.push_back(ValLo);
1944       Ops.push_back(ValHi);
1945       Ops.push_back(MemAddr);
1946       Ops.push_back(Chain);
1947
1948       SDNode *St =
1949           CurDAG->getMachineNode(ARM64::STXPX, DL, MVT::i32, MVT::Other, Ops);
1950       // Transfer memoperands.
1951       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1952       MemOp[0] = cast<MemIntrinsicSDNode>(Node)->getMemOperand();
1953       cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
1954
1955       return St;
1956     }
1957     case Intrinsic::arm64_neon_ld1x2:
1958       if (VT == MVT::v8i8)
1959         return SelectLoad(Node, 2, ARM64::LD1Twov8b, ARM64::dsub0);
1960       else if (VT == MVT::v16i8)
1961         return SelectLoad(Node, 2, ARM64::LD1Twov16b, ARM64::qsub0);
1962       else if (VT == MVT::v4i16)
1963         return SelectLoad(Node, 2, ARM64::LD1Twov4h, ARM64::dsub0);
1964       else if (VT == MVT::v8i16)
1965         return SelectLoad(Node, 2, ARM64::LD1Twov8h, ARM64::qsub0);
1966       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
1967         return SelectLoad(Node, 2, ARM64::LD1Twov2s, ARM64::dsub0);
1968       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
1969         return SelectLoad(Node, 2, ARM64::LD1Twov4s, ARM64::qsub0);
1970       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
1971         return SelectLoad(Node, 2, ARM64::LD1Twov1d, ARM64::dsub0);
1972       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
1973         return SelectLoad(Node, 2, ARM64::LD1Twov2d, ARM64::qsub0);
1974       break;
1975     case Intrinsic::arm64_neon_ld1x3:
1976       if (VT == MVT::v8i8)
1977         return SelectLoad(Node, 3, ARM64::LD1Threev8b, ARM64::dsub0);
1978       else if (VT == MVT::v16i8)
1979         return SelectLoad(Node, 3, ARM64::LD1Threev16b, ARM64::qsub0);
1980       else if (VT == MVT::v4i16)
1981         return SelectLoad(Node, 3, ARM64::LD1Threev4h, ARM64::dsub0);
1982       else if (VT == MVT::v8i16)
1983         return SelectLoad(Node, 3, ARM64::LD1Threev8h, ARM64::qsub0);
1984       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
1985         return SelectLoad(Node, 3, ARM64::LD1Threev2s, ARM64::dsub0);
1986       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
1987         return SelectLoad(Node, 3, ARM64::LD1Threev4s, ARM64::qsub0);
1988       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
1989         return SelectLoad(Node, 3, ARM64::LD1Threev1d, ARM64::dsub0);
1990       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
1991         return SelectLoad(Node, 3, ARM64::LD1Threev2d, ARM64::qsub0);
1992       break;
1993     case Intrinsic::arm64_neon_ld1x4:
1994       if (VT == MVT::v8i8)
1995         return SelectLoad(Node, 4, ARM64::LD1Fourv8b, ARM64::dsub0);
1996       else if (VT == MVT::v16i8)
1997         return SelectLoad(Node, 4, ARM64::LD1Fourv16b, ARM64::qsub0);
1998       else if (VT == MVT::v4i16)
1999         return SelectLoad(Node, 4, ARM64::LD1Fourv4h, ARM64::dsub0);
2000       else if (VT == MVT::v8i16)
2001         return SelectLoad(Node, 4, ARM64::LD1Fourv8h, ARM64::qsub0);
2002       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2003         return SelectLoad(Node, 4, ARM64::LD1Fourv2s, ARM64::dsub0);
2004       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2005         return SelectLoad(Node, 4, ARM64::LD1Fourv4s, ARM64::qsub0);
2006       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2007         return SelectLoad(Node, 4, ARM64::LD1Fourv1d, ARM64::dsub0);
2008       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2009         return SelectLoad(Node, 4, ARM64::LD1Fourv2d, ARM64::qsub0);
2010       break;
2011     case Intrinsic::arm64_neon_ld2:
2012       if (VT == MVT::v8i8)
2013         return SelectLoad(Node, 2, ARM64::LD2Twov8b, ARM64::dsub0);
2014       else if (VT == MVT::v16i8)
2015         return SelectLoad(Node, 2, ARM64::LD2Twov16b, ARM64::qsub0);
2016       else if (VT == MVT::v4i16)
2017         return SelectLoad(Node, 2, ARM64::LD2Twov4h, ARM64::dsub0);
2018       else if (VT == MVT::v8i16)
2019         return SelectLoad(Node, 2, ARM64::LD2Twov8h, ARM64::qsub0);
2020       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2021         return SelectLoad(Node, 2, ARM64::LD2Twov2s, ARM64::dsub0);
2022       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2023         return SelectLoad(Node, 2, ARM64::LD2Twov4s, ARM64::qsub0);
2024       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2025         return SelectLoad(Node, 2, ARM64::LD1Twov1d, ARM64::dsub0);
2026       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2027         return SelectLoad(Node, 2, ARM64::LD2Twov2d, ARM64::qsub0);
2028       break;
2029     case Intrinsic::arm64_neon_ld3:
2030       if (VT == MVT::v8i8)
2031         return SelectLoad(Node, 3, ARM64::LD3Threev8b, ARM64::dsub0);
2032       else if (VT == MVT::v16i8)
2033         return SelectLoad(Node, 3, ARM64::LD3Threev16b, ARM64::qsub0);
2034       else if (VT == MVT::v4i16)
2035         return SelectLoad(Node, 3, ARM64::LD3Threev4h, ARM64::dsub0);
2036       else if (VT == MVT::v8i16)
2037         return SelectLoad(Node, 3, ARM64::LD3Threev8h, ARM64::qsub0);
2038       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2039         return SelectLoad(Node, 3, ARM64::LD3Threev2s, ARM64::dsub0);
2040       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2041         return SelectLoad(Node, 3, ARM64::LD3Threev4s, ARM64::qsub0);
2042       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2043         return SelectLoad(Node, 3, ARM64::LD1Threev1d, ARM64::dsub0);
2044       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2045         return SelectLoad(Node, 3, ARM64::LD3Threev2d, ARM64::qsub0);
2046       break;
2047     case Intrinsic::arm64_neon_ld4:
2048       if (VT == MVT::v8i8)
2049         return SelectLoad(Node, 4, ARM64::LD4Fourv8b, ARM64::dsub0);
2050       else if (VT == MVT::v16i8)
2051         return SelectLoad(Node, 4, ARM64::LD4Fourv16b, ARM64::qsub0);
2052       else if (VT == MVT::v4i16)
2053         return SelectLoad(Node, 4, ARM64::LD4Fourv4h, ARM64::dsub0);
2054       else if (VT == MVT::v8i16)
2055         return SelectLoad(Node, 4, ARM64::LD4Fourv8h, ARM64::qsub0);
2056       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2057         return SelectLoad(Node, 4, ARM64::LD4Fourv2s, ARM64::dsub0);
2058       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2059         return SelectLoad(Node, 4, ARM64::LD4Fourv4s, ARM64::qsub0);
2060       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2061         return SelectLoad(Node, 4, ARM64::LD1Fourv1d, ARM64::dsub0);
2062       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2063         return SelectLoad(Node, 4, ARM64::LD4Fourv2d, ARM64::qsub0);
2064       break;
2065     case Intrinsic::arm64_neon_ld2r:
2066       if (VT == MVT::v8i8)
2067         return SelectLoad(Node, 2, ARM64::LD2Rv8b, ARM64::dsub0);
2068       else if (VT == MVT::v16i8)
2069         return SelectLoad(Node, 2, ARM64::LD2Rv16b, ARM64::qsub0);
2070       else if (VT == MVT::v4i16)
2071         return SelectLoad(Node, 2, ARM64::LD2Rv4h, ARM64::dsub0);
2072       else if (VT == MVT::v8i16)
2073         return SelectLoad(Node, 2, ARM64::LD2Rv8h, ARM64::qsub0);
2074       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2075         return SelectLoad(Node, 2, ARM64::LD2Rv2s, ARM64::dsub0);
2076       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2077         return SelectLoad(Node, 2, ARM64::LD2Rv4s, ARM64::qsub0);
2078       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2079         return SelectLoad(Node, 2, ARM64::LD2Rv1d, ARM64::dsub0);
2080       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2081         return SelectLoad(Node, 2, ARM64::LD2Rv2d, ARM64::qsub0);
2082       break;
2083     case Intrinsic::arm64_neon_ld3r:
2084       if (VT == MVT::v8i8)
2085         return SelectLoad(Node, 3, ARM64::LD3Rv8b, ARM64::dsub0);
2086       else if (VT == MVT::v16i8)
2087         return SelectLoad(Node, 3, ARM64::LD3Rv16b, ARM64::qsub0);
2088       else if (VT == MVT::v4i16)
2089         return SelectLoad(Node, 3, ARM64::LD3Rv4h, ARM64::dsub0);
2090       else if (VT == MVT::v8i16)
2091         return SelectLoad(Node, 3, ARM64::LD3Rv8h, ARM64::qsub0);
2092       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2093         return SelectLoad(Node, 3, ARM64::LD3Rv2s, ARM64::dsub0);
2094       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2095         return SelectLoad(Node, 3, ARM64::LD3Rv4s, ARM64::qsub0);
2096       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2097         return SelectLoad(Node, 3, ARM64::LD3Rv1d, ARM64::dsub0);
2098       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2099         return SelectLoad(Node, 3, ARM64::LD3Rv2d, ARM64::qsub0);
2100       break;
2101     case Intrinsic::arm64_neon_ld4r:
2102       if (VT == MVT::v8i8)
2103         return SelectLoad(Node, 4, ARM64::LD4Rv8b, ARM64::dsub0);
2104       else if (VT == MVT::v16i8)
2105         return SelectLoad(Node, 4, ARM64::LD4Rv16b, ARM64::qsub0);
2106       else if (VT == MVT::v4i16)
2107         return SelectLoad(Node, 4, ARM64::LD4Rv4h, ARM64::dsub0);
2108       else if (VT == MVT::v8i16)
2109         return SelectLoad(Node, 4, ARM64::LD4Rv8h, ARM64::qsub0);
2110       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2111         return SelectLoad(Node, 4, ARM64::LD4Rv2s, ARM64::dsub0);
2112       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2113         return SelectLoad(Node, 4, ARM64::LD4Rv4s, ARM64::qsub0);
2114       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2115         return SelectLoad(Node, 4, ARM64::LD4Rv1d, ARM64::dsub0);
2116       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2117         return SelectLoad(Node, 4, ARM64::LD4Rv2d, ARM64::qsub0);
2118       break;
2119     case Intrinsic::arm64_neon_ld2lane:
2120       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2121         return SelectLoadLane(Node, 2, ARM64::LD2i8);
2122       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2123         return SelectLoadLane(Node, 2, ARM64::LD2i16);
2124       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2125                VT == MVT::v2f32)
2126         return SelectLoadLane(Node, 2, ARM64::LD2i32);
2127       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2128                VT == MVT::v1f64)
2129         return SelectLoadLane(Node, 2, ARM64::LD2i64);
2130       break;
2131     case Intrinsic::arm64_neon_ld3lane:
2132       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2133         return SelectLoadLane(Node, 3, ARM64::LD3i8);
2134       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2135         return SelectLoadLane(Node, 3, ARM64::LD3i16);
2136       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2137                VT == MVT::v2f32)
2138         return SelectLoadLane(Node, 3, ARM64::LD3i32);
2139       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2140                VT == MVT::v1f64)
2141         return SelectLoadLane(Node, 3, ARM64::LD3i64);
2142       break;
2143     case Intrinsic::arm64_neon_ld4lane:
2144       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2145         return SelectLoadLane(Node, 4, ARM64::LD4i8);
2146       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2147         return SelectLoadLane(Node, 4, ARM64::LD4i16);
2148       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2149                VT == MVT::v2f32)
2150         return SelectLoadLane(Node, 4, ARM64::LD4i32);
2151       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2152                VT == MVT::v1f64)
2153         return SelectLoadLane(Node, 4, ARM64::LD4i64);
2154       break;
2155     }
2156   } break;
2157   case ISD::INTRINSIC_WO_CHAIN: {
2158     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
2159     switch (IntNo) {
2160     default:
2161       break;
2162     case Intrinsic::arm64_neon_tbl2:
2163       return SelectTable(Node, 2, VT == MVT::v8i8 ? ARM64::TBLv8i8Two
2164                                                   : ARM64::TBLv16i8Two,
2165                          false);
2166     case Intrinsic::arm64_neon_tbl3:
2167       return SelectTable(Node, 3, VT == MVT::v8i8 ? ARM64::TBLv8i8Three
2168                                                   : ARM64::TBLv16i8Three,
2169                          false);
2170     case Intrinsic::arm64_neon_tbl4:
2171       return SelectTable(Node, 4, VT == MVT::v8i8 ? ARM64::TBLv8i8Four
2172                                                   : ARM64::TBLv16i8Four,
2173                          false);
2174     case Intrinsic::arm64_neon_tbx2:
2175       return SelectTable(Node, 2, VT == MVT::v8i8 ? ARM64::TBXv8i8Two
2176                                                   : ARM64::TBXv16i8Two,
2177                          true);
2178     case Intrinsic::arm64_neon_tbx3:
2179       return SelectTable(Node, 3, VT == MVT::v8i8 ? ARM64::TBXv8i8Three
2180                                                   : ARM64::TBXv16i8Three,
2181                          true);
2182     case Intrinsic::arm64_neon_tbx4:
2183       return SelectTable(Node, 4, VT == MVT::v8i8 ? ARM64::TBXv8i8Four
2184                                                   : ARM64::TBXv16i8Four,
2185                          true);
2186     case Intrinsic::arm64_neon_smull:
2187     case Intrinsic::arm64_neon_umull:
2188       if (SDNode *N = SelectMULLV64LaneV128(IntNo, Node))
2189         return N;
2190       break;
2191     }
2192     break;
2193   }
2194   case ISD::INTRINSIC_VOID: {
2195     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2196     if (Node->getNumOperands() >= 3)
2197       VT = Node->getOperand(2)->getValueType(0);
2198     switch (IntNo) {
2199     default:
2200       break;
2201     case Intrinsic::arm64_neon_st1x2: {
2202       if (VT == MVT::v8i8)
2203         return SelectStore(Node, 2, ARM64::ST1Twov8b);
2204       else if (VT == MVT::v16i8)
2205         return SelectStore(Node, 2, ARM64::ST1Twov16b);
2206       else if (VT == MVT::v4i16)
2207         return SelectStore(Node, 2, ARM64::ST1Twov4h);
2208       else if (VT == MVT::v8i16)
2209         return SelectStore(Node, 2, ARM64::ST1Twov8h);
2210       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2211         return SelectStore(Node, 2, ARM64::ST1Twov2s);
2212       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2213         return SelectStore(Node, 2, ARM64::ST1Twov4s);
2214       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2215         return SelectStore(Node, 2, ARM64::ST1Twov2d);
2216       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2217         return SelectStore(Node, 2, ARM64::ST1Twov1d);
2218       break;
2219     }
2220     case Intrinsic::arm64_neon_st1x3: {
2221       if (VT == MVT::v8i8)
2222         return SelectStore(Node, 3, ARM64::ST1Threev8b);
2223       else if (VT == MVT::v16i8)
2224         return SelectStore(Node, 3, ARM64::ST1Threev16b);
2225       else if (VT == MVT::v4i16)
2226         return SelectStore(Node, 3, ARM64::ST1Threev4h);
2227       else if (VT == MVT::v8i16)
2228         return SelectStore(Node, 3, ARM64::ST1Threev8h);
2229       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2230         return SelectStore(Node, 3, ARM64::ST1Threev2s);
2231       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2232         return SelectStore(Node, 3, ARM64::ST1Threev4s);
2233       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2234         return SelectStore(Node, 3, ARM64::ST1Threev2d);
2235       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2236         return SelectStore(Node, 3, ARM64::ST1Threev1d);
2237       break;
2238     }
2239     case Intrinsic::arm64_neon_st1x4: {
2240       if (VT == MVT::v8i8)
2241         return SelectStore(Node, 4, ARM64::ST1Fourv8b);
2242       else if (VT == MVT::v16i8)
2243         return SelectStore(Node, 4, ARM64::ST1Fourv16b);
2244       else if (VT == MVT::v4i16)
2245         return SelectStore(Node, 4, ARM64::ST1Fourv4h);
2246       else if (VT == MVT::v8i16)
2247         return SelectStore(Node, 4, ARM64::ST1Fourv8h);
2248       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2249         return SelectStore(Node, 4, ARM64::ST1Fourv2s);
2250       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2251         return SelectStore(Node, 4, ARM64::ST1Fourv4s);
2252       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2253         return SelectStore(Node, 4, ARM64::ST1Fourv2d);
2254       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2255         return SelectStore(Node, 4, ARM64::ST1Fourv1d);
2256       break;
2257     }
2258     case Intrinsic::arm64_neon_st2: {
2259       if (VT == MVT::v8i8)
2260         return SelectStore(Node, 2, ARM64::ST2Twov8b);
2261       else if (VT == MVT::v16i8)
2262         return SelectStore(Node, 2, ARM64::ST2Twov16b);
2263       else if (VT == MVT::v4i16)
2264         return SelectStore(Node, 2, ARM64::ST2Twov4h);
2265       else if (VT == MVT::v8i16)
2266         return SelectStore(Node, 2, ARM64::ST2Twov8h);
2267       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2268         return SelectStore(Node, 2, ARM64::ST2Twov2s);
2269       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2270         return SelectStore(Node, 2, ARM64::ST2Twov4s);
2271       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2272         return SelectStore(Node, 2, ARM64::ST2Twov2d);
2273       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2274         return SelectStore(Node, 2, ARM64::ST1Twov1d);
2275       break;
2276     }
2277     case Intrinsic::arm64_neon_st3: {
2278       if (VT == MVT::v8i8)
2279         return SelectStore(Node, 3, ARM64::ST3Threev8b);
2280       else if (VT == MVT::v16i8)
2281         return SelectStore(Node, 3, ARM64::ST3Threev16b);
2282       else if (VT == MVT::v4i16)
2283         return SelectStore(Node, 3, ARM64::ST3Threev4h);
2284       else if (VT == MVT::v8i16)
2285         return SelectStore(Node, 3, ARM64::ST3Threev8h);
2286       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2287         return SelectStore(Node, 3, ARM64::ST3Threev2s);
2288       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2289         return SelectStore(Node, 3, ARM64::ST3Threev4s);
2290       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2291         return SelectStore(Node, 3, ARM64::ST3Threev2d);
2292       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2293         return SelectStore(Node, 3, ARM64::ST1Threev1d);
2294       break;
2295     }
2296     case Intrinsic::arm64_neon_st4: {
2297       if (VT == MVT::v8i8)
2298         return SelectStore(Node, 4, ARM64::ST4Fourv8b);
2299       else if (VT == MVT::v16i8)
2300         return SelectStore(Node, 4, ARM64::ST4Fourv16b);
2301       else if (VT == MVT::v4i16)
2302         return SelectStore(Node, 4, ARM64::ST4Fourv4h);
2303       else if (VT == MVT::v8i16)
2304         return SelectStore(Node, 4, ARM64::ST4Fourv8h);
2305       else if (VT == MVT::v2i32 || VT == MVT::v2f32)
2306         return SelectStore(Node, 4, ARM64::ST4Fourv2s);
2307       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2308         return SelectStore(Node, 4, ARM64::ST4Fourv4s);
2309       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2310         return SelectStore(Node, 4, ARM64::ST4Fourv2d);
2311       else if (VT == MVT::v1i64 || VT == MVT::v1f64)
2312         return SelectStore(Node, 4, ARM64::ST1Fourv1d);
2313       break;
2314     }
2315     case Intrinsic::arm64_neon_st2lane: {
2316       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2317         return SelectStoreLane(Node, 2, ARM64::ST2i8);
2318       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2319         return SelectStoreLane(Node, 2, ARM64::ST2i16);
2320       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2321                VT == MVT::v2f32)
2322         return SelectStoreLane(Node, 2, ARM64::ST2i32);
2323       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2324                VT == MVT::v1f64)
2325         return SelectStoreLane(Node, 2, ARM64::ST2i64);
2326       break;
2327     }
2328     case Intrinsic::arm64_neon_st3lane: {
2329       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2330         return SelectStoreLane(Node, 3, ARM64::ST3i8);
2331       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2332         return SelectStoreLane(Node, 3, ARM64::ST3i16);
2333       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2334                VT == MVT::v2f32)
2335         return SelectStoreLane(Node, 3, ARM64::ST3i32);
2336       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2337                VT == MVT::v1f64)
2338         return SelectStoreLane(Node, 3, ARM64::ST3i64);
2339       break;
2340     }
2341     case Intrinsic::arm64_neon_st4lane: {
2342       if (VT == MVT::v16i8 || VT == MVT::v8i8)
2343         return SelectStoreLane(Node, 4, ARM64::ST4i8);
2344       else if (VT == MVT::v8i16 || VT == MVT::v4i16)
2345         return SelectStoreLane(Node, 4, ARM64::ST4i16);
2346       else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2347                VT == MVT::v2f32)
2348         return SelectStoreLane(Node, 4, ARM64::ST4i32);
2349       else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2350                VT == MVT::v1f64)
2351         return SelectStoreLane(Node, 4, ARM64::ST4i64);
2352       break;
2353     }
2354     }
2355   }
2356
2357   case ISD::FCEIL:
2358   case ISD::FFLOOR:
2359   case ISD::FTRUNC:
2360   case ISD::FROUND:
2361     if (SDNode *I = SelectLIBM(Node))
2362       return I;
2363     break;
2364   }
2365
2366   // Select the default instruction
2367   ResNode = SelectCode(Node);
2368
2369   DEBUG(errs() << "=> ");
2370   if (ResNode == NULL || ResNode == Node)
2371     DEBUG(Node->dump(CurDAG));
2372   else
2373     DEBUG(ResNode->dump(CurDAG));
2374   DEBUG(errs() << "\n");
2375
2376   return ResNode;
2377 }
2378
2379 /// createARM64ISelDag - This pass converts a legalized DAG into a
2380 /// ARM64-specific DAG, ready for instruction scheduling.
2381 FunctionPass *llvm::createARM64ISelDag(ARM64TargetMachine &TM,
2382                                        CodeGenOpt::Level OptLevel) {
2383   return new ARM64DAGToDAGISel(TM, OptLevel);
2384 }