1 //===-- AArch64ISelDAGToDAG.cpp - A dag to dag inst selector for AArch64 --===//
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 AArch64 target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64TargetMachine.h"
15 #include "MCTargetDesc/AArch64AddressingModes.h"
16 #include "llvm/ADT/APSInt.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 #define DEBUG_TYPE "aarch64-isel"
29 
30 //===--------------------------------------------------------------------===//
31 /// AArch64DAGToDAGISel - AArch64 specific code to select AArch64 machine
32 /// instructions for SelectionDAG operations.
33 ///
34 namespace {
35 
36 class AArch64DAGToDAGISel : public SelectionDAGISel {
37 
38   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
39   /// make the right decision when generating code for different targets.
40   const AArch64Subtarget *Subtarget;
41 
42   bool ForCodeSize;
43 
44 public:
45   explicit AArch64DAGToDAGISel(AArch64TargetMachine &tm,
46                                CodeGenOpt::Level OptLevel)
47       : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr),
48         ForCodeSize(false) {}
49 
50   const char *getPassName() const override {
51     return "AArch64 Instruction Selection";
52   }
53 
54   bool runOnMachineFunction(MachineFunction &MF) override {
55     ForCodeSize = MF.getFunction()->optForSize();
56     Subtarget = &MF.getSubtarget<AArch64Subtarget>();
57     return SelectionDAGISel::runOnMachineFunction(MF);
58   }
59 
60   void Select(SDNode *Node) override;
61 
62   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
63   /// inline asm expressions.
64   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
65                                     unsigned ConstraintID,
66                                     std::vector<SDValue> &OutOps) override;
67 
68   bool tryMLAV64LaneV128(SDNode *N);
69   bool tryMULLV64LaneV128(unsigned IntNo, SDNode *N);
70   bool SelectArithExtendedRegister(SDValue N, SDValue &Reg, SDValue &Shift);
71   bool SelectArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
72   bool SelectNegArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
73   bool SelectArithShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
74     return SelectShiftedRegister(N, false, Reg, Shift);
75   }
76   bool SelectLogicalShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
77     return SelectShiftedRegister(N, true, Reg, Shift);
78   }
79   bool SelectAddrModeIndexed7S8(SDValue N, SDValue &Base, SDValue &OffImm) {
80     return SelectAddrModeIndexed7S(N, 1, Base, OffImm);
81   }
82   bool SelectAddrModeIndexed7S16(SDValue N, SDValue &Base, SDValue &OffImm) {
83     return SelectAddrModeIndexed7S(N, 2, Base, OffImm);
84   }
85   bool SelectAddrModeIndexed7S32(SDValue N, SDValue &Base, SDValue &OffImm) {
86     return SelectAddrModeIndexed7S(N, 4, Base, OffImm);
87   }
88   bool SelectAddrModeIndexed7S64(SDValue N, SDValue &Base, SDValue &OffImm) {
89     return SelectAddrModeIndexed7S(N, 8, Base, OffImm);
90   }
91   bool SelectAddrModeIndexed7S128(SDValue N, SDValue &Base, SDValue &OffImm) {
92     return SelectAddrModeIndexed7S(N, 16, Base, OffImm);
93   }
94   bool SelectAddrModeIndexed8(SDValue N, SDValue &Base, SDValue &OffImm) {
95     return SelectAddrModeIndexed(N, 1, Base, OffImm);
96   }
97   bool SelectAddrModeIndexed16(SDValue N, SDValue &Base, SDValue &OffImm) {
98     return SelectAddrModeIndexed(N, 2, Base, OffImm);
99   }
100   bool SelectAddrModeIndexed32(SDValue N, SDValue &Base, SDValue &OffImm) {
101     return SelectAddrModeIndexed(N, 4, Base, OffImm);
102   }
103   bool SelectAddrModeIndexed64(SDValue N, SDValue &Base, SDValue &OffImm) {
104     return SelectAddrModeIndexed(N, 8, Base, OffImm);
105   }
106   bool SelectAddrModeIndexed128(SDValue N, SDValue &Base, SDValue &OffImm) {
107     return SelectAddrModeIndexed(N, 16, Base, OffImm);
108   }
109   bool SelectAddrModeUnscaled8(SDValue N, SDValue &Base, SDValue &OffImm) {
110     return SelectAddrModeUnscaled(N, 1, Base, OffImm);
111   }
112   bool SelectAddrModeUnscaled16(SDValue N, SDValue &Base, SDValue &OffImm) {
113     return SelectAddrModeUnscaled(N, 2, Base, OffImm);
114   }
115   bool SelectAddrModeUnscaled32(SDValue N, SDValue &Base, SDValue &OffImm) {
116     return SelectAddrModeUnscaled(N, 4, Base, OffImm);
117   }
118   bool SelectAddrModeUnscaled64(SDValue N, SDValue &Base, SDValue &OffImm) {
119     return SelectAddrModeUnscaled(N, 8, Base, OffImm);
120   }
121   bool SelectAddrModeUnscaled128(SDValue N, SDValue &Base, SDValue &OffImm) {
122     return SelectAddrModeUnscaled(N, 16, Base, OffImm);
123   }
124 
125   template<int Width>
126   bool SelectAddrModeWRO(SDValue N, SDValue &Base, SDValue &Offset,
127                          SDValue &SignExtend, SDValue &DoShift) {
128     return SelectAddrModeWRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
129   }
130 
131   template<int Width>
132   bool SelectAddrModeXRO(SDValue N, SDValue &Base, SDValue &Offset,
133                          SDValue &SignExtend, SDValue &DoShift) {
134     return SelectAddrModeXRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
135   }
136 
137 
138   /// Form sequences of consecutive 64/128-bit registers for use in NEON
139   /// instructions making use of a vector-list (e.g. ldN, tbl). Vecs must have
140   /// between 1 and 4 elements. If it contains a single element that is returned
141   /// unchanged; otherwise a REG_SEQUENCE value is returned.
142   SDValue createDTuple(ArrayRef<SDValue> Vecs);
143   SDValue createQTuple(ArrayRef<SDValue> Vecs);
144 
145   /// Generic helper for the createDTuple/createQTuple
146   /// functions. Those should almost always be called instead.
147   SDValue createTuple(ArrayRef<SDValue> Vecs, const unsigned RegClassIDs[],
148                       const unsigned SubRegs[]);
149 
150   void SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc, bool isExt);
151 
152   bool tryIndexedLoad(SDNode *N);
153 
154   void SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
155                      unsigned SubRegIdx);
156   void SelectPostLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
157                          unsigned SubRegIdx);
158   void SelectLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
159   void SelectPostLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
160 
161   void SelectStore(SDNode *N, unsigned NumVecs, unsigned Opc);
162   void SelectPostStore(SDNode *N, unsigned NumVecs, unsigned Opc);
163   void SelectStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
164   void SelectPostStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
165 
166   bool tryBitfieldExtractOp(SDNode *N);
167   bool tryBitfieldExtractOpFromSExt(SDNode *N);
168   bool tryBitfieldInsertOp(SDNode *N);
169   bool tryBitfieldInsertInZeroOp(SDNode *N);
170 
171   bool tryReadRegister(SDNode *N);
172   bool tryWriteRegister(SDNode *N);
173 
174 // Include the pieces autogenerated from the target description.
175 #include "AArch64GenDAGISel.inc"
176 
177 private:
178   bool SelectShiftedRegister(SDValue N, bool AllowROR, SDValue &Reg,
179                              SDValue &Shift);
180   bool SelectAddrModeIndexed7S(SDValue N, unsigned Size, SDValue &Base,
181                                SDValue &OffImm);
182   bool SelectAddrModeIndexed(SDValue N, unsigned Size, SDValue &Base,
183                              SDValue &OffImm);
184   bool SelectAddrModeUnscaled(SDValue N, unsigned Size, SDValue &Base,
185                               SDValue &OffImm);
186   bool SelectAddrModeWRO(SDValue N, unsigned Size, SDValue &Base,
187                          SDValue &Offset, SDValue &SignExtend,
188                          SDValue &DoShift);
189   bool SelectAddrModeXRO(SDValue N, unsigned Size, SDValue &Base,
190                          SDValue &Offset, SDValue &SignExtend,
191                          SDValue &DoShift);
192   bool isWorthFolding(SDValue V) const;
193   bool SelectExtendedSHL(SDValue N, unsigned Size, bool WantExtend,
194                          SDValue &Offset, SDValue &SignExtend);
195 
196   template<unsigned RegWidth>
197   bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos) {
198     return SelectCVTFixedPosOperand(N, FixedPos, RegWidth);
199   }
200 
201   bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos, unsigned Width);
202 
203   void SelectCMP_SWAP(SDNode *N);
204 
205 };
206 } // end anonymous namespace
207 
208 /// isIntImmediate - This method tests to see if the node is a constant
209 /// operand. If so Imm will receive the 32-bit value.
210 static bool isIntImmediate(const SDNode *N, uint64_t &Imm) {
211   if (const ConstantSDNode *C = dyn_cast<const ConstantSDNode>(N)) {
212     Imm = C->getZExtValue();
213     return true;
214   }
215   return false;
216 }
217 
218 // isIntImmediate - This method tests to see if a constant operand.
219 // If so Imm will receive the value.
220 static bool isIntImmediate(SDValue N, uint64_t &Imm) {
221   return isIntImmediate(N.getNode(), Imm);
222 }
223 
224 // isOpcWithIntImmediate - This method tests to see if the node is a specific
225 // opcode and that it has a immediate integer right operand.
226 // If so Imm will receive the 32 bit value.
227 static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc,
228                                   uint64_t &Imm) {
229   return N->getOpcode() == Opc &&
230          isIntImmediate(N->getOperand(1).getNode(), Imm);
231 }
232 
233 bool AArch64DAGToDAGISel::SelectInlineAsmMemoryOperand(
234     const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) {
235   switch(ConstraintID) {
236   default:
237     llvm_unreachable("Unexpected asm memory constraint");
238   case InlineAsm::Constraint_i:
239   case InlineAsm::Constraint_m:
240   case InlineAsm::Constraint_Q:
241     // Require the address to be in a register.  That is safe for all AArch64
242     // variants and it is hard to do anything much smarter without knowing
243     // how the operand is used.
244     OutOps.push_back(Op);
245     return false;
246   }
247   return true;
248 }
249 
250 /// SelectArithImmed - Select an immediate value that can be represented as
251 /// a 12-bit value shifted left by either 0 or 12.  If so, return true with
252 /// Val set to the 12-bit value and Shift set to the shifter operand.
253 bool AArch64DAGToDAGISel::SelectArithImmed(SDValue N, SDValue &Val,
254                                            SDValue &Shift) {
255   // This function is called from the addsub_shifted_imm ComplexPattern,
256   // which lists [imm] as the list of opcode it's interested in, however
257   // we still need to check whether the operand is actually an immediate
258   // here because the ComplexPattern opcode list is only used in
259   // root-level opcode matching.
260   if (!isa<ConstantSDNode>(N.getNode()))
261     return false;
262 
263   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
264   unsigned ShiftAmt;
265 
266   if (Immed >> 12 == 0) {
267     ShiftAmt = 0;
268   } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
269     ShiftAmt = 12;
270     Immed = Immed >> 12;
271   } else
272     return false;
273 
274   unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
275   SDLoc dl(N);
276   Val = CurDAG->getTargetConstant(Immed, dl, MVT::i32);
277   Shift = CurDAG->getTargetConstant(ShVal, dl, MVT::i32);
278   return true;
279 }
280 
281 /// SelectNegArithImmed - As above, but negates the value before trying to
282 /// select it.
283 bool AArch64DAGToDAGISel::SelectNegArithImmed(SDValue N, SDValue &Val,
284                                               SDValue &Shift) {
285   // This function is called from the addsub_shifted_imm ComplexPattern,
286   // which lists [imm] as the list of opcode it's interested in, however
287   // we still need to check whether the operand is actually an immediate
288   // here because the ComplexPattern opcode list is only used in
289   // root-level opcode matching.
290   if (!isa<ConstantSDNode>(N.getNode()))
291     return false;
292 
293   // The immediate operand must be a 24-bit zero-extended immediate.
294   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
295 
296   // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
297   // have the opposite effect on the C flag, so this pattern mustn't match under
298   // those circumstances.
299   if (Immed == 0)
300     return false;
301 
302   if (N.getValueType() == MVT::i32)
303     Immed = ~((uint32_t)Immed) + 1;
304   else
305     Immed = ~Immed + 1ULL;
306   if (Immed & 0xFFFFFFFFFF000000ULL)
307     return false;
308 
309   Immed &= 0xFFFFFFULL;
310   return SelectArithImmed(CurDAG->getConstant(Immed, SDLoc(N), MVT::i32), Val,
311                           Shift);
312 }
313 
314 /// getShiftTypeForNode - Translate a shift node to the corresponding
315 /// ShiftType value.
316 static AArch64_AM::ShiftExtendType getShiftTypeForNode(SDValue N) {
317   switch (N.getOpcode()) {
318   default:
319     return AArch64_AM::InvalidShiftExtend;
320   case ISD::SHL:
321     return AArch64_AM::LSL;
322   case ISD::SRL:
323     return AArch64_AM::LSR;
324   case ISD::SRA:
325     return AArch64_AM::ASR;
326   case ISD::ROTR:
327     return AArch64_AM::ROR;
328   }
329 }
330 
331 /// \brief Determine whether it is worth to fold V into an extended register.
332 bool AArch64DAGToDAGISel::isWorthFolding(SDValue V) const {
333   // it hurts if the value is used at least twice, unless we are optimizing
334   // for code size.
335   return ForCodeSize || V.hasOneUse();
336 }
337 
338 /// SelectShiftedRegister - Select a "shifted register" operand.  If the value
339 /// is not shifted, set the Shift operand to default of "LSL 0".  The logical
340 /// instructions allow the shifted register to be rotated, but the arithmetic
341 /// instructions do not.  The AllowROR parameter specifies whether ROR is
342 /// supported.
343 bool AArch64DAGToDAGISel::SelectShiftedRegister(SDValue N, bool AllowROR,
344                                                 SDValue &Reg, SDValue &Shift) {
345   AArch64_AM::ShiftExtendType ShType = getShiftTypeForNode(N);
346   if (ShType == AArch64_AM::InvalidShiftExtend)
347     return false;
348   if (!AllowROR && ShType == AArch64_AM::ROR)
349     return false;
350 
351   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
352     unsigned BitSize = N.getValueType().getSizeInBits();
353     unsigned Val = RHS->getZExtValue() & (BitSize - 1);
354     unsigned ShVal = AArch64_AM::getShifterImm(ShType, Val);
355 
356     Reg = N.getOperand(0);
357     Shift = CurDAG->getTargetConstant(ShVal, SDLoc(N), MVT::i32);
358     return isWorthFolding(N);
359   }
360 
361   return false;
362 }
363 
364 /// getExtendTypeForNode - Translate an extend node to the corresponding
365 /// ExtendType value.
366 static AArch64_AM::ShiftExtendType
367 getExtendTypeForNode(SDValue N, bool IsLoadStore = false) {
368   if (N.getOpcode() == ISD::SIGN_EXTEND ||
369       N.getOpcode() == ISD::SIGN_EXTEND_INREG) {
370     EVT SrcVT;
371     if (N.getOpcode() == ISD::SIGN_EXTEND_INREG)
372       SrcVT = cast<VTSDNode>(N.getOperand(1))->getVT();
373     else
374       SrcVT = N.getOperand(0).getValueType();
375 
376     if (!IsLoadStore && SrcVT == MVT::i8)
377       return AArch64_AM::SXTB;
378     else if (!IsLoadStore && SrcVT == MVT::i16)
379       return AArch64_AM::SXTH;
380     else if (SrcVT == MVT::i32)
381       return AArch64_AM::SXTW;
382     assert(SrcVT != MVT::i64 && "extend from 64-bits?");
383 
384     return AArch64_AM::InvalidShiftExtend;
385   } else if (N.getOpcode() == ISD::ZERO_EXTEND ||
386              N.getOpcode() == ISD::ANY_EXTEND) {
387     EVT SrcVT = N.getOperand(0).getValueType();
388     if (!IsLoadStore && SrcVT == MVT::i8)
389       return AArch64_AM::UXTB;
390     else if (!IsLoadStore && SrcVT == MVT::i16)
391       return AArch64_AM::UXTH;
392     else if (SrcVT == MVT::i32)
393       return AArch64_AM::UXTW;
394     assert(SrcVT != MVT::i64 && "extend from 64-bits?");
395 
396     return AArch64_AM::InvalidShiftExtend;
397   } else if (N.getOpcode() == ISD::AND) {
398     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
399     if (!CSD)
400       return AArch64_AM::InvalidShiftExtend;
401     uint64_t AndMask = CSD->getZExtValue();
402 
403     switch (AndMask) {
404     default:
405       return AArch64_AM::InvalidShiftExtend;
406     case 0xFF:
407       return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
408     case 0xFFFF:
409       return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
410     case 0xFFFFFFFF:
411       return AArch64_AM::UXTW;
412     }
413   }
414 
415   return AArch64_AM::InvalidShiftExtend;
416 }
417 
418 // Helper for SelectMLAV64LaneV128 - Recognize high lane extracts.
419 static bool checkHighLaneIndex(SDNode *DL, SDValue &LaneOp, int &LaneIdx) {
420   if (DL->getOpcode() != AArch64ISD::DUPLANE16 &&
421       DL->getOpcode() != AArch64ISD::DUPLANE32)
422     return false;
423 
424   SDValue SV = DL->getOperand(0);
425   if (SV.getOpcode() != ISD::INSERT_SUBVECTOR)
426     return false;
427 
428   SDValue EV = SV.getOperand(1);
429   if (EV.getOpcode() != ISD::EXTRACT_SUBVECTOR)
430     return false;
431 
432   ConstantSDNode *DLidx = cast<ConstantSDNode>(DL->getOperand(1).getNode());
433   ConstantSDNode *EVidx = cast<ConstantSDNode>(EV.getOperand(1).getNode());
434   LaneIdx = DLidx->getSExtValue() + EVidx->getSExtValue();
435   LaneOp = EV.getOperand(0);
436 
437   return true;
438 }
439 
440 // Helper for SelectOpcV64LaneV128 - Recognize operations where one operand is a
441 // high lane extract.
442 static bool checkV64LaneV128(SDValue Op0, SDValue Op1, SDValue &StdOp,
443                              SDValue &LaneOp, int &LaneIdx) {
444 
445   if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx)) {
446     std::swap(Op0, Op1);
447     if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx))
448       return false;
449   }
450   StdOp = Op1;
451   return true;
452 }
453 
454 /// SelectMLAV64LaneV128 - AArch64 supports vector MLAs where one multiplicand
455 /// is a lane in the upper half of a 128-bit vector.  Recognize and select this
456 /// so that we don't emit unnecessary lane extracts.
457 bool AArch64DAGToDAGISel::tryMLAV64LaneV128(SDNode *N) {
458   SDLoc dl(N);
459   SDValue Op0 = N->getOperand(0);
460   SDValue Op1 = N->getOperand(1);
461   SDValue MLAOp1;   // Will hold ordinary multiplicand for MLA.
462   SDValue MLAOp2;   // Will hold lane-accessed multiplicand for MLA.
463   int LaneIdx = -1; // Will hold the lane index.
464 
465   if (Op1.getOpcode() != ISD::MUL ||
466       !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
467                         LaneIdx)) {
468     std::swap(Op0, Op1);
469     if (Op1.getOpcode() != ISD::MUL ||
470         !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
471                           LaneIdx))
472       return false;
473   }
474 
475   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
476 
477   SDValue Ops[] = { Op0, MLAOp1, MLAOp2, LaneIdxVal };
478 
479   unsigned MLAOpc = ~0U;
480 
481   switch (N->getSimpleValueType(0).SimpleTy) {
482   default:
483     llvm_unreachable("Unrecognized MLA.");
484   case MVT::v4i16:
485     MLAOpc = AArch64::MLAv4i16_indexed;
486     break;
487   case MVT::v8i16:
488     MLAOpc = AArch64::MLAv8i16_indexed;
489     break;
490   case MVT::v2i32:
491     MLAOpc = AArch64::MLAv2i32_indexed;
492     break;
493   case MVT::v4i32:
494     MLAOpc = AArch64::MLAv4i32_indexed;
495     break;
496   }
497 
498   ReplaceNode(N, CurDAG->getMachineNode(MLAOpc, dl, N->getValueType(0), Ops));
499   return true;
500 }
501 
502 bool AArch64DAGToDAGISel::tryMULLV64LaneV128(unsigned IntNo, SDNode *N) {
503   SDLoc dl(N);
504   SDValue SMULLOp0;
505   SDValue SMULLOp1;
506   int LaneIdx;
507 
508   if (!checkV64LaneV128(N->getOperand(1), N->getOperand(2), SMULLOp0, SMULLOp1,
509                         LaneIdx))
510     return false;
511 
512   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
513 
514   SDValue Ops[] = { SMULLOp0, SMULLOp1, LaneIdxVal };
515 
516   unsigned SMULLOpc = ~0U;
517 
518   if (IntNo == Intrinsic::aarch64_neon_smull) {
519     switch (N->getSimpleValueType(0).SimpleTy) {
520     default:
521       llvm_unreachable("Unrecognized SMULL.");
522     case MVT::v4i32:
523       SMULLOpc = AArch64::SMULLv4i16_indexed;
524       break;
525     case MVT::v2i64:
526       SMULLOpc = AArch64::SMULLv2i32_indexed;
527       break;
528     }
529   } else if (IntNo == Intrinsic::aarch64_neon_umull) {
530     switch (N->getSimpleValueType(0).SimpleTy) {
531     default:
532       llvm_unreachable("Unrecognized SMULL.");
533     case MVT::v4i32:
534       SMULLOpc = AArch64::UMULLv4i16_indexed;
535       break;
536     case MVT::v2i64:
537       SMULLOpc = AArch64::UMULLv2i32_indexed;
538       break;
539     }
540   } else
541     llvm_unreachable("Unrecognized intrinsic.");
542 
543   ReplaceNode(N, CurDAG->getMachineNode(SMULLOpc, dl, N->getValueType(0), Ops));
544   return true;
545 }
546 
547 /// Instructions that accept extend modifiers like UXTW expect the register
548 /// being extended to be a GPR32, but the incoming DAG might be acting on a
549 /// GPR64 (either via SEXT_INREG or AND). Extract the appropriate low bits if
550 /// this is the case.
551 static SDValue narrowIfNeeded(SelectionDAG *CurDAG, SDValue N) {
552   if (N.getValueType() == MVT::i32)
553     return N;
554 
555   SDLoc dl(N);
556   SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
557   MachineSDNode *Node = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
558                                                dl, MVT::i32, N, SubReg);
559   return SDValue(Node, 0);
560 }
561 
562 
563 /// SelectArithExtendedRegister - Select a "extended register" operand.  This
564 /// operand folds in an extend followed by an optional left shift.
565 bool AArch64DAGToDAGISel::SelectArithExtendedRegister(SDValue N, SDValue &Reg,
566                                                       SDValue &Shift) {
567   unsigned ShiftVal = 0;
568   AArch64_AM::ShiftExtendType Ext;
569 
570   if (N.getOpcode() == ISD::SHL) {
571     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
572     if (!CSD)
573       return false;
574     ShiftVal = CSD->getZExtValue();
575     if (ShiftVal > 4)
576       return false;
577 
578     Ext = getExtendTypeForNode(N.getOperand(0));
579     if (Ext == AArch64_AM::InvalidShiftExtend)
580       return false;
581 
582     Reg = N.getOperand(0).getOperand(0);
583   } else {
584     Ext = getExtendTypeForNode(N);
585     if (Ext == AArch64_AM::InvalidShiftExtend)
586       return false;
587 
588     Reg = N.getOperand(0);
589   }
590 
591   // AArch64 mandates that the RHS of the operation must use the smallest
592   // register class that could contain the size being extended from.  Thus,
593   // if we're folding a (sext i8), we need the RHS to be a GPR32, even though
594   // there might not be an actual 32-bit value in the program.  We can
595   // (harmlessly) synthesize one by injected an EXTRACT_SUBREG here.
596   assert(Ext != AArch64_AM::UXTX && Ext != AArch64_AM::SXTX);
597   Reg = narrowIfNeeded(CurDAG, Reg);
598   Shift = CurDAG->getTargetConstant(getArithExtendImm(Ext, ShiftVal), SDLoc(N),
599                                     MVT::i32);
600   return isWorthFolding(N);
601 }
602 
603 /// If there's a use of this ADDlow that's not itself a load/store then we'll
604 /// need to create a real ADD instruction from it anyway and there's no point in
605 /// folding it into the mem op. Theoretically, it shouldn't matter, but there's
606 /// a single pseudo-instruction for an ADRP/ADD pair so over-aggressive folding
607 /// leads to duplicated ADRP instructions.
608 static bool isWorthFoldingADDlow(SDValue N) {
609   for (auto Use : N->uses()) {
610     if (Use->getOpcode() != ISD::LOAD && Use->getOpcode() != ISD::STORE &&
611         Use->getOpcode() != ISD::ATOMIC_LOAD &&
612         Use->getOpcode() != ISD::ATOMIC_STORE)
613       return false;
614 
615     // ldar and stlr have much more restrictive addressing modes (just a
616     // register).
617     if (isStrongerThanMonotonic(cast<MemSDNode>(Use)->getOrdering()))
618       return false;
619   }
620 
621   return true;
622 }
623 
624 /// SelectAddrModeIndexed7S - Select a "register plus scaled signed 7-bit
625 /// immediate" address.  The "Size" argument is the size in bytes of the memory
626 /// reference, which determines the scale.
627 bool AArch64DAGToDAGISel::SelectAddrModeIndexed7S(SDValue N, unsigned Size,
628                                                   SDValue &Base,
629                                                   SDValue &OffImm) {
630   SDLoc dl(N);
631   const DataLayout &DL = CurDAG->getDataLayout();
632   const TargetLowering *TLI = getTargetLowering();
633   if (N.getOpcode() == ISD::FrameIndex) {
634     int FI = cast<FrameIndexSDNode>(N)->getIndex();
635     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
636     OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
637     return true;
638   }
639 
640   // As opposed to the (12-bit) Indexed addressing mode below, the 7-bit signed
641   // selected here doesn't support labels/immediates, only base+offset.
642 
643   if (CurDAG->isBaseWithConstantOffset(N)) {
644     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
645       int64_t RHSC = RHS->getSExtValue();
646       unsigned Scale = Log2_32(Size);
647       if ((RHSC & (Size - 1)) == 0 && RHSC >= -(0x40 << Scale) &&
648           RHSC < (0x40 << Scale)) {
649         Base = N.getOperand(0);
650         if (Base.getOpcode() == ISD::FrameIndex) {
651           int FI = cast<FrameIndexSDNode>(Base)->getIndex();
652           Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
653         }
654         OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
655         return true;
656       }
657     }
658   }
659 
660   // Base only. The address will be materialized into a register before
661   // the memory is accessed.
662   //    add x0, Xbase, #offset
663   //    stp x1, x2, [x0]
664   Base = N;
665   OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
666   return true;
667 }
668 
669 /// SelectAddrModeIndexed - Select a "register plus scaled unsigned 12-bit
670 /// immediate" address.  The "Size" argument is the size in bytes of the memory
671 /// reference, which determines the scale.
672 bool AArch64DAGToDAGISel::SelectAddrModeIndexed(SDValue N, unsigned Size,
673                                               SDValue &Base, SDValue &OffImm) {
674   SDLoc dl(N);
675   const DataLayout &DL = CurDAG->getDataLayout();
676   const TargetLowering *TLI = getTargetLowering();
677   if (N.getOpcode() == ISD::FrameIndex) {
678     int FI = cast<FrameIndexSDNode>(N)->getIndex();
679     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
680     OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
681     return true;
682   }
683 
684   if (N.getOpcode() == AArch64ISD::ADDlow && isWorthFoldingADDlow(N)) {
685     GlobalAddressSDNode *GAN =
686         dyn_cast<GlobalAddressSDNode>(N.getOperand(1).getNode());
687     Base = N.getOperand(0);
688     OffImm = N.getOperand(1);
689     if (!GAN)
690       return true;
691 
692     const GlobalValue *GV = GAN->getGlobal();
693     unsigned Alignment = GV->getAlignment();
694     Type *Ty = GV->getValueType();
695     if (Alignment == 0 && Ty->isSized())
696       Alignment = DL.getABITypeAlignment(Ty);
697 
698     if (Alignment >= Size)
699       return true;
700   }
701 
702   if (CurDAG->isBaseWithConstantOffset(N)) {
703     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
704       int64_t RHSC = (int64_t)RHS->getZExtValue();
705       unsigned Scale = Log2_32(Size);
706       if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
707         Base = N.getOperand(0);
708         if (Base.getOpcode() == ISD::FrameIndex) {
709           int FI = cast<FrameIndexSDNode>(Base)->getIndex();
710           Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
711         }
712         OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
713         return true;
714       }
715     }
716   }
717 
718   // Before falling back to our general case, check if the unscaled
719   // instructions can handle this. If so, that's preferable.
720   if (SelectAddrModeUnscaled(N, Size, Base, OffImm))
721     return false;
722 
723   // Base only. The address will be materialized into a register before
724   // the memory is accessed.
725   //    add x0, Xbase, #offset
726   //    ldr x0, [x0]
727   Base = N;
728   OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
729   return true;
730 }
731 
732 /// SelectAddrModeUnscaled - Select a "register plus unscaled signed 9-bit
733 /// immediate" address.  This should only match when there is an offset that
734 /// is not valid for a scaled immediate addressing mode.  The "Size" argument
735 /// is the size in bytes of the memory reference, which is needed here to know
736 /// what is valid for a scaled immediate.
737 bool AArch64DAGToDAGISel::SelectAddrModeUnscaled(SDValue N, unsigned Size,
738                                                  SDValue &Base,
739                                                  SDValue &OffImm) {
740   if (!CurDAG->isBaseWithConstantOffset(N))
741     return false;
742   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
743     int64_t RHSC = RHS->getSExtValue();
744     // If the offset is valid as a scaled immediate, don't match here.
745     if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 &&
746         RHSC < (0x1000 << Log2_32(Size)))
747       return false;
748     if (RHSC >= -256 && RHSC < 256) {
749       Base = N.getOperand(0);
750       if (Base.getOpcode() == ISD::FrameIndex) {
751         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
752         const TargetLowering *TLI = getTargetLowering();
753         Base = CurDAG->getTargetFrameIndex(
754             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
755       }
756       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i64);
757       return true;
758     }
759   }
760   return false;
761 }
762 
763 static SDValue Widen(SelectionDAG *CurDAG, SDValue N) {
764   SDLoc dl(N);
765   SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
766   SDValue ImpDef = SDValue(
767       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, MVT::i64), 0);
768   MachineSDNode *Node = CurDAG->getMachineNode(
769       TargetOpcode::INSERT_SUBREG, dl, MVT::i64, ImpDef, N, SubReg);
770   return SDValue(Node, 0);
771 }
772 
773 /// \brief Check if the given SHL node (\p N), can be used to form an
774 /// extended register for an addressing mode.
775 bool AArch64DAGToDAGISel::SelectExtendedSHL(SDValue N, unsigned Size,
776                                             bool WantExtend, SDValue &Offset,
777                                             SDValue &SignExtend) {
778   assert(N.getOpcode() == ISD::SHL && "Invalid opcode.");
779   ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
780   if (!CSD || (CSD->getZExtValue() & 0x7) != CSD->getZExtValue())
781     return false;
782 
783   SDLoc dl(N);
784   if (WantExtend) {
785     AArch64_AM::ShiftExtendType Ext =
786         getExtendTypeForNode(N.getOperand(0), true);
787     if (Ext == AArch64_AM::InvalidShiftExtend)
788       return false;
789 
790     Offset = narrowIfNeeded(CurDAG, N.getOperand(0).getOperand(0));
791     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
792                                            MVT::i32);
793   } else {
794     Offset = N.getOperand(0);
795     SignExtend = CurDAG->getTargetConstant(0, dl, MVT::i32);
796   }
797 
798   unsigned LegalShiftVal = Log2_32(Size);
799   unsigned ShiftVal = CSD->getZExtValue();
800 
801   if (ShiftVal != 0 && ShiftVal != LegalShiftVal)
802     return false;
803 
804   return isWorthFolding(N);
805 }
806 
807 bool AArch64DAGToDAGISel::SelectAddrModeWRO(SDValue N, unsigned Size,
808                                             SDValue &Base, SDValue &Offset,
809                                             SDValue &SignExtend,
810                                             SDValue &DoShift) {
811   if (N.getOpcode() != ISD::ADD)
812     return false;
813   SDValue LHS = N.getOperand(0);
814   SDValue RHS = N.getOperand(1);
815   SDLoc dl(N);
816 
817   // We don't want to match immediate adds here, because they are better lowered
818   // to the register-immediate addressing modes.
819   if (isa<ConstantSDNode>(LHS) || isa<ConstantSDNode>(RHS))
820     return false;
821 
822   // Check if this particular node is reused in any non-memory related
823   // operation.  If yes, do not try to fold this node into the address
824   // computation, since the computation will be kept.
825   const SDNode *Node = N.getNode();
826   for (SDNode *UI : Node->uses()) {
827     if (!isa<MemSDNode>(*UI))
828       return false;
829   }
830 
831   // Remember if it is worth folding N when it produces extended register.
832   bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
833 
834   // Try to match a shifted extend on the RHS.
835   if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
836       SelectExtendedSHL(RHS, Size, true, Offset, SignExtend)) {
837     Base = LHS;
838     DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
839     return true;
840   }
841 
842   // Try to match a shifted extend on the LHS.
843   if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
844       SelectExtendedSHL(LHS, Size, true, Offset, SignExtend)) {
845     Base = RHS;
846     DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
847     return true;
848   }
849 
850   // There was no shift, whatever else we find.
851   DoShift = CurDAG->getTargetConstant(false, dl, MVT::i32);
852 
853   AArch64_AM::ShiftExtendType Ext = AArch64_AM::InvalidShiftExtend;
854   // Try to match an unshifted extend on the LHS.
855   if (IsExtendedRegisterWorthFolding &&
856       (Ext = getExtendTypeForNode(LHS, true)) !=
857           AArch64_AM::InvalidShiftExtend) {
858     Base = RHS;
859     Offset = narrowIfNeeded(CurDAG, LHS.getOperand(0));
860     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
861                                            MVT::i32);
862     if (isWorthFolding(LHS))
863       return true;
864   }
865 
866   // Try to match an unshifted extend on the RHS.
867   if (IsExtendedRegisterWorthFolding &&
868       (Ext = getExtendTypeForNode(RHS, true)) !=
869           AArch64_AM::InvalidShiftExtend) {
870     Base = LHS;
871     Offset = narrowIfNeeded(CurDAG, RHS.getOperand(0));
872     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
873                                            MVT::i32);
874     if (isWorthFolding(RHS))
875       return true;
876   }
877 
878   return false;
879 }
880 
881 // Check if the given immediate is preferred by ADD. If an immediate can be
882 // encoded in an ADD, or it can be encoded in an "ADD LSL #12" and can not be
883 // encoded by one MOVZ, return true.
884 static bool isPreferredADD(int64_t ImmOff) {
885   // Constant in [0x0, 0xfff] can be encoded in ADD.
886   if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
887     return true;
888   // Check if it can be encoded in an "ADD LSL #12".
889   if ((ImmOff & 0xffffffffff000fffLL) == 0x0LL)
890     // As a single MOVZ is faster than a "ADD of LSL #12", ignore such constant.
891     return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
892            (ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
893   return false;
894 }
895 
896 bool AArch64DAGToDAGISel::SelectAddrModeXRO(SDValue N, unsigned Size,
897                                             SDValue &Base, SDValue &Offset,
898                                             SDValue &SignExtend,
899                                             SDValue &DoShift) {
900   if (N.getOpcode() != ISD::ADD)
901     return false;
902   SDValue LHS = N.getOperand(0);
903   SDValue RHS = N.getOperand(1);
904   SDLoc DL(N);
905 
906   // Check if this particular node is reused in any non-memory related
907   // operation.  If yes, do not try to fold this node into the address
908   // computation, since the computation will be kept.
909   const SDNode *Node = N.getNode();
910   for (SDNode *UI : Node->uses()) {
911     if (!isa<MemSDNode>(*UI))
912       return false;
913   }
914 
915   // Watch out if RHS is a wide immediate, it can not be selected into
916   // [BaseReg+Imm] addressing mode. Also it may not be able to be encoded into
917   // ADD/SUB. Instead it will use [BaseReg + 0] address mode and generate
918   // instructions like:
919   //     MOV  X0, WideImmediate
920   //     ADD  X1, BaseReg, X0
921   //     LDR  X2, [X1, 0]
922   // For such situation, using [BaseReg, XReg] addressing mode can save one
923   // ADD/SUB:
924   //     MOV  X0, WideImmediate
925   //     LDR  X2, [BaseReg, X0]
926   if (isa<ConstantSDNode>(RHS)) {
927     int64_t ImmOff = (int64_t)cast<ConstantSDNode>(RHS)->getZExtValue();
928     unsigned Scale = Log2_32(Size);
929     // Skip the immediate can be selected by load/store addressing mode.
930     // Also skip the immediate can be encoded by a single ADD (SUB is also
931     // checked by using -ImmOff).
932     if ((ImmOff % Size == 0 && ImmOff >= 0 && ImmOff < (0x1000 << Scale)) ||
933         isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
934       return false;
935 
936     SDValue Ops[] = { RHS };
937     SDNode *MOVI =
938         CurDAG->getMachineNode(AArch64::MOVi64imm, DL, MVT::i64, Ops);
939     SDValue MOVIV = SDValue(MOVI, 0);
940     // This ADD of two X register will be selected into [Reg+Reg] mode.
941     N = CurDAG->getNode(ISD::ADD, DL, MVT::i64, LHS, MOVIV);
942   }
943 
944   // Remember if it is worth folding N when it produces extended register.
945   bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
946 
947   // Try to match a shifted extend on the RHS.
948   if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
949       SelectExtendedSHL(RHS, Size, false, Offset, SignExtend)) {
950     Base = LHS;
951     DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
952     return true;
953   }
954 
955   // Try to match a shifted extend on the LHS.
956   if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
957       SelectExtendedSHL(LHS, Size, false, Offset, SignExtend)) {
958     Base = RHS;
959     DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
960     return true;
961   }
962 
963   // Match any non-shifted, non-extend, non-immediate add expression.
964   Base = LHS;
965   Offset = RHS;
966   SignExtend = CurDAG->getTargetConstant(false, DL, MVT::i32);
967   DoShift = CurDAG->getTargetConstant(false, DL, MVT::i32);
968   // Reg1 + Reg2 is free: no check needed.
969   return true;
970 }
971 
972 SDValue AArch64DAGToDAGISel::createDTuple(ArrayRef<SDValue> Regs) {
973   static const unsigned RegClassIDs[] = {
974       AArch64::DDRegClassID, AArch64::DDDRegClassID, AArch64::DDDDRegClassID};
975   static const unsigned SubRegs[] = {AArch64::dsub0, AArch64::dsub1,
976                                      AArch64::dsub2, AArch64::dsub3};
977 
978   return createTuple(Regs, RegClassIDs, SubRegs);
979 }
980 
981 SDValue AArch64DAGToDAGISel::createQTuple(ArrayRef<SDValue> Regs) {
982   static const unsigned RegClassIDs[] = {
983       AArch64::QQRegClassID, AArch64::QQQRegClassID, AArch64::QQQQRegClassID};
984   static const unsigned SubRegs[] = {AArch64::qsub0, AArch64::qsub1,
985                                      AArch64::qsub2, AArch64::qsub3};
986 
987   return createTuple(Regs, RegClassIDs, SubRegs);
988 }
989 
990 SDValue AArch64DAGToDAGISel::createTuple(ArrayRef<SDValue> Regs,
991                                          const unsigned RegClassIDs[],
992                                          const unsigned SubRegs[]) {
993   // There's no special register-class for a vector-list of 1 element: it's just
994   // a vector.
995   if (Regs.size() == 1)
996     return Regs[0];
997 
998   assert(Regs.size() >= 2 && Regs.size() <= 4);
999 
1000   SDLoc DL(Regs[0]);
1001 
1002   SmallVector<SDValue, 4> Ops;
1003 
1004   // First operand of REG_SEQUENCE is the desired RegClass.
1005   Ops.push_back(
1006       CurDAG->getTargetConstant(RegClassIDs[Regs.size() - 2], DL, MVT::i32));
1007 
1008   // Then we get pairs of source & subregister-position for the components.
1009   for (unsigned i = 0; i < Regs.size(); ++i) {
1010     Ops.push_back(Regs[i]);
1011     Ops.push_back(CurDAG->getTargetConstant(SubRegs[i], DL, MVT::i32));
1012   }
1013 
1014   SDNode *N =
1015       CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, MVT::Untyped, Ops);
1016   return SDValue(N, 0);
1017 }
1018 
1019 void AArch64DAGToDAGISel::SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc,
1020                                       bool isExt) {
1021   SDLoc dl(N);
1022   EVT VT = N->getValueType(0);
1023 
1024   unsigned ExtOff = isExt;
1025 
1026   // Form a REG_SEQUENCE to force register allocation.
1027   unsigned Vec0Off = ExtOff + 1;
1028   SmallVector<SDValue, 4> Regs(N->op_begin() + Vec0Off,
1029                                N->op_begin() + Vec0Off + NumVecs);
1030   SDValue RegSeq = createQTuple(Regs);
1031 
1032   SmallVector<SDValue, 6> Ops;
1033   if (isExt)
1034     Ops.push_back(N->getOperand(1));
1035   Ops.push_back(RegSeq);
1036   Ops.push_back(N->getOperand(NumVecs + ExtOff + 1));
1037   ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
1038 }
1039 
1040 bool AArch64DAGToDAGISel::tryIndexedLoad(SDNode *N) {
1041   LoadSDNode *LD = cast<LoadSDNode>(N);
1042   if (LD->isUnindexed())
1043     return false;
1044   EVT VT = LD->getMemoryVT();
1045   EVT DstVT = N->getValueType(0);
1046   ISD::MemIndexedMode AM = LD->getAddressingMode();
1047   bool IsPre = AM == ISD::PRE_INC || AM == ISD::PRE_DEC;
1048 
1049   // We're not doing validity checking here. That was done when checking
1050   // if we should mark the load as indexed or not. We're just selecting
1051   // the right instruction.
1052   unsigned Opcode = 0;
1053 
1054   ISD::LoadExtType ExtType = LD->getExtensionType();
1055   bool InsertTo64 = false;
1056   if (VT == MVT::i64)
1057     Opcode = IsPre ? AArch64::LDRXpre : AArch64::LDRXpost;
1058   else if (VT == MVT::i32) {
1059     if (ExtType == ISD::NON_EXTLOAD)
1060       Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
1061     else if (ExtType == ISD::SEXTLOAD)
1062       Opcode = IsPre ? AArch64::LDRSWpre : AArch64::LDRSWpost;
1063     else {
1064       Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
1065       InsertTo64 = true;
1066       // The result of the load is only i32. It's the subreg_to_reg that makes
1067       // it into an i64.
1068       DstVT = MVT::i32;
1069     }
1070   } else if (VT == MVT::i16) {
1071     if (ExtType == ISD::SEXTLOAD) {
1072       if (DstVT == MVT::i64)
1073         Opcode = IsPre ? AArch64::LDRSHXpre : AArch64::LDRSHXpost;
1074       else
1075         Opcode = IsPre ? AArch64::LDRSHWpre : AArch64::LDRSHWpost;
1076     } else {
1077       Opcode = IsPre ? AArch64::LDRHHpre : AArch64::LDRHHpost;
1078       InsertTo64 = DstVT == MVT::i64;
1079       // The result of the load is only i32. It's the subreg_to_reg that makes
1080       // it into an i64.
1081       DstVT = MVT::i32;
1082     }
1083   } else if (VT == MVT::i8) {
1084     if (ExtType == ISD::SEXTLOAD) {
1085       if (DstVT == MVT::i64)
1086         Opcode = IsPre ? AArch64::LDRSBXpre : AArch64::LDRSBXpost;
1087       else
1088         Opcode = IsPre ? AArch64::LDRSBWpre : AArch64::LDRSBWpost;
1089     } else {
1090       Opcode = IsPre ? AArch64::LDRBBpre : AArch64::LDRBBpost;
1091       InsertTo64 = DstVT == MVT::i64;
1092       // The result of the load is only i32. It's the subreg_to_reg that makes
1093       // it into an i64.
1094       DstVT = MVT::i32;
1095     }
1096   } else if (VT == MVT::f16) {
1097     Opcode = IsPre ? AArch64::LDRHpre : AArch64::LDRHpost;
1098   } else if (VT == MVT::f32) {
1099     Opcode = IsPre ? AArch64::LDRSpre : AArch64::LDRSpost;
1100   } else if (VT == MVT::f64 || VT.is64BitVector()) {
1101     Opcode = IsPre ? AArch64::LDRDpre : AArch64::LDRDpost;
1102   } else if (VT.is128BitVector()) {
1103     Opcode = IsPre ? AArch64::LDRQpre : AArch64::LDRQpost;
1104   } else
1105     return false;
1106   SDValue Chain = LD->getChain();
1107   SDValue Base = LD->getBasePtr();
1108   ConstantSDNode *OffsetOp = cast<ConstantSDNode>(LD->getOffset());
1109   int OffsetVal = (int)OffsetOp->getZExtValue();
1110   SDLoc dl(N);
1111   SDValue Offset = CurDAG->getTargetConstant(OffsetVal, dl, MVT::i64);
1112   SDValue Ops[] = { Base, Offset, Chain };
1113   SDNode *Res = CurDAG->getMachineNode(Opcode, dl, MVT::i64, DstVT,
1114                                        MVT::Other, Ops);
1115   // Either way, we're replacing the node, so tell the caller that.
1116   SDValue LoadedVal = SDValue(Res, 1);
1117   if (InsertTo64) {
1118     SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
1119     LoadedVal =
1120         SDValue(CurDAG->getMachineNode(
1121                     AArch64::SUBREG_TO_REG, dl, MVT::i64,
1122                     CurDAG->getTargetConstant(0, dl, MVT::i64), LoadedVal,
1123                     SubReg),
1124                 0);
1125   }
1126 
1127   ReplaceUses(SDValue(N, 0), LoadedVal);
1128   ReplaceUses(SDValue(N, 1), SDValue(Res, 0));
1129   ReplaceUses(SDValue(N, 2), SDValue(Res, 2));
1130   CurDAG->RemoveDeadNode(N);
1131   return true;
1132 }
1133 
1134 void AArch64DAGToDAGISel::SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
1135                                      unsigned SubRegIdx) {
1136   SDLoc dl(N);
1137   EVT VT = N->getValueType(0);
1138   SDValue Chain = N->getOperand(0);
1139 
1140   SDValue Ops[] = {N->getOperand(2), // Mem operand;
1141                    Chain};
1142 
1143   const EVT ResTys[] = {MVT::Untyped, MVT::Other};
1144 
1145   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1146   SDValue SuperReg = SDValue(Ld, 0);
1147   for (unsigned i = 0; i < NumVecs; ++i)
1148     ReplaceUses(SDValue(N, i),
1149         CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
1150 
1151   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
1152   CurDAG->RemoveDeadNode(N);
1153 }
1154 
1155 void AArch64DAGToDAGISel::SelectPostLoad(SDNode *N, unsigned NumVecs,
1156                                          unsigned Opc, unsigned SubRegIdx) {
1157   SDLoc dl(N);
1158   EVT VT = N->getValueType(0);
1159   SDValue Chain = N->getOperand(0);
1160 
1161   SDValue Ops[] = {N->getOperand(1), // Mem operand
1162                    N->getOperand(2), // Incremental
1163                    Chain};
1164 
1165   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1166                         MVT::Untyped, MVT::Other};
1167 
1168   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1169 
1170   // Update uses of write back register
1171   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
1172 
1173   // Update uses of vector list
1174   SDValue SuperReg = SDValue(Ld, 1);
1175   if (NumVecs == 1)
1176     ReplaceUses(SDValue(N, 0), SuperReg);
1177   else
1178     for (unsigned i = 0; i < NumVecs; ++i)
1179       ReplaceUses(SDValue(N, i),
1180           CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
1181 
1182   // Update the chain
1183   ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
1184   CurDAG->RemoveDeadNode(N);
1185 }
1186 
1187 void AArch64DAGToDAGISel::SelectStore(SDNode *N, unsigned NumVecs,
1188                                       unsigned Opc) {
1189   SDLoc dl(N);
1190   EVT VT = N->getOperand(2)->getValueType(0);
1191 
1192   // Form a REG_SEQUENCE to force register allocation.
1193   bool Is128Bit = VT.getSizeInBits() == 128;
1194   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1195   SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
1196 
1197   SDValue Ops[] = {RegSeq, N->getOperand(NumVecs + 2), N->getOperand(0)};
1198   SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
1199 
1200   ReplaceNode(N, St);
1201 }
1202 
1203 void AArch64DAGToDAGISel::SelectPostStore(SDNode *N, unsigned NumVecs,
1204                                           unsigned Opc) {
1205   SDLoc dl(N);
1206   EVT VT = N->getOperand(2)->getValueType(0);
1207   const EVT ResTys[] = {MVT::i64,    // Type of the write back register
1208                         MVT::Other}; // Type for the Chain
1209 
1210   // Form a REG_SEQUENCE to force register allocation.
1211   bool Is128Bit = VT.getSizeInBits() == 128;
1212   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1213   SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
1214 
1215   SDValue Ops[] = {RegSeq,
1216                    N->getOperand(NumVecs + 1), // base register
1217                    N->getOperand(NumVecs + 2), // Incremental
1218                    N->getOperand(0)};          // Chain
1219   SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1220 
1221   ReplaceNode(N, St);
1222 }
1223 
1224 namespace {
1225 /// WidenVector - Given a value in the V64 register class, produce the
1226 /// equivalent value in the V128 register class.
1227 class WidenVector {
1228   SelectionDAG &DAG;
1229 
1230 public:
1231   WidenVector(SelectionDAG &DAG) : DAG(DAG) {}
1232 
1233   SDValue operator()(SDValue V64Reg) {
1234     EVT VT = V64Reg.getValueType();
1235     unsigned NarrowSize = VT.getVectorNumElements();
1236     MVT EltTy = VT.getVectorElementType().getSimpleVT();
1237     MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
1238     SDLoc DL(V64Reg);
1239 
1240     SDValue Undef =
1241         SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, WideTy), 0);
1242     return DAG.getTargetInsertSubreg(AArch64::dsub, DL, WideTy, Undef, V64Reg);
1243   }
1244 };
1245 } // namespace
1246 
1247 /// NarrowVector - Given a value in the V128 register class, produce the
1248 /// equivalent value in the V64 register class.
1249 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
1250   EVT VT = V128Reg.getValueType();
1251   unsigned WideSize = VT.getVectorNumElements();
1252   MVT EltTy = VT.getVectorElementType().getSimpleVT();
1253   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
1254 
1255   return DAG.getTargetExtractSubreg(AArch64::dsub, SDLoc(V128Reg), NarrowTy,
1256                                     V128Reg);
1257 }
1258 
1259 void AArch64DAGToDAGISel::SelectLoadLane(SDNode *N, unsigned NumVecs,
1260                                          unsigned Opc) {
1261   SDLoc dl(N);
1262   EVT VT = N->getValueType(0);
1263   bool Narrow = VT.getSizeInBits() == 64;
1264 
1265   // Form a REG_SEQUENCE to force register allocation.
1266   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1267 
1268   if (Narrow)
1269     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1270                    WidenVector(*CurDAG));
1271 
1272   SDValue RegSeq = createQTuple(Regs);
1273 
1274   const EVT ResTys[] = {MVT::Untyped, MVT::Other};
1275 
1276   unsigned LaneNo =
1277       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1278 
1279   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1280                    N->getOperand(NumVecs + 3), N->getOperand(0)};
1281   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1282   SDValue SuperReg = SDValue(Ld, 0);
1283 
1284   EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
1285   static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
1286                                     AArch64::qsub2, AArch64::qsub3 };
1287   for (unsigned i = 0; i < NumVecs; ++i) {
1288     SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT, SuperReg);
1289     if (Narrow)
1290       NV = NarrowVector(NV, *CurDAG);
1291     ReplaceUses(SDValue(N, i), NV);
1292   }
1293 
1294   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
1295   CurDAG->RemoveDeadNode(N);
1296 }
1297 
1298 void AArch64DAGToDAGISel::SelectPostLoadLane(SDNode *N, unsigned NumVecs,
1299                                              unsigned Opc) {
1300   SDLoc dl(N);
1301   EVT VT = N->getValueType(0);
1302   bool Narrow = VT.getSizeInBits() == 64;
1303 
1304   // Form a REG_SEQUENCE to force register allocation.
1305   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1306 
1307   if (Narrow)
1308     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1309                    WidenVector(*CurDAG));
1310 
1311   SDValue RegSeq = createQTuple(Regs);
1312 
1313   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1314                         RegSeq->getValueType(0), MVT::Other};
1315 
1316   unsigned LaneNo =
1317       cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
1318 
1319   SDValue Ops[] = {RegSeq,
1320                    CurDAG->getTargetConstant(LaneNo, dl,
1321                                              MVT::i64),         // Lane Number
1322                    N->getOperand(NumVecs + 2),                  // Base register
1323                    N->getOperand(NumVecs + 3),                  // Incremental
1324                    N->getOperand(0)};
1325   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1326 
1327   // Update uses of the write back register
1328   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
1329 
1330   // Update uses of the vector list
1331   SDValue SuperReg = SDValue(Ld, 1);
1332   if (NumVecs == 1) {
1333     ReplaceUses(SDValue(N, 0),
1334                 Narrow ? NarrowVector(SuperReg, *CurDAG) : SuperReg);
1335   } else {
1336     EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
1337     static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
1338                                       AArch64::qsub2, AArch64::qsub3 };
1339     for (unsigned i = 0; i < NumVecs; ++i) {
1340       SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT,
1341                                                   SuperReg);
1342       if (Narrow)
1343         NV = NarrowVector(NV, *CurDAG);
1344       ReplaceUses(SDValue(N, i), NV);
1345     }
1346   }
1347 
1348   // Update the Chain
1349   ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
1350   CurDAG->RemoveDeadNode(N);
1351 }
1352 
1353 void AArch64DAGToDAGISel::SelectStoreLane(SDNode *N, unsigned NumVecs,
1354                                           unsigned Opc) {
1355   SDLoc dl(N);
1356   EVT VT = N->getOperand(2)->getValueType(0);
1357   bool Narrow = VT.getSizeInBits() == 64;
1358 
1359   // Form a REG_SEQUENCE to force register allocation.
1360   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1361 
1362   if (Narrow)
1363     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1364                    WidenVector(*CurDAG));
1365 
1366   SDValue RegSeq = createQTuple(Regs);
1367 
1368   unsigned LaneNo =
1369       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1370 
1371   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1372                    N->getOperand(NumVecs + 3), N->getOperand(0)};
1373   SDNode *St = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
1374 
1375   // Transfer memoperands.
1376   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1377   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1378   cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
1379 
1380   ReplaceNode(N, St);
1381 }
1382 
1383 void AArch64DAGToDAGISel::SelectPostStoreLane(SDNode *N, unsigned NumVecs,
1384                                               unsigned Opc) {
1385   SDLoc dl(N);
1386   EVT VT = N->getOperand(2)->getValueType(0);
1387   bool Narrow = VT.getSizeInBits() == 64;
1388 
1389   // Form a REG_SEQUENCE to force register allocation.
1390   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1391 
1392   if (Narrow)
1393     std::transform(Regs.begin(), Regs.end(), Regs.begin(),
1394                    WidenVector(*CurDAG));
1395 
1396   SDValue RegSeq = createQTuple(Regs);
1397 
1398   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1399                         MVT::Other};
1400 
1401   unsigned LaneNo =
1402       cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
1403 
1404   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1405                    N->getOperand(NumVecs + 2), // Base Register
1406                    N->getOperand(NumVecs + 3), // Incremental
1407                    N->getOperand(0)};
1408   SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1409 
1410   // Transfer memoperands.
1411   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1412   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1413   cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
1414 
1415   ReplaceNode(N, St);
1416 }
1417 
1418 static bool isBitfieldExtractOpFromAnd(SelectionDAG *CurDAG, SDNode *N,
1419                                        unsigned &Opc, SDValue &Opd0,
1420                                        unsigned &LSB, unsigned &MSB,
1421                                        unsigned NumberOfIgnoredLowBits,
1422                                        bool BiggerPattern) {
1423   assert(N->getOpcode() == ISD::AND &&
1424          "N must be a AND operation to call this function");
1425 
1426   EVT VT = N->getValueType(0);
1427 
1428   // Here we can test the type of VT and return false when the type does not
1429   // match, but since it is done prior to that call in the current context
1430   // we turned that into an assert to avoid redundant code.
1431   assert((VT == MVT::i32 || VT == MVT::i64) &&
1432          "Type checking must have been done before calling this function");
1433 
1434   // FIXME: simplify-demanded-bits in DAGCombine will probably have
1435   // changed the AND node to a 32-bit mask operation. We'll have to
1436   // undo that as part of the transform here if we want to catch all
1437   // the opportunities.
1438   // Currently the NumberOfIgnoredLowBits argument helps to recover
1439   // form these situations when matching bigger pattern (bitfield insert).
1440 
1441   // For unsigned extracts, check for a shift right and mask
1442   uint64_t AndImm = 0;
1443   if (!isOpcWithIntImmediate(N, ISD::AND, AndImm))
1444     return false;
1445 
1446   const SDNode *Op0 = N->getOperand(0).getNode();
1447 
1448   // Because of simplify-demanded-bits in DAGCombine, the mask may have been
1449   // simplified. Try to undo that
1450   AndImm |= (1 << NumberOfIgnoredLowBits) - 1;
1451 
1452   // The immediate is a mask of the low bits iff imm & (imm+1) == 0
1453   if (AndImm & (AndImm + 1))
1454     return false;
1455 
1456   bool ClampMSB = false;
1457   uint64_t SrlImm = 0;
1458   // Handle the SRL + ANY_EXTEND case.
1459   if (VT == MVT::i64 && Op0->getOpcode() == ISD::ANY_EXTEND &&
1460       isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL, SrlImm)) {
1461     // Extend the incoming operand of the SRL to 64-bit.
1462     Opd0 = Widen(CurDAG, Op0->getOperand(0).getOperand(0));
1463     // Make sure to clamp the MSB so that we preserve the semantics of the
1464     // original operations.
1465     ClampMSB = true;
1466   } else if (VT == MVT::i32 && Op0->getOpcode() == ISD::TRUNCATE &&
1467              isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL,
1468                                    SrlImm)) {
1469     // If the shift result was truncated, we can still combine them.
1470     Opd0 = Op0->getOperand(0).getOperand(0);
1471 
1472     // Use the type of SRL node.
1473     VT = Opd0->getValueType(0);
1474   } else if (isOpcWithIntImmediate(Op0, ISD::SRL, SrlImm)) {
1475     Opd0 = Op0->getOperand(0);
1476   } else if (BiggerPattern) {
1477     // Let's pretend a 0 shift right has been performed.
1478     // The resulting code will be at least as good as the original one
1479     // plus it may expose more opportunities for bitfield insert pattern.
1480     // FIXME: Currently we limit this to the bigger pattern, because
1481     // some optimizations expect AND and not UBFM.
1482     Opd0 = N->getOperand(0);
1483   } else
1484     return false;
1485 
1486   // Bail out on large immediates. This happens when no proper
1487   // combining/constant folding was performed.
1488   if (!BiggerPattern && (SrlImm <= 0 || SrlImm >= VT.getSizeInBits())) {
1489     DEBUG((dbgs() << N
1490            << ": Found large shift immediate, this should not happen\n"));
1491     return false;
1492   }
1493 
1494   LSB = SrlImm;
1495   MSB = SrlImm + (VT == MVT::i32 ? countTrailingOnes<uint32_t>(AndImm)
1496                                  : countTrailingOnes<uint64_t>(AndImm)) -
1497         1;
1498   if (ClampMSB)
1499     // Since we're moving the extend before the right shift operation, we need
1500     // to clamp the MSB to make sure we don't shift in undefined bits instead of
1501     // the zeros which would get shifted in with the original right shift
1502     // operation.
1503     MSB = MSB > 31 ? 31 : MSB;
1504 
1505   Opc = VT == MVT::i32 ? AArch64::UBFMWri : AArch64::UBFMXri;
1506   return true;
1507 }
1508 
1509 static bool isBitfieldExtractOpFromSExtInReg(SDNode *N, unsigned &Opc,
1510                                              SDValue &Opd0, unsigned &Immr,
1511                                              unsigned &Imms) {
1512   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
1513 
1514   EVT VT = N->getValueType(0);
1515   unsigned BitWidth = VT.getSizeInBits();
1516   assert((VT == MVT::i32 || VT == MVT::i64) &&
1517          "Type checking must have been done before calling this function");
1518 
1519   SDValue Op = N->getOperand(0);
1520   if (Op->getOpcode() == ISD::TRUNCATE) {
1521     Op = Op->getOperand(0);
1522     VT = Op->getValueType(0);
1523     BitWidth = VT.getSizeInBits();
1524   }
1525 
1526   uint64_t ShiftImm;
1527   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRL, ShiftImm) &&
1528       !isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
1529     return false;
1530 
1531   unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
1532   if (ShiftImm + Width > BitWidth)
1533     return false;
1534 
1535   Opc = (VT == MVT::i32) ? AArch64::SBFMWri : AArch64::SBFMXri;
1536   Opd0 = Op.getOperand(0);
1537   Immr = ShiftImm;
1538   Imms = ShiftImm + Width - 1;
1539   return true;
1540 }
1541 
1542 static bool isSeveralBitsExtractOpFromShr(SDNode *N, unsigned &Opc,
1543                                           SDValue &Opd0, unsigned &LSB,
1544                                           unsigned &MSB) {
1545   // We are looking for the following pattern which basically extracts several
1546   // continuous bits from the source value and places it from the LSB of the
1547   // destination value, all other bits of the destination value or set to zero:
1548   //
1549   // Value2 = AND Value, MaskImm
1550   // SRL Value2, ShiftImm
1551   //
1552   // with MaskImm >> ShiftImm to search for the bit width.
1553   //
1554   // This gets selected into a single UBFM:
1555   //
1556   // UBFM Value, ShiftImm, BitWide + SrlImm -1
1557   //
1558 
1559   if (N->getOpcode() != ISD::SRL)
1560     return false;
1561 
1562   uint64_t AndMask = 0;
1563   if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, AndMask))
1564     return false;
1565 
1566   Opd0 = N->getOperand(0).getOperand(0);
1567 
1568   uint64_t SrlImm = 0;
1569   if (!isIntImmediate(N->getOperand(1), SrlImm))
1570     return false;
1571 
1572   // Check whether we really have several bits extract here.
1573   unsigned BitWide = 64 - countLeadingOnes(~(AndMask >> SrlImm));
1574   if (BitWide && isMask_64(AndMask >> SrlImm)) {
1575     if (N->getValueType(0) == MVT::i32)
1576       Opc = AArch64::UBFMWri;
1577     else
1578       Opc = AArch64::UBFMXri;
1579 
1580     LSB = SrlImm;
1581     MSB = BitWide + SrlImm - 1;
1582     return true;
1583   }
1584 
1585   return false;
1586 }
1587 
1588 static bool isBitfieldExtractOpFromShr(SDNode *N, unsigned &Opc, SDValue &Opd0,
1589                                        unsigned &Immr, unsigned &Imms,
1590                                        bool BiggerPattern) {
1591   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
1592          "N must be a SHR/SRA operation to call this function");
1593 
1594   EVT VT = N->getValueType(0);
1595 
1596   // Here we can test the type of VT and return false when the type does not
1597   // match, but since it is done prior to that call in the current context
1598   // we turned that into an assert to avoid redundant code.
1599   assert((VT == MVT::i32 || VT == MVT::i64) &&
1600          "Type checking must have been done before calling this function");
1601 
1602   // Check for AND + SRL doing several bits extract.
1603   if (isSeveralBitsExtractOpFromShr(N, Opc, Opd0, Immr, Imms))
1604     return true;
1605 
1606   // We're looking for a shift of a shift.
1607   uint64_t ShlImm = 0;
1608   uint64_t TruncBits = 0;
1609   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, ShlImm)) {
1610     Opd0 = N->getOperand(0).getOperand(0);
1611   } else if (VT == MVT::i32 && N->getOpcode() == ISD::SRL &&
1612              N->getOperand(0).getNode()->getOpcode() == ISD::TRUNCATE) {
1613     // We are looking for a shift of truncate. Truncate from i64 to i32 could
1614     // be considered as setting high 32 bits as zero. Our strategy here is to
1615     // always generate 64bit UBFM. This consistency will help the CSE pass
1616     // later find more redundancy.
1617     Opd0 = N->getOperand(0).getOperand(0);
1618     TruncBits = Opd0->getValueType(0).getSizeInBits() - VT.getSizeInBits();
1619     VT = Opd0->getValueType(0);
1620     assert(VT == MVT::i64 && "the promoted type should be i64");
1621   } else if (BiggerPattern) {
1622     // Let's pretend a 0 shift left has been performed.
1623     // FIXME: Currently we limit this to the bigger pattern case,
1624     // because some optimizations expect AND and not UBFM
1625     Opd0 = N->getOperand(0);
1626   } else
1627     return false;
1628 
1629   // Missing combines/constant folding may have left us with strange
1630   // constants.
1631   if (ShlImm >= VT.getSizeInBits()) {
1632     DEBUG((dbgs() << N
1633            << ": Found large shift immediate, this should not happen\n"));
1634     return false;
1635   }
1636 
1637   uint64_t SrlImm = 0;
1638   if (!isIntImmediate(N->getOperand(1), SrlImm))
1639     return false;
1640 
1641   assert(SrlImm > 0 && SrlImm < VT.getSizeInBits() &&
1642          "bad amount in shift node!");
1643   int immr = SrlImm - ShlImm;
1644   Immr = immr < 0 ? immr + VT.getSizeInBits() : immr;
1645   Imms = VT.getSizeInBits() - ShlImm - TruncBits - 1;
1646   // SRA requires a signed extraction
1647   if (VT == MVT::i32)
1648     Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMWri : AArch64::UBFMWri;
1649   else
1650     Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMXri : AArch64::UBFMXri;
1651   return true;
1652 }
1653 
1654 bool AArch64DAGToDAGISel::tryBitfieldExtractOpFromSExt(SDNode *N) {
1655   assert(N->getOpcode() == ISD::SIGN_EXTEND);
1656 
1657   EVT VT = N->getValueType(0);
1658   EVT NarrowVT = N->getOperand(0)->getValueType(0);
1659   if (VT != MVT::i64 || NarrowVT != MVT::i32)
1660     return false;
1661 
1662   uint64_t ShiftImm;
1663   SDValue Op = N->getOperand(0);
1664   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
1665     return false;
1666 
1667   SDLoc dl(N);
1668   // Extend the incoming operand of the shift to 64-bits.
1669   SDValue Opd0 = Widen(CurDAG, Op.getOperand(0));
1670   unsigned Immr = ShiftImm;
1671   unsigned Imms = NarrowVT.getSizeInBits() - 1;
1672   SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
1673                    CurDAG->getTargetConstant(Imms, dl, VT)};
1674   CurDAG->SelectNodeTo(N, AArch64::SBFMXri, VT, Ops);
1675   return true;
1676 }
1677 
1678 static bool isBitfieldExtractOp(SelectionDAG *CurDAG, SDNode *N, unsigned &Opc,
1679                                 SDValue &Opd0, unsigned &Immr, unsigned &Imms,
1680                                 unsigned NumberOfIgnoredLowBits = 0,
1681                                 bool BiggerPattern = false) {
1682   if (N->getValueType(0) != MVT::i32 && N->getValueType(0) != MVT::i64)
1683     return false;
1684 
1685   switch (N->getOpcode()) {
1686   default:
1687     if (!N->isMachineOpcode())
1688       return false;
1689     break;
1690   case ISD::AND:
1691     return isBitfieldExtractOpFromAnd(CurDAG, N, Opc, Opd0, Immr, Imms,
1692                                       NumberOfIgnoredLowBits, BiggerPattern);
1693   case ISD::SRL:
1694   case ISD::SRA:
1695     return isBitfieldExtractOpFromShr(N, Opc, Opd0, Immr, Imms, BiggerPattern);
1696 
1697   case ISD::SIGN_EXTEND_INREG:
1698     return isBitfieldExtractOpFromSExtInReg(N, Opc, Opd0, Immr, Imms);
1699   }
1700 
1701   unsigned NOpc = N->getMachineOpcode();
1702   switch (NOpc) {
1703   default:
1704     return false;
1705   case AArch64::SBFMWri:
1706   case AArch64::UBFMWri:
1707   case AArch64::SBFMXri:
1708   case AArch64::UBFMXri:
1709     Opc = NOpc;
1710     Opd0 = N->getOperand(0);
1711     Immr = cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
1712     Imms = cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
1713     return true;
1714   }
1715   // Unreachable
1716   return false;
1717 }
1718 
1719 bool AArch64DAGToDAGISel::tryBitfieldExtractOp(SDNode *N) {
1720   unsigned Opc, Immr, Imms;
1721   SDValue Opd0;
1722   if (!isBitfieldExtractOp(CurDAG, N, Opc, Opd0, Immr, Imms))
1723     return false;
1724 
1725   EVT VT = N->getValueType(0);
1726   SDLoc dl(N);
1727 
1728   // If the bit extract operation is 64bit but the original type is 32bit, we
1729   // need to add one EXTRACT_SUBREG.
1730   if ((Opc == AArch64::SBFMXri || Opc == AArch64::UBFMXri) && VT == MVT::i32) {
1731     SDValue Ops64[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, MVT::i64),
1732                        CurDAG->getTargetConstant(Imms, dl, MVT::i64)};
1733 
1734     SDNode *BFM = CurDAG->getMachineNode(Opc, dl, MVT::i64, Ops64);
1735     SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
1736     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1737                                           MVT::i32, SDValue(BFM, 0), SubReg));
1738     return true;
1739   }
1740 
1741   SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
1742                    CurDAG->getTargetConstant(Imms, dl, VT)};
1743   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
1744   return true;
1745 }
1746 
1747 /// Does DstMask form a complementary pair with the mask provided by
1748 /// BitsToBeInserted, suitable for use in a BFI instruction. Roughly speaking,
1749 /// this asks whether DstMask zeroes precisely those bits that will be set by
1750 /// the other half.
1751 static bool isBitfieldDstMask(uint64_t DstMask, const APInt &BitsToBeInserted,
1752                               unsigned NumberOfIgnoredHighBits, EVT VT) {
1753   assert((VT == MVT::i32 || VT == MVT::i64) &&
1754          "i32 or i64 mask type expected!");
1755   unsigned BitWidth = VT.getSizeInBits() - NumberOfIgnoredHighBits;
1756 
1757   APInt SignificantDstMask = APInt(BitWidth, DstMask);
1758   APInt SignificantBitsToBeInserted = BitsToBeInserted.zextOrTrunc(BitWidth);
1759 
1760   return (SignificantDstMask & SignificantBitsToBeInserted) == 0 &&
1761          (SignificantDstMask | SignificantBitsToBeInserted).isAllOnesValue();
1762 }
1763 
1764 // Look for bits that will be useful for later uses.
1765 // A bit is consider useless as soon as it is dropped and never used
1766 // before it as been dropped.
1767 // E.g., looking for useful bit of x
1768 // 1. y = x & 0x7
1769 // 2. z = y >> 2
1770 // After #1, x useful bits are 0x7, then the useful bits of x, live through
1771 // y.
1772 // After #2, the useful bits of x are 0x4.
1773 // However, if x is used on an unpredicatable instruction, then all its bits
1774 // are useful.
1775 // E.g.
1776 // 1. y = x & 0x7
1777 // 2. z = y >> 2
1778 // 3. str x, [@x]
1779 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth = 0);
1780 
1781 static void getUsefulBitsFromAndWithImmediate(SDValue Op, APInt &UsefulBits,
1782                                               unsigned Depth) {
1783   uint64_t Imm =
1784       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
1785   Imm = AArch64_AM::decodeLogicalImmediate(Imm, UsefulBits.getBitWidth());
1786   UsefulBits &= APInt(UsefulBits.getBitWidth(), Imm);
1787   getUsefulBits(Op, UsefulBits, Depth + 1);
1788 }
1789 
1790 static void getUsefulBitsFromBitfieldMoveOpd(SDValue Op, APInt &UsefulBits,
1791                                              uint64_t Imm, uint64_t MSB,
1792                                              unsigned Depth) {
1793   // inherit the bitwidth value
1794   APInt OpUsefulBits(UsefulBits);
1795   OpUsefulBits = 1;
1796 
1797   if (MSB >= Imm) {
1798     OpUsefulBits = OpUsefulBits.shl(MSB - Imm + 1);
1799     --OpUsefulBits;
1800     // The interesting part will be in the lower part of the result
1801     getUsefulBits(Op, OpUsefulBits, Depth + 1);
1802     // The interesting part was starting at Imm in the argument
1803     OpUsefulBits = OpUsefulBits.shl(Imm);
1804   } else {
1805     OpUsefulBits = OpUsefulBits.shl(MSB + 1);
1806     --OpUsefulBits;
1807     // The interesting part will be shifted in the result
1808     OpUsefulBits = OpUsefulBits.shl(OpUsefulBits.getBitWidth() - Imm);
1809     getUsefulBits(Op, OpUsefulBits, Depth + 1);
1810     // The interesting part was at zero in the argument
1811     OpUsefulBits = OpUsefulBits.lshr(OpUsefulBits.getBitWidth() - Imm);
1812   }
1813 
1814   UsefulBits &= OpUsefulBits;
1815 }
1816 
1817 static void getUsefulBitsFromUBFM(SDValue Op, APInt &UsefulBits,
1818                                   unsigned Depth) {
1819   uint64_t Imm =
1820       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
1821   uint64_t MSB =
1822       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1823 
1824   getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
1825 }
1826 
1827 static void getUsefulBitsFromOrWithShiftedReg(SDValue Op, APInt &UsefulBits,
1828                                               unsigned Depth) {
1829   uint64_t ShiftTypeAndValue =
1830       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1831   APInt Mask(UsefulBits);
1832   Mask.clearAllBits();
1833   Mask.flipAllBits();
1834 
1835   if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSL) {
1836     // Shift Left
1837     uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
1838     Mask = Mask.shl(ShiftAmt);
1839     getUsefulBits(Op, Mask, Depth + 1);
1840     Mask = Mask.lshr(ShiftAmt);
1841   } else if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSR) {
1842     // Shift Right
1843     // We do not handle AArch64_AM::ASR, because the sign will change the
1844     // number of useful bits
1845     uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
1846     Mask = Mask.lshr(ShiftAmt);
1847     getUsefulBits(Op, Mask, Depth + 1);
1848     Mask = Mask.shl(ShiftAmt);
1849   } else
1850     return;
1851 
1852   UsefulBits &= Mask;
1853 }
1854 
1855 static void getUsefulBitsFromBFM(SDValue Op, SDValue Orig, APInt &UsefulBits,
1856                                  unsigned Depth) {
1857   uint64_t Imm =
1858       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1859   uint64_t MSB =
1860       cast<const ConstantSDNode>(Op.getOperand(3).getNode())->getZExtValue();
1861 
1862   if (Op.getOperand(1) == Orig)
1863     return getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
1864 
1865   APInt OpUsefulBits(UsefulBits);
1866   OpUsefulBits = 1;
1867 
1868   if (MSB >= Imm) {
1869     OpUsefulBits = OpUsefulBits.shl(MSB - Imm + 1);
1870     --OpUsefulBits;
1871     UsefulBits &= ~OpUsefulBits;
1872     getUsefulBits(Op, UsefulBits, Depth + 1);
1873   } else {
1874     OpUsefulBits = OpUsefulBits.shl(MSB + 1);
1875     --OpUsefulBits;
1876     UsefulBits = ~(OpUsefulBits.shl(OpUsefulBits.getBitWidth() - Imm));
1877     getUsefulBits(Op, UsefulBits, Depth + 1);
1878   }
1879 }
1880 
1881 static void getUsefulBitsForUse(SDNode *UserNode, APInt &UsefulBits,
1882                                 SDValue Orig, unsigned Depth) {
1883 
1884   // Users of this node should have already been instruction selected
1885   // FIXME: Can we turn that into an assert?
1886   if (!UserNode->isMachineOpcode())
1887     return;
1888 
1889   switch (UserNode->getMachineOpcode()) {
1890   default:
1891     return;
1892   case AArch64::ANDSWri:
1893   case AArch64::ANDSXri:
1894   case AArch64::ANDWri:
1895   case AArch64::ANDXri:
1896     // We increment Depth only when we call the getUsefulBits
1897     return getUsefulBitsFromAndWithImmediate(SDValue(UserNode, 0), UsefulBits,
1898                                              Depth);
1899   case AArch64::UBFMWri:
1900   case AArch64::UBFMXri:
1901     return getUsefulBitsFromUBFM(SDValue(UserNode, 0), UsefulBits, Depth);
1902 
1903   case AArch64::ORRWrs:
1904   case AArch64::ORRXrs:
1905     if (UserNode->getOperand(1) != Orig)
1906       return;
1907     return getUsefulBitsFromOrWithShiftedReg(SDValue(UserNode, 0), UsefulBits,
1908                                              Depth);
1909   case AArch64::BFMWri:
1910   case AArch64::BFMXri:
1911     return getUsefulBitsFromBFM(SDValue(UserNode, 0), Orig, UsefulBits, Depth);
1912 
1913   case AArch64::STRBBui:
1914   case AArch64::STURBBi:
1915     if (UserNode->getOperand(0) != Orig)
1916       return;
1917     UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xff);
1918     return;
1919 
1920   case AArch64::STRHHui:
1921   case AArch64::STURHHi:
1922     if (UserNode->getOperand(0) != Orig)
1923       return;
1924     UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xffff);
1925     return;
1926   }
1927 }
1928 
1929 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth) {
1930   if (Depth >= 6)
1931     return;
1932   // Initialize UsefulBits
1933   if (!Depth) {
1934     unsigned Bitwidth = Op.getValueType().getScalarType().getSizeInBits();
1935     // At the beginning, assume every produced bits is useful
1936     UsefulBits = APInt(Bitwidth, 0);
1937     UsefulBits.flipAllBits();
1938   }
1939   APInt UsersUsefulBits(UsefulBits.getBitWidth(), 0);
1940 
1941   for (SDNode *Node : Op.getNode()->uses()) {
1942     // A use cannot produce useful bits
1943     APInt UsefulBitsForUse = APInt(UsefulBits);
1944     getUsefulBitsForUse(Node, UsefulBitsForUse, Op, Depth);
1945     UsersUsefulBits |= UsefulBitsForUse;
1946   }
1947   // UsefulBits contains the produced bits that are meaningful for the
1948   // current definition, thus a user cannot make a bit meaningful at
1949   // this point
1950   UsefulBits &= UsersUsefulBits;
1951 }
1952 
1953 /// Create a machine node performing a notional SHL of Op by ShlAmount. If
1954 /// ShlAmount is negative, do a (logical) right-shift instead. If ShlAmount is
1955 /// 0, return Op unchanged.
1956 static SDValue getLeftShift(SelectionDAG *CurDAG, SDValue Op, int ShlAmount) {
1957   if (ShlAmount == 0)
1958     return Op;
1959 
1960   EVT VT = Op.getValueType();
1961   SDLoc dl(Op);
1962   unsigned BitWidth = VT.getSizeInBits();
1963   unsigned UBFMOpc = BitWidth == 32 ? AArch64::UBFMWri : AArch64::UBFMXri;
1964 
1965   SDNode *ShiftNode;
1966   if (ShlAmount > 0) {
1967     // LSL wD, wN, #Amt == UBFM wD, wN, #32-Amt, #31-Amt
1968     ShiftNode = CurDAG->getMachineNode(
1969         UBFMOpc, dl, VT, Op,
1970         CurDAG->getTargetConstant(BitWidth - ShlAmount, dl, VT),
1971         CurDAG->getTargetConstant(BitWidth - 1 - ShlAmount, dl, VT));
1972   } else {
1973     // LSR wD, wN, #Amt == UBFM wD, wN, #Amt, #32-1
1974     assert(ShlAmount < 0 && "expected right shift");
1975     int ShrAmount = -ShlAmount;
1976     ShiftNode = CurDAG->getMachineNode(
1977         UBFMOpc, dl, VT, Op, CurDAG->getTargetConstant(ShrAmount, dl, VT),
1978         CurDAG->getTargetConstant(BitWidth - 1, dl, VT));
1979   }
1980 
1981   return SDValue(ShiftNode, 0);
1982 }
1983 
1984 /// Does this tree qualify as an attempt to move a bitfield into position,
1985 /// essentially "(and (shl VAL, N), Mask)".
1986 static bool isBitfieldPositioningOp(SelectionDAG *CurDAG, SDValue Op,
1987                                     bool BiggerPattern,
1988                                     SDValue &Src, int &ShiftAmount,
1989                                     int &MaskWidth) {
1990   EVT VT = Op.getValueType();
1991   unsigned BitWidth = VT.getSizeInBits();
1992   (void)BitWidth;
1993   assert(BitWidth == 32 || BitWidth == 64);
1994 
1995   APInt KnownZero, KnownOne;
1996   CurDAG->computeKnownBits(Op, KnownZero, KnownOne);
1997 
1998   // Non-zero in the sense that they're not provably zero, which is the key
1999   // point if we want to use this value
2000   uint64_t NonZeroBits = (~KnownZero).getZExtValue();
2001 
2002   // Discard a constant AND mask if present. It's safe because the node will
2003   // already have been factored into the computeKnownBits calculation above.
2004   uint64_t AndImm;
2005   if (isOpcWithIntImmediate(Op.getNode(), ISD::AND, AndImm)) {
2006     assert((~APInt(BitWidth, AndImm) & ~KnownZero) == 0);
2007     Op = Op.getOperand(0);
2008   }
2009 
2010   // Don't match if the SHL has more than one use, since then we'll end up
2011   // generating SHL+UBFIZ instead of just keeping SHL+AND.
2012   if (!BiggerPattern && !Op.hasOneUse())
2013     return false;
2014 
2015   uint64_t ShlImm;
2016   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SHL, ShlImm))
2017     return false;
2018   Op = Op.getOperand(0);
2019 
2020   if (!isShiftedMask_64(NonZeroBits))
2021     return false;
2022 
2023   ShiftAmount = countTrailingZeros(NonZeroBits);
2024   MaskWidth = countTrailingOnes(NonZeroBits >> ShiftAmount);
2025 
2026   // BFI encompasses sufficiently many nodes that it's worth inserting an extra
2027   // LSL/LSR if the mask in NonZeroBits doesn't quite match up with the ISD::SHL
2028   // amount.  BiggerPattern is true when this pattern is being matched for BFI,
2029   // BiggerPattern is false when this pattern is being matched for UBFIZ, in
2030   // which case it is not profitable to insert an extra shift.
2031   if (ShlImm - ShiftAmount != 0 && !BiggerPattern)
2032     return false;
2033   Src = getLeftShift(CurDAG, Op, ShlImm - ShiftAmount);
2034 
2035   return true;
2036 }
2037 
2038 static bool isShiftedMask(uint64_t Mask, EVT VT) {
2039   assert(VT == MVT::i32 || VT == MVT::i64);
2040   if (VT == MVT::i32)
2041     return isShiftedMask_32(Mask);
2042   return isShiftedMask_64(Mask);
2043 }
2044 
2045 // Generate a BFI/BFXIL from 'or (and X, MaskImm), OrImm' iff the value being
2046 // inserted only sets known zero bits.
2047 static bool tryBitfieldInsertOpFromOrAndImm(SDNode *N, SelectionDAG *CurDAG) {
2048   assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
2049 
2050   EVT VT = N->getValueType(0);
2051   if (VT != MVT::i32 && VT != MVT::i64)
2052     return false;
2053 
2054   unsigned BitWidth = VT.getSizeInBits();
2055 
2056   uint64_t OrImm;
2057   if (!isOpcWithIntImmediate(N, ISD::OR, OrImm))
2058     return false;
2059 
2060   // Skip this transformation if the ORR immediate can be encoded in the ORR.
2061   // Otherwise, we'll trade an AND+ORR for ORR+BFI/BFXIL, which is most likely
2062   // performance neutral.
2063   if (AArch64_AM::isLogicalImmediate(OrImm, BitWidth))
2064     return false;
2065 
2066   uint64_t MaskImm;
2067   SDValue And = N->getOperand(0);
2068   // Must be a single use AND with an immediate operand.
2069   if (!And.hasOneUse() ||
2070       !isOpcWithIntImmediate(And.getNode(), ISD::AND, MaskImm))
2071     return false;
2072 
2073   // Compute the Known Zero for the AND as this allows us to catch more general
2074   // cases than just looking for AND with imm.
2075   APInt KnownZero, KnownOne;
2076   CurDAG->computeKnownBits(And, KnownZero, KnownOne);
2077 
2078   // Non-zero in the sense that they're not provably zero, which is the key
2079   // point if we want to use this value.
2080   uint64_t NotKnownZero = (~KnownZero).getZExtValue();
2081 
2082   // The KnownZero mask must be a shifted mask (e.g., 1110..011, 11100..00).
2083   if (!isShiftedMask(KnownZero.getZExtValue(), VT))
2084     return false;
2085 
2086   // The bits being inserted must only set those bits that are known to be zero.
2087   if ((OrImm & NotKnownZero) != 0) {
2088     // FIXME:  It's okay if the OrImm sets NotKnownZero bits to 1, but we don't
2089     // currently handle this case.
2090     return false;
2091   }
2092 
2093   // BFI/BFXIL dst, src, #lsb, #width.
2094   int LSB = countTrailingOnes(NotKnownZero);
2095   int Width = BitWidth - APInt(BitWidth, NotKnownZero).countPopulation();
2096 
2097   // BFI/BFXIL is an alias of BFM, so translate to BFM operands.
2098   unsigned ImmR = (BitWidth - LSB) % BitWidth;
2099   unsigned ImmS = Width - 1;
2100 
2101   // If we're creating a BFI instruction avoid cases where we need more
2102   // instructions to materialize the BFI constant as compared to the original
2103   // ORR.  A BFXIL will use the same constant as the original ORR, so the code
2104   // should be no worse in this case.
2105   bool IsBFI = LSB != 0;
2106   uint64_t BFIImm = OrImm >> LSB;
2107   if (IsBFI && !AArch64_AM::isLogicalImmediate(BFIImm, BitWidth)) {
2108     // We have a BFI instruction and we know the constant can't be materialized
2109     // with a ORR-immediate with the zero register.
2110     unsigned OrChunks = 0, BFIChunks = 0;
2111     for (unsigned Shift = 0; Shift < BitWidth; Shift += 16) {
2112       if (((OrImm >> Shift) & 0xFFFF) != 0)
2113         ++OrChunks;
2114       if (((BFIImm >> Shift) & 0xFFFF) != 0)
2115         ++BFIChunks;
2116     }
2117     if (BFIChunks > OrChunks)
2118       return false;
2119   }
2120 
2121   // Materialize the constant to be inserted.
2122   SDLoc DL(N);
2123   unsigned MOVIOpc = VT == MVT::i32 ? AArch64::MOVi32imm : AArch64::MOVi64imm;
2124   SDNode *MOVI = CurDAG->getMachineNode(
2125       MOVIOpc, DL, VT, CurDAG->getTargetConstant(BFIImm, DL, VT));
2126 
2127   // Create the BFI/BFXIL instruction.
2128   SDValue Ops[] = {And.getOperand(0), SDValue(MOVI, 0),
2129                    CurDAG->getTargetConstant(ImmR, DL, VT),
2130                    CurDAG->getTargetConstant(ImmS, DL, VT)};
2131   unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2132   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2133   return true;
2134 }
2135 
2136 static bool tryBitfieldInsertOpFromOr(SDNode *N, const APInt &UsefulBits,
2137                                       SelectionDAG *CurDAG) {
2138   assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
2139 
2140   EVT VT = N->getValueType(0);
2141   if (VT != MVT::i32 && VT != MVT::i64)
2142     return false;
2143 
2144   unsigned BitWidth = VT.getSizeInBits();
2145 
2146   // Because of simplify-demanded-bits in DAGCombine, involved masks may not
2147   // have the expected shape. Try to undo that.
2148 
2149   unsigned NumberOfIgnoredLowBits = UsefulBits.countTrailingZeros();
2150   unsigned NumberOfIgnoredHighBits = UsefulBits.countLeadingZeros();
2151 
2152   // Given a OR operation, check if we have the following pattern
2153   // ubfm c, b, imm, imm2 (or something that does the same jobs, see
2154   //                       isBitfieldExtractOp)
2155   // d = e & mask2 ; where mask is a binary sequence of 1..10..0 and
2156   //                 countTrailingZeros(mask2) == imm2 - imm + 1
2157   // f = d | c
2158   // if yes, replace the OR instruction with:
2159   // f = BFM Opd0, Opd1, LSB, MSB ; where LSB = imm, and MSB = imm2
2160 
2161   // OR is commutative, check all combinations of operand order and values of
2162   // BiggerPattern, i.e.
2163   //     Opd0, Opd1, BiggerPattern=false
2164   //     Opd1, Opd0, BiggerPattern=false
2165   //     Opd0, Opd1, BiggerPattern=true
2166   //     Opd1, Opd0, BiggerPattern=true
2167   // Several of these combinations may match, so check with BiggerPattern=false
2168   // first since that will produce better results by matching more instructions
2169   // and/or inserting fewer extra instructions.
2170   for (int I = 0; I < 4; ++I) {
2171 
2172     SDValue Dst, Src;
2173     unsigned ImmR, ImmS;
2174     bool BiggerPattern = I / 2;
2175     SDNode *OrOpd0 = N->getOperand(I % 2).getNode();
2176     SDValue OrOpd1Val = N->getOperand((I + 1) % 2);
2177     SDNode *OrOpd1 = OrOpd1Val.getNode();
2178 
2179     unsigned BFXOpc;
2180     int DstLSB, Width;
2181     if (isBitfieldExtractOp(CurDAG, OrOpd0, BFXOpc, Src, ImmR, ImmS,
2182                             NumberOfIgnoredLowBits, BiggerPattern)) {
2183       // Check that the returned opcode is compatible with the pattern,
2184       // i.e., same type and zero extended (U and not S)
2185       if ((BFXOpc != AArch64::UBFMXri && VT == MVT::i64) ||
2186           (BFXOpc != AArch64::UBFMWri && VT == MVT::i32))
2187         continue;
2188 
2189       // Compute the width of the bitfield insertion
2190       DstLSB = 0;
2191       Width = ImmS - ImmR + 1;
2192       // FIXME: This constraint is to catch bitfield insertion we may
2193       // want to widen the pattern if we want to grab general bitfied
2194       // move case
2195       if (Width <= 0)
2196         continue;
2197 
2198       // If the mask on the insertee is correct, we have a BFXIL operation. We
2199       // can share the ImmR and ImmS values from the already-computed UBFM.
2200     } else if (isBitfieldPositioningOp(CurDAG, SDValue(OrOpd0, 0),
2201                                        BiggerPattern,
2202                                        Src, DstLSB, Width)) {
2203       ImmR = (BitWidth - DstLSB) % BitWidth;
2204       ImmS = Width - 1;
2205     } else
2206       continue;
2207 
2208     // Check the second part of the pattern
2209     EVT VT = OrOpd1->getValueType(0);
2210     assert((VT == MVT::i32 || VT == MVT::i64) && "unexpected OR operand");
2211 
2212     // Compute the Known Zero for the candidate of the first operand.
2213     // This allows to catch more general case than just looking for
2214     // AND with imm. Indeed, simplify-demanded-bits may have removed
2215     // the AND instruction because it proves it was useless.
2216     APInt KnownZero, KnownOne;
2217     CurDAG->computeKnownBits(OrOpd1Val, KnownZero, KnownOne);
2218 
2219     // Check if there is enough room for the second operand to appear
2220     // in the first one
2221     APInt BitsToBeInserted =
2222         APInt::getBitsSet(KnownZero.getBitWidth(), DstLSB, DstLSB + Width);
2223 
2224     if ((BitsToBeInserted & ~KnownZero) != 0)
2225       continue;
2226 
2227     // Set the first operand
2228     uint64_t Imm;
2229     if (isOpcWithIntImmediate(OrOpd1, ISD::AND, Imm) &&
2230         isBitfieldDstMask(Imm, BitsToBeInserted, NumberOfIgnoredHighBits, VT))
2231       // In that case, we can eliminate the AND
2232       Dst = OrOpd1->getOperand(0);
2233     else
2234       // Maybe the AND has been removed by simplify-demanded-bits
2235       // or is useful because it discards more bits
2236       Dst = OrOpd1Val;
2237 
2238     // both parts match
2239     SDLoc DL(N);
2240     SDValue Ops[] = {Dst, Src, CurDAG->getTargetConstant(ImmR, DL, VT),
2241                      CurDAG->getTargetConstant(ImmS, DL, VT)};
2242     unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2243     CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2244     return true;
2245   }
2246 
2247   // Generate a BFXIL from 'or (and X, Mask0Imm), (and Y, Mask1Imm)' iff
2248   // Mask0Imm and ~Mask1Imm are equivalent and one of the MaskImms is a shifted
2249   // mask (e.g., 0x000ffff0).
2250   uint64_t Mask0Imm, Mask1Imm;
2251   SDValue And0 = N->getOperand(0);
2252   SDValue And1 = N->getOperand(1);
2253   if (And0.hasOneUse() && And1.hasOneUse() &&
2254       isOpcWithIntImmediate(And0.getNode(), ISD::AND, Mask0Imm) &&
2255       isOpcWithIntImmediate(And1.getNode(), ISD::AND, Mask1Imm) &&
2256       APInt(BitWidth, Mask0Imm) == ~APInt(BitWidth, Mask1Imm) &&
2257       (isShiftedMask(Mask0Imm, VT) || isShiftedMask(Mask1Imm, VT))) {
2258 
2259     // ORR is commutative, so canonicalize to the form 'or (and X, Mask0Imm),
2260     // (and Y, Mask1Imm)' where Mask1Imm is the shifted mask masking off the
2261     // bits to be inserted.
2262     if (isShiftedMask(Mask0Imm, VT)) {
2263       std::swap(And0, And1);
2264       std::swap(Mask0Imm, Mask1Imm);
2265     }
2266 
2267     SDValue Src = And1->getOperand(0);
2268     SDValue Dst = And0->getOperand(0);
2269     unsigned LSB = countTrailingZeros(Mask1Imm);
2270     int Width = BitWidth - APInt(BitWidth, Mask0Imm).countPopulation();
2271 
2272     // The BFXIL inserts the low-order bits from a source register, so right
2273     // shift the needed bits into place.
2274     SDLoc DL(N);
2275     unsigned ShiftOpc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
2276     SDNode *LSR = CurDAG->getMachineNode(
2277         ShiftOpc, DL, VT, Src, CurDAG->getTargetConstant(LSB, DL, VT),
2278         CurDAG->getTargetConstant(BitWidth - 1, DL, VT));
2279 
2280     // BFXIL is an alias of BFM, so translate to BFM operands.
2281     unsigned ImmR = (BitWidth - LSB) % BitWidth;
2282     unsigned ImmS = Width - 1;
2283 
2284     // Create the BFXIL instruction.
2285     SDValue Ops[] = {Dst, SDValue(LSR, 0),
2286                      CurDAG->getTargetConstant(ImmR, DL, VT),
2287                      CurDAG->getTargetConstant(ImmS, DL, VT)};
2288     unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2289     CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2290     return true;
2291   }
2292 
2293   return false;
2294 }
2295 
2296 bool AArch64DAGToDAGISel::tryBitfieldInsertOp(SDNode *N) {
2297   if (N->getOpcode() != ISD::OR)
2298     return false;
2299 
2300   APInt NUsefulBits;
2301   getUsefulBits(SDValue(N, 0), NUsefulBits);
2302 
2303   // If all bits are not useful, just return UNDEF.
2304   if (!NUsefulBits) {
2305     CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2306     return true;
2307   }
2308 
2309   if (tryBitfieldInsertOpFromOr(N, NUsefulBits, CurDAG))
2310     return true;
2311 
2312   return tryBitfieldInsertOpFromOrAndImm(N, CurDAG);
2313 }
2314 
2315 /// SelectBitfieldInsertInZeroOp - Match a UBFIZ instruction that is the
2316 /// equivalent of a left shift by a constant amount followed by an and masking
2317 /// out a contiguous set of bits.
2318 bool AArch64DAGToDAGISel::tryBitfieldInsertInZeroOp(SDNode *N) {
2319   if (N->getOpcode() != ISD::AND)
2320     return false;
2321 
2322   EVT VT = N->getValueType(0);
2323   if (VT != MVT::i32 && VT != MVT::i64)
2324     return false;
2325 
2326   SDValue Op0;
2327   int DstLSB, Width;
2328   if (!isBitfieldPositioningOp(CurDAG, SDValue(N, 0), /*BiggerPattern=*/false,
2329                                Op0, DstLSB, Width))
2330     return false;
2331 
2332   // ImmR is the rotate right amount.
2333   unsigned ImmR = (VT.getSizeInBits() - DstLSB) % VT.getSizeInBits();
2334   // ImmS is the most significant bit of the source to be moved.
2335   unsigned ImmS = Width - 1;
2336 
2337   SDLoc DL(N);
2338   SDValue Ops[] = {Op0, CurDAG->getTargetConstant(ImmR, DL, VT),
2339                    CurDAG->getTargetConstant(ImmS, DL, VT)};
2340   unsigned Opc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
2341   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2342   return true;
2343 }
2344 
2345 bool
2346 AArch64DAGToDAGISel::SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos,
2347                                               unsigned RegWidth) {
2348   APFloat FVal(0.0);
2349   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
2350     FVal = CN->getValueAPF();
2351   else if (LoadSDNode *LN = dyn_cast<LoadSDNode>(N)) {
2352     // Some otherwise illegal constants are allowed in this case.
2353     if (LN->getOperand(1).getOpcode() != AArch64ISD::ADDlow ||
2354         !isa<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1)))
2355       return false;
2356 
2357     ConstantPoolSDNode *CN =
2358         dyn_cast<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1));
2359     FVal = cast<ConstantFP>(CN->getConstVal())->getValueAPF();
2360   } else
2361     return false;
2362 
2363   // An FCVT[SU] instruction performs: convertToInt(Val * 2^fbits) where fbits
2364   // is between 1 and 32 for a destination w-register, or 1 and 64 for an
2365   // x-register.
2366   //
2367   // By this stage, we've detected (fp_to_[su]int (fmul Val, THIS_NODE)) so we
2368   // want THIS_NODE to be 2^fbits. This is much easier to deal with using
2369   // integers.
2370   bool IsExact;
2371 
2372   // fbits is between 1 and 64 in the worst-case, which means the fmul
2373   // could have 2^64 as an actual operand. Need 65 bits of precision.
2374   APSInt IntVal(65, true);
2375   FVal.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact);
2376 
2377   // N.b. isPowerOf2 also checks for > 0.
2378   if (!IsExact || !IntVal.isPowerOf2()) return false;
2379   unsigned FBits = IntVal.logBase2();
2380 
2381   // Checks above should have guaranteed that we haven't lost information in
2382   // finding FBits, but it must still be in range.
2383   if (FBits == 0 || FBits > RegWidth) return false;
2384 
2385   FixedPos = CurDAG->getTargetConstant(FBits, SDLoc(N), MVT::i32);
2386   return true;
2387 }
2388 
2389 // Inspects a register string of the form o0:op1:CRn:CRm:op2 gets the fields
2390 // of the string and obtains the integer values from them and combines these
2391 // into a single value to be used in the MRS/MSR instruction.
2392 static int getIntOperandFromRegisterString(StringRef RegString) {
2393   SmallVector<StringRef, 5> Fields;
2394   RegString.split(Fields, ':');
2395 
2396   if (Fields.size() == 1)
2397     return -1;
2398 
2399   assert(Fields.size() == 5
2400             && "Invalid number of fields in read register string");
2401 
2402   SmallVector<int, 5> Ops;
2403   bool AllIntFields = true;
2404 
2405   for (StringRef Field : Fields) {
2406     unsigned IntField;
2407     AllIntFields &= !Field.getAsInteger(10, IntField);
2408     Ops.push_back(IntField);
2409   }
2410 
2411   assert(AllIntFields &&
2412           "Unexpected non-integer value in special register string.");
2413 
2414   // Need to combine the integer fields of the string into a single value
2415   // based on the bit encoding of MRS/MSR instruction.
2416   return (Ops[0] << 14) | (Ops[1] << 11) | (Ops[2] << 7) |
2417          (Ops[3] << 3) | (Ops[4]);
2418 }
2419 
2420 // Lower the read_register intrinsic to an MRS instruction node if the special
2421 // register string argument is either of the form detailed in the ALCE (the
2422 // form described in getIntOperandsFromRegsterString) or is a named register
2423 // known by the MRS SysReg mapper.
2424 bool AArch64DAGToDAGISel::tryReadRegister(SDNode *N) {
2425   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
2426   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2427   SDLoc DL(N);
2428 
2429   int Reg = getIntOperandFromRegisterString(RegString->getString());
2430   if (Reg != -1) {
2431     ReplaceNode(N, CurDAG->getMachineNode(
2432                        AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
2433                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2434                        N->getOperand(0)));
2435     return true;
2436   }
2437 
2438   // Use the sysreg mapper to map the remaining possible strings to the
2439   // value for the register to be used for the instruction operand.
2440   AArch64SysReg::MRSMapper mapper;
2441   bool IsValidSpecialReg;
2442   Reg = mapper.fromString(RegString->getString(),
2443                           Subtarget->getFeatureBits(),
2444                           IsValidSpecialReg);
2445   if (IsValidSpecialReg) {
2446     ReplaceNode(N, CurDAG->getMachineNode(
2447                        AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
2448                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2449                        N->getOperand(0)));
2450     return true;
2451   }
2452 
2453   return false;
2454 }
2455 
2456 // Lower the write_register intrinsic to an MSR instruction node if the special
2457 // register string argument is either of the form detailed in the ALCE (the
2458 // form described in getIntOperandsFromRegsterString) or is a named register
2459 // known by the MSR SysReg mapper.
2460 bool AArch64DAGToDAGISel::tryWriteRegister(SDNode *N) {
2461   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
2462   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2463   SDLoc DL(N);
2464 
2465   int Reg = getIntOperandFromRegisterString(RegString->getString());
2466   if (Reg != -1) {
2467     ReplaceNode(
2468         N, CurDAG->getMachineNode(AArch64::MSR, DL, MVT::Other,
2469                                   CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2470                                   N->getOperand(2), N->getOperand(0)));
2471     return true;
2472   }
2473 
2474   // Check if the register was one of those allowed as the pstatefield value in
2475   // the MSR (immediate) instruction. To accept the values allowed in the
2476   // pstatefield for the MSR (immediate) instruction, we also require that an
2477   // immediate value has been provided as an argument, we know that this is
2478   // the case as it has been ensured by semantic checking.
2479   AArch64PState::PStateMapper PMapper;
2480   bool IsValidSpecialReg;
2481   Reg = PMapper.fromString(RegString->getString(),
2482                            Subtarget->getFeatureBits(),
2483                            IsValidSpecialReg);
2484   if (IsValidSpecialReg) {
2485     assert (isa<ConstantSDNode>(N->getOperand(2))
2486               && "Expected a constant integer expression.");
2487     uint64_t Immed = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
2488     unsigned State;
2489     if (Reg == AArch64PState::PAN || Reg == AArch64PState::UAO) {
2490       assert(Immed < 2 && "Bad imm");
2491       State = AArch64::MSRpstateImm1;
2492     } else {
2493       assert(Immed < 16 && "Bad imm");
2494       State = AArch64::MSRpstateImm4;
2495     }
2496     ReplaceNode(N, CurDAG->getMachineNode(
2497                        State, DL, MVT::Other,
2498                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2499                        CurDAG->getTargetConstant(Immed, DL, MVT::i16),
2500                        N->getOperand(0)));
2501     return true;
2502   }
2503 
2504   // Use the sysreg mapper to attempt to map the remaining possible strings
2505   // to the value for the register to be used for the MSR (register)
2506   // instruction operand.
2507   AArch64SysReg::MSRMapper Mapper;
2508   Reg = Mapper.fromString(RegString->getString(),
2509                           Subtarget->getFeatureBits(),
2510                           IsValidSpecialReg);
2511 
2512   if (IsValidSpecialReg) {
2513     ReplaceNode(
2514         N, CurDAG->getMachineNode(AArch64::MSR, DL, MVT::Other,
2515                                   CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2516                                   N->getOperand(2), N->getOperand(0)));
2517     return true;
2518   }
2519 
2520   return false;
2521 }
2522 
2523 /// We've got special pseudo-instructions for these
2524 void AArch64DAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
2525   unsigned Opcode;
2526   EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
2527   if (MemTy == MVT::i8)
2528     Opcode = AArch64::CMP_SWAP_8;
2529   else if (MemTy == MVT::i16)
2530     Opcode = AArch64::CMP_SWAP_16;
2531   else if (MemTy == MVT::i32)
2532     Opcode = AArch64::CMP_SWAP_32;
2533   else if (MemTy == MVT::i64)
2534     Opcode = AArch64::CMP_SWAP_64;
2535   else
2536     llvm_unreachable("Unknown AtomicCmpSwap type");
2537 
2538   MVT RegTy = MemTy == MVT::i64 ? MVT::i64 : MVT::i32;
2539   SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
2540                    N->getOperand(0)};
2541   SDNode *CmpSwap = CurDAG->getMachineNode(
2542       Opcode, SDLoc(N),
2543       CurDAG->getVTList(RegTy, MVT::i32, MVT::Other), Ops);
2544 
2545   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2546   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2547   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
2548 
2549   ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
2550   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
2551   CurDAG->RemoveDeadNode(N);
2552 }
2553 
2554 void AArch64DAGToDAGISel::Select(SDNode *Node) {
2555   // Dump information about the Node being selected
2556   DEBUG(errs() << "Selecting: ");
2557   DEBUG(Node->dump(CurDAG));
2558   DEBUG(errs() << "\n");
2559 
2560   // If we have a custom node, we already have selected!
2561   if (Node->isMachineOpcode()) {
2562     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
2563     Node->setNodeId(-1);
2564     return;
2565   }
2566 
2567   // Few custom selection stuff.
2568   EVT VT = Node->getValueType(0);
2569 
2570   switch (Node->getOpcode()) {
2571   default:
2572     break;
2573 
2574   case ISD::ATOMIC_CMP_SWAP:
2575     SelectCMP_SWAP(Node);
2576     return;
2577 
2578   case ISD::READ_REGISTER:
2579     if (tryReadRegister(Node))
2580       return;
2581     break;
2582 
2583   case ISD::WRITE_REGISTER:
2584     if (tryWriteRegister(Node))
2585       return;
2586     break;
2587 
2588   case ISD::ADD:
2589     if (tryMLAV64LaneV128(Node))
2590       return;
2591     break;
2592 
2593   case ISD::LOAD: {
2594     // Try to select as an indexed load. Fall through to normal processing
2595     // if we can't.
2596     if (tryIndexedLoad(Node))
2597       return;
2598     break;
2599   }
2600 
2601   case ISD::SRL:
2602   case ISD::AND:
2603   case ISD::SRA:
2604   case ISD::SIGN_EXTEND_INREG:
2605     if (tryBitfieldExtractOp(Node))
2606       return;
2607     if (tryBitfieldInsertInZeroOp(Node))
2608       return;
2609     break;
2610 
2611   case ISD::SIGN_EXTEND:
2612     if (tryBitfieldExtractOpFromSExt(Node))
2613       return;
2614     break;
2615 
2616   case ISD::OR:
2617     if (tryBitfieldInsertOp(Node))
2618       return;
2619     break;
2620 
2621   case ISD::EXTRACT_VECTOR_ELT: {
2622     // Extracting lane zero is a special case where we can just use a plain
2623     // EXTRACT_SUBREG instruction, which will become FMOV. This is easier for
2624     // the rest of the compiler, especially the register allocator and copyi
2625     // propagation, to reason about, so is preferred when it's possible to
2626     // use it.
2627     ConstantSDNode *LaneNode = cast<ConstantSDNode>(Node->getOperand(1));
2628     // Bail and use the default Select() for non-zero lanes.
2629     if (LaneNode->getZExtValue() != 0)
2630       break;
2631     // If the element type is not the same as the result type, likewise
2632     // bail and use the default Select(), as there's more to do than just
2633     // a cross-class COPY. This catches extracts of i8 and i16 elements
2634     // since they will need an explicit zext.
2635     if (VT != Node->getOperand(0).getValueType().getVectorElementType())
2636       break;
2637     unsigned SubReg;
2638     switch (Node->getOperand(0)
2639                 .getValueType()
2640                 .getVectorElementType()
2641                 .getSizeInBits()) {
2642     default:
2643       llvm_unreachable("Unexpected vector element type!");
2644     case 64:
2645       SubReg = AArch64::dsub;
2646       break;
2647     case 32:
2648       SubReg = AArch64::ssub;
2649       break;
2650     case 16:
2651       SubReg = AArch64::hsub;
2652       break;
2653     case 8:
2654       llvm_unreachable("unexpected zext-requiring extract element!");
2655     }
2656     SDValue Extract = CurDAG->getTargetExtractSubreg(SubReg, SDLoc(Node), VT,
2657                                                      Node->getOperand(0));
2658     DEBUG(dbgs() << "ISEL: Custom selection!\n=> ");
2659     DEBUG(Extract->dumpr(CurDAG));
2660     DEBUG(dbgs() << "\n");
2661     ReplaceNode(Node, Extract.getNode());
2662     return;
2663   }
2664   case ISD::Constant: {
2665     // Materialize zero constants as copies from WZR/XZR.  This allows
2666     // the coalescer to propagate these into other instructions.
2667     ConstantSDNode *ConstNode = cast<ConstantSDNode>(Node);
2668     if (ConstNode->isNullValue()) {
2669       if (VT == MVT::i32) {
2670         SDValue New = CurDAG->getCopyFromReg(
2671             CurDAG->getEntryNode(), SDLoc(Node), AArch64::WZR, MVT::i32);
2672         ReplaceNode(Node, New.getNode());
2673         return;
2674       } else if (VT == MVT::i64) {
2675         SDValue New = CurDAG->getCopyFromReg(
2676             CurDAG->getEntryNode(), SDLoc(Node), AArch64::XZR, MVT::i64);
2677         ReplaceNode(Node, New.getNode());
2678         return;
2679       }
2680     }
2681     break;
2682   }
2683 
2684   case ISD::FrameIndex: {
2685     // Selects to ADDXri FI, 0 which in turn will become ADDXri SP, imm.
2686     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
2687     unsigned Shifter = AArch64_AM::getShifterImm(AArch64_AM::LSL, 0);
2688     const TargetLowering *TLI = getTargetLowering();
2689     SDValue TFI = CurDAG->getTargetFrameIndex(
2690         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
2691     SDLoc DL(Node);
2692     SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, DL, MVT::i32),
2693                       CurDAG->getTargetConstant(Shifter, DL, MVT::i32) };
2694     CurDAG->SelectNodeTo(Node, AArch64::ADDXri, MVT::i64, Ops);
2695     return;
2696   }
2697   case ISD::INTRINSIC_W_CHAIN: {
2698     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
2699     switch (IntNo) {
2700     default:
2701       break;
2702     case Intrinsic::aarch64_ldaxp:
2703     case Intrinsic::aarch64_ldxp: {
2704       unsigned Op =
2705           IntNo == Intrinsic::aarch64_ldaxp ? AArch64::LDAXPX : AArch64::LDXPX;
2706       SDValue MemAddr = Node->getOperand(2);
2707       SDLoc DL(Node);
2708       SDValue Chain = Node->getOperand(0);
2709 
2710       SDNode *Ld = CurDAG->getMachineNode(Op, DL, MVT::i64, MVT::i64,
2711                                           MVT::Other, MemAddr, Chain);
2712 
2713       // Transfer memoperands.
2714       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2715       MemOp[0] = cast<MemIntrinsicSDNode>(Node)->getMemOperand();
2716       cast<MachineSDNode>(Ld)->setMemRefs(MemOp, MemOp + 1);
2717       ReplaceNode(Node, Ld);
2718       return;
2719     }
2720     case Intrinsic::aarch64_stlxp:
2721     case Intrinsic::aarch64_stxp: {
2722       unsigned Op =
2723           IntNo == Intrinsic::aarch64_stlxp ? AArch64::STLXPX : AArch64::STXPX;
2724       SDLoc DL(Node);
2725       SDValue Chain = Node->getOperand(0);
2726       SDValue ValLo = Node->getOperand(2);
2727       SDValue ValHi = Node->getOperand(3);
2728       SDValue MemAddr = Node->getOperand(4);
2729 
2730       // Place arguments in the right order.
2731       SDValue Ops[] = {ValLo, ValHi, MemAddr, Chain};
2732 
2733       SDNode *St = CurDAG->getMachineNode(Op, DL, MVT::i32, MVT::Other, Ops);
2734       // Transfer memoperands.
2735       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2736       MemOp[0] = cast<MemIntrinsicSDNode>(Node)->getMemOperand();
2737       cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
2738 
2739       ReplaceNode(Node, St);
2740       return;
2741     }
2742     case Intrinsic::aarch64_neon_ld1x2:
2743       if (VT == MVT::v8i8) {
2744         SelectLoad(Node, 2, AArch64::LD1Twov8b, AArch64::dsub0);
2745         return;
2746       } else if (VT == MVT::v16i8) {
2747         SelectLoad(Node, 2, AArch64::LD1Twov16b, AArch64::qsub0);
2748         return;
2749       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2750         SelectLoad(Node, 2, AArch64::LD1Twov4h, AArch64::dsub0);
2751         return;
2752       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2753         SelectLoad(Node, 2, AArch64::LD1Twov8h, AArch64::qsub0);
2754         return;
2755       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2756         SelectLoad(Node, 2, AArch64::LD1Twov2s, AArch64::dsub0);
2757         return;
2758       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2759         SelectLoad(Node, 2, AArch64::LD1Twov4s, AArch64::qsub0);
2760         return;
2761       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2762         SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
2763         return;
2764       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2765         SelectLoad(Node, 2, AArch64::LD1Twov2d, AArch64::qsub0);
2766         return;
2767       }
2768       break;
2769     case Intrinsic::aarch64_neon_ld1x3:
2770       if (VT == MVT::v8i8) {
2771         SelectLoad(Node, 3, AArch64::LD1Threev8b, AArch64::dsub0);
2772         return;
2773       } else if (VT == MVT::v16i8) {
2774         SelectLoad(Node, 3, AArch64::LD1Threev16b, AArch64::qsub0);
2775         return;
2776       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2777         SelectLoad(Node, 3, AArch64::LD1Threev4h, AArch64::dsub0);
2778         return;
2779       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2780         SelectLoad(Node, 3, AArch64::LD1Threev8h, AArch64::qsub0);
2781         return;
2782       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2783         SelectLoad(Node, 3, AArch64::LD1Threev2s, AArch64::dsub0);
2784         return;
2785       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2786         SelectLoad(Node, 3, AArch64::LD1Threev4s, AArch64::qsub0);
2787         return;
2788       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2789         SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
2790         return;
2791       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2792         SelectLoad(Node, 3, AArch64::LD1Threev2d, AArch64::qsub0);
2793         return;
2794       }
2795       break;
2796     case Intrinsic::aarch64_neon_ld1x4:
2797       if (VT == MVT::v8i8) {
2798         SelectLoad(Node, 4, AArch64::LD1Fourv8b, AArch64::dsub0);
2799         return;
2800       } else if (VT == MVT::v16i8) {
2801         SelectLoad(Node, 4, AArch64::LD1Fourv16b, AArch64::qsub0);
2802         return;
2803       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2804         SelectLoad(Node, 4, AArch64::LD1Fourv4h, AArch64::dsub0);
2805         return;
2806       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2807         SelectLoad(Node, 4, AArch64::LD1Fourv8h, AArch64::qsub0);
2808         return;
2809       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2810         SelectLoad(Node, 4, AArch64::LD1Fourv2s, AArch64::dsub0);
2811         return;
2812       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2813         SelectLoad(Node, 4, AArch64::LD1Fourv4s, AArch64::qsub0);
2814         return;
2815       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2816         SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
2817         return;
2818       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2819         SelectLoad(Node, 4, AArch64::LD1Fourv2d, AArch64::qsub0);
2820         return;
2821       }
2822       break;
2823     case Intrinsic::aarch64_neon_ld2:
2824       if (VT == MVT::v8i8) {
2825         SelectLoad(Node, 2, AArch64::LD2Twov8b, AArch64::dsub0);
2826         return;
2827       } else if (VT == MVT::v16i8) {
2828         SelectLoad(Node, 2, AArch64::LD2Twov16b, AArch64::qsub0);
2829         return;
2830       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2831         SelectLoad(Node, 2, AArch64::LD2Twov4h, AArch64::dsub0);
2832         return;
2833       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2834         SelectLoad(Node, 2, AArch64::LD2Twov8h, AArch64::qsub0);
2835         return;
2836       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2837         SelectLoad(Node, 2, AArch64::LD2Twov2s, AArch64::dsub0);
2838         return;
2839       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2840         SelectLoad(Node, 2, AArch64::LD2Twov4s, AArch64::qsub0);
2841         return;
2842       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2843         SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
2844         return;
2845       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2846         SelectLoad(Node, 2, AArch64::LD2Twov2d, AArch64::qsub0);
2847         return;
2848       }
2849       break;
2850     case Intrinsic::aarch64_neon_ld3:
2851       if (VT == MVT::v8i8) {
2852         SelectLoad(Node, 3, AArch64::LD3Threev8b, AArch64::dsub0);
2853         return;
2854       } else if (VT == MVT::v16i8) {
2855         SelectLoad(Node, 3, AArch64::LD3Threev16b, AArch64::qsub0);
2856         return;
2857       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2858         SelectLoad(Node, 3, AArch64::LD3Threev4h, AArch64::dsub0);
2859         return;
2860       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2861         SelectLoad(Node, 3, AArch64::LD3Threev8h, AArch64::qsub0);
2862         return;
2863       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2864         SelectLoad(Node, 3, AArch64::LD3Threev2s, AArch64::dsub0);
2865         return;
2866       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2867         SelectLoad(Node, 3, AArch64::LD3Threev4s, AArch64::qsub0);
2868         return;
2869       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2870         SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
2871         return;
2872       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2873         SelectLoad(Node, 3, AArch64::LD3Threev2d, AArch64::qsub0);
2874         return;
2875       }
2876       break;
2877     case Intrinsic::aarch64_neon_ld4:
2878       if (VT == MVT::v8i8) {
2879         SelectLoad(Node, 4, AArch64::LD4Fourv8b, AArch64::dsub0);
2880         return;
2881       } else if (VT == MVT::v16i8) {
2882         SelectLoad(Node, 4, AArch64::LD4Fourv16b, AArch64::qsub0);
2883         return;
2884       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2885         SelectLoad(Node, 4, AArch64::LD4Fourv4h, AArch64::dsub0);
2886         return;
2887       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2888         SelectLoad(Node, 4, AArch64::LD4Fourv8h, AArch64::qsub0);
2889         return;
2890       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2891         SelectLoad(Node, 4, AArch64::LD4Fourv2s, AArch64::dsub0);
2892         return;
2893       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2894         SelectLoad(Node, 4, AArch64::LD4Fourv4s, AArch64::qsub0);
2895         return;
2896       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2897         SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
2898         return;
2899       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2900         SelectLoad(Node, 4, AArch64::LD4Fourv2d, AArch64::qsub0);
2901         return;
2902       }
2903       break;
2904     case Intrinsic::aarch64_neon_ld2r:
2905       if (VT == MVT::v8i8) {
2906         SelectLoad(Node, 2, AArch64::LD2Rv8b, AArch64::dsub0);
2907         return;
2908       } else if (VT == MVT::v16i8) {
2909         SelectLoad(Node, 2, AArch64::LD2Rv16b, AArch64::qsub0);
2910         return;
2911       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2912         SelectLoad(Node, 2, AArch64::LD2Rv4h, AArch64::dsub0);
2913         return;
2914       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2915         SelectLoad(Node, 2, AArch64::LD2Rv8h, AArch64::qsub0);
2916         return;
2917       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2918         SelectLoad(Node, 2, AArch64::LD2Rv2s, AArch64::dsub0);
2919         return;
2920       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2921         SelectLoad(Node, 2, AArch64::LD2Rv4s, AArch64::qsub0);
2922         return;
2923       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2924         SelectLoad(Node, 2, AArch64::LD2Rv1d, AArch64::dsub0);
2925         return;
2926       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2927         SelectLoad(Node, 2, AArch64::LD2Rv2d, AArch64::qsub0);
2928         return;
2929       }
2930       break;
2931     case Intrinsic::aarch64_neon_ld3r:
2932       if (VT == MVT::v8i8) {
2933         SelectLoad(Node, 3, AArch64::LD3Rv8b, AArch64::dsub0);
2934         return;
2935       } else if (VT == MVT::v16i8) {
2936         SelectLoad(Node, 3, AArch64::LD3Rv16b, AArch64::qsub0);
2937         return;
2938       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2939         SelectLoad(Node, 3, AArch64::LD3Rv4h, AArch64::dsub0);
2940         return;
2941       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2942         SelectLoad(Node, 3, AArch64::LD3Rv8h, AArch64::qsub0);
2943         return;
2944       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2945         SelectLoad(Node, 3, AArch64::LD3Rv2s, AArch64::dsub0);
2946         return;
2947       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2948         SelectLoad(Node, 3, AArch64::LD3Rv4s, AArch64::qsub0);
2949         return;
2950       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2951         SelectLoad(Node, 3, AArch64::LD3Rv1d, AArch64::dsub0);
2952         return;
2953       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2954         SelectLoad(Node, 3, AArch64::LD3Rv2d, AArch64::qsub0);
2955         return;
2956       }
2957       break;
2958     case Intrinsic::aarch64_neon_ld4r:
2959       if (VT == MVT::v8i8) {
2960         SelectLoad(Node, 4, AArch64::LD4Rv8b, AArch64::dsub0);
2961         return;
2962       } else if (VT == MVT::v16i8) {
2963         SelectLoad(Node, 4, AArch64::LD4Rv16b, AArch64::qsub0);
2964         return;
2965       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
2966         SelectLoad(Node, 4, AArch64::LD4Rv4h, AArch64::dsub0);
2967         return;
2968       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
2969         SelectLoad(Node, 4, AArch64::LD4Rv8h, AArch64::qsub0);
2970         return;
2971       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
2972         SelectLoad(Node, 4, AArch64::LD4Rv2s, AArch64::dsub0);
2973         return;
2974       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
2975         SelectLoad(Node, 4, AArch64::LD4Rv4s, AArch64::qsub0);
2976         return;
2977       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
2978         SelectLoad(Node, 4, AArch64::LD4Rv1d, AArch64::dsub0);
2979         return;
2980       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
2981         SelectLoad(Node, 4, AArch64::LD4Rv2d, AArch64::qsub0);
2982         return;
2983       }
2984       break;
2985     case Intrinsic::aarch64_neon_ld2lane:
2986       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
2987         SelectLoadLane(Node, 2, AArch64::LD2i8);
2988         return;
2989       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
2990                  VT == MVT::v8f16) {
2991         SelectLoadLane(Node, 2, AArch64::LD2i16);
2992         return;
2993       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
2994                  VT == MVT::v2f32) {
2995         SelectLoadLane(Node, 2, AArch64::LD2i32);
2996         return;
2997       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
2998                  VT == MVT::v1f64) {
2999         SelectLoadLane(Node, 2, AArch64::LD2i64);
3000         return;
3001       }
3002       break;
3003     case Intrinsic::aarch64_neon_ld3lane:
3004       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3005         SelectLoadLane(Node, 3, AArch64::LD3i8);
3006         return;
3007       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3008                  VT == MVT::v8f16) {
3009         SelectLoadLane(Node, 3, AArch64::LD3i16);
3010         return;
3011       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3012                  VT == MVT::v2f32) {
3013         SelectLoadLane(Node, 3, AArch64::LD3i32);
3014         return;
3015       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3016                  VT == MVT::v1f64) {
3017         SelectLoadLane(Node, 3, AArch64::LD3i64);
3018         return;
3019       }
3020       break;
3021     case Intrinsic::aarch64_neon_ld4lane:
3022       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3023         SelectLoadLane(Node, 4, AArch64::LD4i8);
3024         return;
3025       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3026                  VT == MVT::v8f16) {
3027         SelectLoadLane(Node, 4, AArch64::LD4i16);
3028         return;
3029       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3030                  VT == MVT::v2f32) {
3031         SelectLoadLane(Node, 4, AArch64::LD4i32);
3032         return;
3033       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3034                  VT == MVT::v1f64) {
3035         SelectLoadLane(Node, 4, AArch64::LD4i64);
3036         return;
3037       }
3038       break;
3039     }
3040   } break;
3041   case ISD::INTRINSIC_WO_CHAIN: {
3042     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
3043     switch (IntNo) {
3044     default:
3045       break;
3046     case Intrinsic::aarch64_neon_tbl2:
3047       SelectTable(Node, 2,
3048                   VT == MVT::v8i8 ? AArch64::TBLv8i8Two : AArch64::TBLv16i8Two,
3049                   false);
3050       return;
3051     case Intrinsic::aarch64_neon_tbl3:
3052       SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBLv8i8Three
3053                                            : AArch64::TBLv16i8Three,
3054                   false);
3055       return;
3056     case Intrinsic::aarch64_neon_tbl4:
3057       SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBLv8i8Four
3058                                            : AArch64::TBLv16i8Four,
3059                   false);
3060       return;
3061     case Intrinsic::aarch64_neon_tbx2:
3062       SelectTable(Node, 2,
3063                   VT == MVT::v8i8 ? AArch64::TBXv8i8Two : AArch64::TBXv16i8Two,
3064                   true);
3065       return;
3066     case Intrinsic::aarch64_neon_tbx3:
3067       SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBXv8i8Three
3068                                            : AArch64::TBXv16i8Three,
3069                   true);
3070       return;
3071     case Intrinsic::aarch64_neon_tbx4:
3072       SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBXv8i8Four
3073                                            : AArch64::TBXv16i8Four,
3074                   true);
3075       return;
3076     case Intrinsic::aarch64_neon_smull:
3077     case Intrinsic::aarch64_neon_umull:
3078       if (tryMULLV64LaneV128(IntNo, Node))
3079         return;
3080       break;
3081     }
3082     break;
3083   }
3084   case ISD::INTRINSIC_VOID: {
3085     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
3086     if (Node->getNumOperands() >= 3)
3087       VT = Node->getOperand(2)->getValueType(0);
3088     switch (IntNo) {
3089     default:
3090       break;
3091     case Intrinsic::aarch64_neon_st1x2: {
3092       if (VT == MVT::v8i8) {
3093         SelectStore(Node, 2, AArch64::ST1Twov8b);
3094         return;
3095       } else if (VT == MVT::v16i8) {
3096         SelectStore(Node, 2, AArch64::ST1Twov16b);
3097         return;
3098       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3099         SelectStore(Node, 2, AArch64::ST1Twov4h);
3100         return;
3101       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3102         SelectStore(Node, 2, AArch64::ST1Twov8h);
3103         return;
3104       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3105         SelectStore(Node, 2, AArch64::ST1Twov2s);
3106         return;
3107       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3108         SelectStore(Node, 2, AArch64::ST1Twov4s);
3109         return;
3110       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3111         SelectStore(Node, 2, AArch64::ST1Twov2d);
3112         return;
3113       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3114         SelectStore(Node, 2, AArch64::ST1Twov1d);
3115         return;
3116       }
3117       break;
3118     }
3119     case Intrinsic::aarch64_neon_st1x3: {
3120       if (VT == MVT::v8i8) {
3121         SelectStore(Node, 3, AArch64::ST1Threev8b);
3122         return;
3123       } else if (VT == MVT::v16i8) {
3124         SelectStore(Node, 3, AArch64::ST1Threev16b);
3125         return;
3126       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3127         SelectStore(Node, 3, AArch64::ST1Threev4h);
3128         return;
3129       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3130         SelectStore(Node, 3, AArch64::ST1Threev8h);
3131         return;
3132       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3133         SelectStore(Node, 3, AArch64::ST1Threev2s);
3134         return;
3135       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3136         SelectStore(Node, 3, AArch64::ST1Threev4s);
3137         return;
3138       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3139         SelectStore(Node, 3, AArch64::ST1Threev2d);
3140         return;
3141       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3142         SelectStore(Node, 3, AArch64::ST1Threev1d);
3143         return;
3144       }
3145       break;
3146     }
3147     case Intrinsic::aarch64_neon_st1x4: {
3148       if (VT == MVT::v8i8) {
3149         SelectStore(Node, 4, AArch64::ST1Fourv8b);
3150         return;
3151       } else if (VT == MVT::v16i8) {
3152         SelectStore(Node, 4, AArch64::ST1Fourv16b);
3153         return;
3154       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3155         SelectStore(Node, 4, AArch64::ST1Fourv4h);
3156         return;
3157       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3158         SelectStore(Node, 4, AArch64::ST1Fourv8h);
3159         return;
3160       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3161         SelectStore(Node, 4, AArch64::ST1Fourv2s);
3162         return;
3163       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3164         SelectStore(Node, 4, AArch64::ST1Fourv4s);
3165         return;
3166       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3167         SelectStore(Node, 4, AArch64::ST1Fourv2d);
3168         return;
3169       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3170         SelectStore(Node, 4, AArch64::ST1Fourv1d);
3171         return;
3172       }
3173       break;
3174     }
3175     case Intrinsic::aarch64_neon_st2: {
3176       if (VT == MVT::v8i8) {
3177         SelectStore(Node, 2, AArch64::ST2Twov8b);
3178         return;
3179       } else if (VT == MVT::v16i8) {
3180         SelectStore(Node, 2, AArch64::ST2Twov16b);
3181         return;
3182       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3183         SelectStore(Node, 2, AArch64::ST2Twov4h);
3184         return;
3185       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3186         SelectStore(Node, 2, AArch64::ST2Twov8h);
3187         return;
3188       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3189         SelectStore(Node, 2, AArch64::ST2Twov2s);
3190         return;
3191       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3192         SelectStore(Node, 2, AArch64::ST2Twov4s);
3193         return;
3194       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3195         SelectStore(Node, 2, AArch64::ST2Twov2d);
3196         return;
3197       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3198         SelectStore(Node, 2, AArch64::ST1Twov1d);
3199         return;
3200       }
3201       break;
3202     }
3203     case Intrinsic::aarch64_neon_st3: {
3204       if (VT == MVT::v8i8) {
3205         SelectStore(Node, 3, AArch64::ST3Threev8b);
3206         return;
3207       } else if (VT == MVT::v16i8) {
3208         SelectStore(Node, 3, AArch64::ST3Threev16b);
3209         return;
3210       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3211         SelectStore(Node, 3, AArch64::ST3Threev4h);
3212         return;
3213       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3214         SelectStore(Node, 3, AArch64::ST3Threev8h);
3215         return;
3216       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3217         SelectStore(Node, 3, AArch64::ST3Threev2s);
3218         return;
3219       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3220         SelectStore(Node, 3, AArch64::ST3Threev4s);
3221         return;
3222       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3223         SelectStore(Node, 3, AArch64::ST3Threev2d);
3224         return;
3225       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3226         SelectStore(Node, 3, AArch64::ST1Threev1d);
3227         return;
3228       }
3229       break;
3230     }
3231     case Intrinsic::aarch64_neon_st4: {
3232       if (VT == MVT::v8i8) {
3233         SelectStore(Node, 4, AArch64::ST4Fourv8b);
3234         return;
3235       } else if (VT == MVT::v16i8) {
3236         SelectStore(Node, 4, AArch64::ST4Fourv16b);
3237         return;
3238       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3239         SelectStore(Node, 4, AArch64::ST4Fourv4h);
3240         return;
3241       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3242         SelectStore(Node, 4, AArch64::ST4Fourv8h);
3243         return;
3244       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3245         SelectStore(Node, 4, AArch64::ST4Fourv2s);
3246         return;
3247       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3248         SelectStore(Node, 4, AArch64::ST4Fourv4s);
3249         return;
3250       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3251         SelectStore(Node, 4, AArch64::ST4Fourv2d);
3252         return;
3253       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3254         SelectStore(Node, 4, AArch64::ST1Fourv1d);
3255         return;
3256       }
3257       break;
3258     }
3259     case Intrinsic::aarch64_neon_st2lane: {
3260       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3261         SelectStoreLane(Node, 2, AArch64::ST2i8);
3262         return;
3263       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3264                  VT == MVT::v8f16) {
3265         SelectStoreLane(Node, 2, AArch64::ST2i16);
3266         return;
3267       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3268                  VT == MVT::v2f32) {
3269         SelectStoreLane(Node, 2, AArch64::ST2i32);
3270         return;
3271       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3272                  VT == MVT::v1f64) {
3273         SelectStoreLane(Node, 2, AArch64::ST2i64);
3274         return;
3275       }
3276       break;
3277     }
3278     case Intrinsic::aarch64_neon_st3lane: {
3279       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3280         SelectStoreLane(Node, 3, AArch64::ST3i8);
3281         return;
3282       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3283                  VT == MVT::v8f16) {
3284         SelectStoreLane(Node, 3, AArch64::ST3i16);
3285         return;
3286       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3287                  VT == MVT::v2f32) {
3288         SelectStoreLane(Node, 3, AArch64::ST3i32);
3289         return;
3290       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3291                  VT == MVT::v1f64) {
3292         SelectStoreLane(Node, 3, AArch64::ST3i64);
3293         return;
3294       }
3295       break;
3296     }
3297     case Intrinsic::aarch64_neon_st4lane: {
3298       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3299         SelectStoreLane(Node, 4, AArch64::ST4i8);
3300         return;
3301       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3302                  VT == MVT::v8f16) {
3303         SelectStoreLane(Node, 4, AArch64::ST4i16);
3304         return;
3305       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3306                  VT == MVT::v2f32) {
3307         SelectStoreLane(Node, 4, AArch64::ST4i32);
3308         return;
3309       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3310                  VT == MVT::v1f64) {
3311         SelectStoreLane(Node, 4, AArch64::ST4i64);
3312         return;
3313       }
3314       break;
3315     }
3316     }
3317     break;
3318   }
3319   case AArch64ISD::LD2post: {
3320     if (VT == MVT::v8i8) {
3321       SelectPostLoad(Node, 2, AArch64::LD2Twov8b_POST, AArch64::dsub0);
3322       return;
3323     } else if (VT == MVT::v16i8) {
3324       SelectPostLoad(Node, 2, AArch64::LD2Twov16b_POST, AArch64::qsub0);
3325       return;
3326     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3327       SelectPostLoad(Node, 2, AArch64::LD2Twov4h_POST, AArch64::dsub0);
3328       return;
3329     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3330       SelectPostLoad(Node, 2, AArch64::LD2Twov8h_POST, AArch64::qsub0);
3331       return;
3332     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3333       SelectPostLoad(Node, 2, AArch64::LD2Twov2s_POST, AArch64::dsub0);
3334       return;
3335     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3336       SelectPostLoad(Node, 2, AArch64::LD2Twov4s_POST, AArch64::qsub0);
3337       return;
3338     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3339       SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
3340       return;
3341     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3342       SelectPostLoad(Node, 2, AArch64::LD2Twov2d_POST, AArch64::qsub0);
3343       return;
3344     }
3345     break;
3346   }
3347   case AArch64ISD::LD3post: {
3348     if (VT == MVT::v8i8) {
3349       SelectPostLoad(Node, 3, AArch64::LD3Threev8b_POST, AArch64::dsub0);
3350       return;
3351     } else if (VT == MVT::v16i8) {
3352       SelectPostLoad(Node, 3, AArch64::LD3Threev16b_POST, AArch64::qsub0);
3353       return;
3354     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3355       SelectPostLoad(Node, 3, AArch64::LD3Threev4h_POST, AArch64::dsub0);
3356       return;
3357     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3358       SelectPostLoad(Node, 3, AArch64::LD3Threev8h_POST, AArch64::qsub0);
3359       return;
3360     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3361       SelectPostLoad(Node, 3, AArch64::LD3Threev2s_POST, AArch64::dsub0);
3362       return;
3363     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3364       SelectPostLoad(Node, 3, AArch64::LD3Threev4s_POST, AArch64::qsub0);
3365       return;
3366     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3367       SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
3368       return;
3369     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3370       SelectPostLoad(Node, 3, AArch64::LD3Threev2d_POST, AArch64::qsub0);
3371       return;
3372     }
3373     break;
3374   }
3375   case AArch64ISD::LD4post: {
3376     if (VT == MVT::v8i8) {
3377       SelectPostLoad(Node, 4, AArch64::LD4Fourv8b_POST, AArch64::dsub0);
3378       return;
3379     } else if (VT == MVT::v16i8) {
3380       SelectPostLoad(Node, 4, AArch64::LD4Fourv16b_POST, AArch64::qsub0);
3381       return;
3382     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3383       SelectPostLoad(Node, 4, AArch64::LD4Fourv4h_POST, AArch64::dsub0);
3384       return;
3385     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3386       SelectPostLoad(Node, 4, AArch64::LD4Fourv8h_POST, AArch64::qsub0);
3387       return;
3388     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3389       SelectPostLoad(Node, 4, AArch64::LD4Fourv2s_POST, AArch64::dsub0);
3390       return;
3391     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3392       SelectPostLoad(Node, 4, AArch64::LD4Fourv4s_POST, AArch64::qsub0);
3393       return;
3394     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3395       SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
3396       return;
3397     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3398       SelectPostLoad(Node, 4, AArch64::LD4Fourv2d_POST, AArch64::qsub0);
3399       return;
3400     }
3401     break;
3402   }
3403   case AArch64ISD::LD1x2post: {
3404     if (VT == MVT::v8i8) {
3405       SelectPostLoad(Node, 2, AArch64::LD1Twov8b_POST, AArch64::dsub0);
3406       return;
3407     } else if (VT == MVT::v16i8) {
3408       SelectPostLoad(Node, 2, AArch64::LD1Twov16b_POST, AArch64::qsub0);
3409       return;
3410     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3411       SelectPostLoad(Node, 2, AArch64::LD1Twov4h_POST, AArch64::dsub0);
3412       return;
3413     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3414       SelectPostLoad(Node, 2, AArch64::LD1Twov8h_POST, AArch64::qsub0);
3415       return;
3416     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3417       SelectPostLoad(Node, 2, AArch64::LD1Twov2s_POST, AArch64::dsub0);
3418       return;
3419     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3420       SelectPostLoad(Node, 2, AArch64::LD1Twov4s_POST, AArch64::qsub0);
3421       return;
3422     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3423       SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
3424       return;
3425     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3426       SelectPostLoad(Node, 2, AArch64::LD1Twov2d_POST, AArch64::qsub0);
3427       return;
3428     }
3429     break;
3430   }
3431   case AArch64ISD::LD1x3post: {
3432     if (VT == MVT::v8i8) {
3433       SelectPostLoad(Node, 3, AArch64::LD1Threev8b_POST, AArch64::dsub0);
3434       return;
3435     } else if (VT == MVT::v16i8) {
3436       SelectPostLoad(Node, 3, AArch64::LD1Threev16b_POST, AArch64::qsub0);
3437       return;
3438     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3439       SelectPostLoad(Node, 3, AArch64::LD1Threev4h_POST, AArch64::dsub0);
3440       return;
3441     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3442       SelectPostLoad(Node, 3, AArch64::LD1Threev8h_POST, AArch64::qsub0);
3443       return;
3444     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3445       SelectPostLoad(Node, 3, AArch64::LD1Threev2s_POST, AArch64::dsub0);
3446       return;
3447     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3448       SelectPostLoad(Node, 3, AArch64::LD1Threev4s_POST, AArch64::qsub0);
3449       return;
3450     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3451       SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
3452       return;
3453     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3454       SelectPostLoad(Node, 3, AArch64::LD1Threev2d_POST, AArch64::qsub0);
3455       return;
3456     }
3457     break;
3458   }
3459   case AArch64ISD::LD1x4post: {
3460     if (VT == MVT::v8i8) {
3461       SelectPostLoad(Node, 4, AArch64::LD1Fourv8b_POST, AArch64::dsub0);
3462       return;
3463     } else if (VT == MVT::v16i8) {
3464       SelectPostLoad(Node, 4, AArch64::LD1Fourv16b_POST, AArch64::qsub0);
3465       return;
3466     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3467       SelectPostLoad(Node, 4, AArch64::LD1Fourv4h_POST, AArch64::dsub0);
3468       return;
3469     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3470       SelectPostLoad(Node, 4, AArch64::LD1Fourv8h_POST, AArch64::qsub0);
3471       return;
3472     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3473       SelectPostLoad(Node, 4, AArch64::LD1Fourv2s_POST, AArch64::dsub0);
3474       return;
3475     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3476       SelectPostLoad(Node, 4, AArch64::LD1Fourv4s_POST, AArch64::qsub0);
3477       return;
3478     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3479       SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
3480       return;
3481     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3482       SelectPostLoad(Node, 4, AArch64::LD1Fourv2d_POST, AArch64::qsub0);
3483       return;
3484     }
3485     break;
3486   }
3487   case AArch64ISD::LD1DUPpost: {
3488     if (VT == MVT::v8i8) {
3489       SelectPostLoad(Node, 1, AArch64::LD1Rv8b_POST, AArch64::dsub0);
3490       return;
3491     } else if (VT == MVT::v16i8) {
3492       SelectPostLoad(Node, 1, AArch64::LD1Rv16b_POST, AArch64::qsub0);
3493       return;
3494     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3495       SelectPostLoad(Node, 1, AArch64::LD1Rv4h_POST, AArch64::dsub0);
3496       return;
3497     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3498       SelectPostLoad(Node, 1, AArch64::LD1Rv8h_POST, AArch64::qsub0);
3499       return;
3500     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3501       SelectPostLoad(Node, 1, AArch64::LD1Rv2s_POST, AArch64::dsub0);
3502       return;
3503     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3504       SelectPostLoad(Node, 1, AArch64::LD1Rv4s_POST, AArch64::qsub0);
3505       return;
3506     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3507       SelectPostLoad(Node, 1, AArch64::LD1Rv1d_POST, AArch64::dsub0);
3508       return;
3509     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3510       SelectPostLoad(Node, 1, AArch64::LD1Rv2d_POST, AArch64::qsub0);
3511       return;
3512     }
3513     break;
3514   }
3515   case AArch64ISD::LD2DUPpost: {
3516     if (VT == MVT::v8i8) {
3517       SelectPostLoad(Node, 2, AArch64::LD2Rv8b_POST, AArch64::dsub0);
3518       return;
3519     } else if (VT == MVT::v16i8) {
3520       SelectPostLoad(Node, 2, AArch64::LD2Rv16b_POST, AArch64::qsub0);
3521       return;
3522     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3523       SelectPostLoad(Node, 2, AArch64::LD2Rv4h_POST, AArch64::dsub0);
3524       return;
3525     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3526       SelectPostLoad(Node, 2, AArch64::LD2Rv8h_POST, AArch64::qsub0);
3527       return;
3528     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3529       SelectPostLoad(Node, 2, AArch64::LD2Rv2s_POST, AArch64::dsub0);
3530       return;
3531     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3532       SelectPostLoad(Node, 2, AArch64::LD2Rv4s_POST, AArch64::qsub0);
3533       return;
3534     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3535       SelectPostLoad(Node, 2, AArch64::LD2Rv1d_POST, AArch64::dsub0);
3536       return;
3537     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3538       SelectPostLoad(Node, 2, AArch64::LD2Rv2d_POST, AArch64::qsub0);
3539       return;
3540     }
3541     break;
3542   }
3543   case AArch64ISD::LD3DUPpost: {
3544     if (VT == MVT::v8i8) {
3545       SelectPostLoad(Node, 3, AArch64::LD3Rv8b_POST, AArch64::dsub0);
3546       return;
3547     } else if (VT == MVT::v16i8) {
3548       SelectPostLoad(Node, 3, AArch64::LD3Rv16b_POST, AArch64::qsub0);
3549       return;
3550     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3551       SelectPostLoad(Node, 3, AArch64::LD3Rv4h_POST, AArch64::dsub0);
3552       return;
3553     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3554       SelectPostLoad(Node, 3, AArch64::LD3Rv8h_POST, AArch64::qsub0);
3555       return;
3556     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3557       SelectPostLoad(Node, 3, AArch64::LD3Rv2s_POST, AArch64::dsub0);
3558       return;
3559     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3560       SelectPostLoad(Node, 3, AArch64::LD3Rv4s_POST, AArch64::qsub0);
3561       return;
3562     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3563       SelectPostLoad(Node, 3, AArch64::LD3Rv1d_POST, AArch64::dsub0);
3564       return;
3565     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3566       SelectPostLoad(Node, 3, AArch64::LD3Rv2d_POST, AArch64::qsub0);
3567       return;
3568     }
3569     break;
3570   }
3571   case AArch64ISD::LD4DUPpost: {
3572     if (VT == MVT::v8i8) {
3573       SelectPostLoad(Node, 4, AArch64::LD4Rv8b_POST, AArch64::dsub0);
3574       return;
3575     } else if (VT == MVT::v16i8) {
3576       SelectPostLoad(Node, 4, AArch64::LD4Rv16b_POST, AArch64::qsub0);
3577       return;
3578     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3579       SelectPostLoad(Node, 4, AArch64::LD4Rv4h_POST, AArch64::dsub0);
3580       return;
3581     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3582       SelectPostLoad(Node, 4, AArch64::LD4Rv8h_POST, AArch64::qsub0);
3583       return;
3584     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3585       SelectPostLoad(Node, 4, AArch64::LD4Rv2s_POST, AArch64::dsub0);
3586       return;
3587     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3588       SelectPostLoad(Node, 4, AArch64::LD4Rv4s_POST, AArch64::qsub0);
3589       return;
3590     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3591       SelectPostLoad(Node, 4, AArch64::LD4Rv1d_POST, AArch64::dsub0);
3592       return;
3593     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3594       SelectPostLoad(Node, 4, AArch64::LD4Rv2d_POST, AArch64::qsub0);
3595       return;
3596     }
3597     break;
3598   }
3599   case AArch64ISD::LD1LANEpost: {
3600     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3601       SelectPostLoadLane(Node, 1, AArch64::LD1i8_POST);
3602       return;
3603     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3604                VT == MVT::v8f16) {
3605       SelectPostLoadLane(Node, 1, AArch64::LD1i16_POST);
3606       return;
3607     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3608                VT == MVT::v2f32) {
3609       SelectPostLoadLane(Node, 1, AArch64::LD1i32_POST);
3610       return;
3611     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3612                VT == MVT::v1f64) {
3613       SelectPostLoadLane(Node, 1, AArch64::LD1i64_POST);
3614       return;
3615     }
3616     break;
3617   }
3618   case AArch64ISD::LD2LANEpost: {
3619     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3620       SelectPostLoadLane(Node, 2, AArch64::LD2i8_POST);
3621       return;
3622     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3623                VT == MVT::v8f16) {
3624       SelectPostLoadLane(Node, 2, AArch64::LD2i16_POST);
3625       return;
3626     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3627                VT == MVT::v2f32) {
3628       SelectPostLoadLane(Node, 2, AArch64::LD2i32_POST);
3629       return;
3630     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3631                VT == MVT::v1f64) {
3632       SelectPostLoadLane(Node, 2, AArch64::LD2i64_POST);
3633       return;
3634     }
3635     break;
3636   }
3637   case AArch64ISD::LD3LANEpost: {
3638     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3639       SelectPostLoadLane(Node, 3, AArch64::LD3i8_POST);
3640       return;
3641     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3642                VT == MVT::v8f16) {
3643       SelectPostLoadLane(Node, 3, AArch64::LD3i16_POST);
3644       return;
3645     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3646                VT == MVT::v2f32) {
3647       SelectPostLoadLane(Node, 3, AArch64::LD3i32_POST);
3648       return;
3649     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3650                VT == MVT::v1f64) {
3651       SelectPostLoadLane(Node, 3, AArch64::LD3i64_POST);
3652       return;
3653     }
3654     break;
3655   }
3656   case AArch64ISD::LD4LANEpost: {
3657     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3658       SelectPostLoadLane(Node, 4, AArch64::LD4i8_POST);
3659       return;
3660     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3661                VT == MVT::v8f16) {
3662       SelectPostLoadLane(Node, 4, AArch64::LD4i16_POST);
3663       return;
3664     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3665                VT == MVT::v2f32) {
3666       SelectPostLoadLane(Node, 4, AArch64::LD4i32_POST);
3667       return;
3668     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3669                VT == MVT::v1f64) {
3670       SelectPostLoadLane(Node, 4, AArch64::LD4i64_POST);
3671       return;
3672     }
3673     break;
3674   }
3675   case AArch64ISD::ST2post: {
3676     VT = Node->getOperand(1).getValueType();
3677     if (VT == MVT::v8i8) {
3678       SelectPostStore(Node, 2, AArch64::ST2Twov8b_POST);
3679       return;
3680     } else if (VT == MVT::v16i8) {
3681       SelectPostStore(Node, 2, AArch64::ST2Twov16b_POST);
3682       return;
3683     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3684       SelectPostStore(Node, 2, AArch64::ST2Twov4h_POST);
3685       return;
3686     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3687       SelectPostStore(Node, 2, AArch64::ST2Twov8h_POST);
3688       return;
3689     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3690       SelectPostStore(Node, 2, AArch64::ST2Twov2s_POST);
3691       return;
3692     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3693       SelectPostStore(Node, 2, AArch64::ST2Twov4s_POST);
3694       return;
3695     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3696       SelectPostStore(Node, 2, AArch64::ST2Twov2d_POST);
3697       return;
3698     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3699       SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
3700       return;
3701     }
3702     break;
3703   }
3704   case AArch64ISD::ST3post: {
3705     VT = Node->getOperand(1).getValueType();
3706     if (VT == MVT::v8i8) {
3707       SelectPostStore(Node, 3, AArch64::ST3Threev8b_POST);
3708       return;
3709     } else if (VT == MVT::v16i8) {
3710       SelectPostStore(Node, 3, AArch64::ST3Threev16b_POST);
3711       return;
3712     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3713       SelectPostStore(Node, 3, AArch64::ST3Threev4h_POST);
3714       return;
3715     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3716       SelectPostStore(Node, 3, AArch64::ST3Threev8h_POST);
3717       return;
3718     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3719       SelectPostStore(Node, 3, AArch64::ST3Threev2s_POST);
3720       return;
3721     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3722       SelectPostStore(Node, 3, AArch64::ST3Threev4s_POST);
3723       return;
3724     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3725       SelectPostStore(Node, 3, AArch64::ST3Threev2d_POST);
3726       return;
3727     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3728       SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
3729       return;
3730     }
3731     break;
3732   }
3733   case AArch64ISD::ST4post: {
3734     VT = Node->getOperand(1).getValueType();
3735     if (VT == MVT::v8i8) {
3736       SelectPostStore(Node, 4, AArch64::ST4Fourv8b_POST);
3737       return;
3738     } else if (VT == MVT::v16i8) {
3739       SelectPostStore(Node, 4, AArch64::ST4Fourv16b_POST);
3740       return;
3741     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3742       SelectPostStore(Node, 4, AArch64::ST4Fourv4h_POST);
3743       return;
3744     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3745       SelectPostStore(Node, 4, AArch64::ST4Fourv8h_POST);
3746       return;
3747     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3748       SelectPostStore(Node, 4, AArch64::ST4Fourv2s_POST);
3749       return;
3750     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3751       SelectPostStore(Node, 4, AArch64::ST4Fourv4s_POST);
3752       return;
3753     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3754       SelectPostStore(Node, 4, AArch64::ST4Fourv2d_POST);
3755       return;
3756     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3757       SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
3758       return;
3759     }
3760     break;
3761   }
3762   case AArch64ISD::ST1x2post: {
3763     VT = Node->getOperand(1).getValueType();
3764     if (VT == MVT::v8i8) {
3765       SelectPostStore(Node, 2, AArch64::ST1Twov8b_POST);
3766       return;
3767     } else if (VT == MVT::v16i8) {
3768       SelectPostStore(Node, 2, AArch64::ST1Twov16b_POST);
3769       return;
3770     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3771       SelectPostStore(Node, 2, AArch64::ST1Twov4h_POST);
3772       return;
3773     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3774       SelectPostStore(Node, 2, AArch64::ST1Twov8h_POST);
3775       return;
3776     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3777       SelectPostStore(Node, 2, AArch64::ST1Twov2s_POST);
3778       return;
3779     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3780       SelectPostStore(Node, 2, AArch64::ST1Twov4s_POST);
3781       return;
3782     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3783       SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
3784       return;
3785     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3786       SelectPostStore(Node, 2, AArch64::ST1Twov2d_POST);
3787       return;
3788     }
3789     break;
3790   }
3791   case AArch64ISD::ST1x3post: {
3792     VT = Node->getOperand(1).getValueType();
3793     if (VT == MVT::v8i8) {
3794       SelectPostStore(Node, 3, AArch64::ST1Threev8b_POST);
3795       return;
3796     } else if (VT == MVT::v16i8) {
3797       SelectPostStore(Node, 3, AArch64::ST1Threev16b_POST);
3798       return;
3799     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3800       SelectPostStore(Node, 3, AArch64::ST1Threev4h_POST);
3801       return;
3802     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3803       SelectPostStore(Node, 3, AArch64::ST1Threev8h_POST);
3804       return;
3805     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3806       SelectPostStore(Node, 3, AArch64::ST1Threev2s_POST);
3807       return;
3808     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3809       SelectPostStore(Node, 3, AArch64::ST1Threev4s_POST);
3810       return;
3811     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3812       SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
3813       return;
3814     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3815       SelectPostStore(Node, 3, AArch64::ST1Threev2d_POST);
3816       return;
3817     }
3818     break;
3819   }
3820   case AArch64ISD::ST1x4post: {
3821     VT = Node->getOperand(1).getValueType();
3822     if (VT == MVT::v8i8) {
3823       SelectPostStore(Node, 4, AArch64::ST1Fourv8b_POST);
3824       return;
3825     } else if (VT == MVT::v16i8) {
3826       SelectPostStore(Node, 4, AArch64::ST1Fourv16b_POST);
3827       return;
3828     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3829       SelectPostStore(Node, 4, AArch64::ST1Fourv4h_POST);
3830       return;
3831     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3832       SelectPostStore(Node, 4, AArch64::ST1Fourv8h_POST);
3833       return;
3834     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3835       SelectPostStore(Node, 4, AArch64::ST1Fourv2s_POST);
3836       return;
3837     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3838       SelectPostStore(Node, 4, AArch64::ST1Fourv4s_POST);
3839       return;
3840     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3841       SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
3842       return;
3843     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3844       SelectPostStore(Node, 4, AArch64::ST1Fourv2d_POST);
3845       return;
3846     }
3847     break;
3848   }
3849   case AArch64ISD::ST2LANEpost: {
3850     VT = Node->getOperand(1).getValueType();
3851     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3852       SelectPostStoreLane(Node, 2, AArch64::ST2i8_POST);
3853       return;
3854     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3855                VT == MVT::v8f16) {
3856       SelectPostStoreLane(Node, 2, AArch64::ST2i16_POST);
3857       return;
3858     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3859                VT == MVT::v2f32) {
3860       SelectPostStoreLane(Node, 2, AArch64::ST2i32_POST);
3861       return;
3862     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3863                VT == MVT::v1f64) {
3864       SelectPostStoreLane(Node, 2, AArch64::ST2i64_POST);
3865       return;
3866     }
3867     break;
3868   }
3869   case AArch64ISD::ST3LANEpost: {
3870     VT = Node->getOperand(1).getValueType();
3871     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3872       SelectPostStoreLane(Node, 3, AArch64::ST3i8_POST);
3873       return;
3874     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3875                VT == MVT::v8f16) {
3876       SelectPostStoreLane(Node, 3, AArch64::ST3i16_POST);
3877       return;
3878     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3879                VT == MVT::v2f32) {
3880       SelectPostStoreLane(Node, 3, AArch64::ST3i32_POST);
3881       return;
3882     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3883                VT == MVT::v1f64) {
3884       SelectPostStoreLane(Node, 3, AArch64::ST3i64_POST);
3885       return;
3886     }
3887     break;
3888   }
3889   case AArch64ISD::ST4LANEpost: {
3890     VT = Node->getOperand(1).getValueType();
3891     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3892       SelectPostStoreLane(Node, 4, AArch64::ST4i8_POST);
3893       return;
3894     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3895                VT == MVT::v8f16) {
3896       SelectPostStoreLane(Node, 4, AArch64::ST4i16_POST);
3897       return;
3898     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3899                VT == MVT::v2f32) {
3900       SelectPostStoreLane(Node, 4, AArch64::ST4i32_POST);
3901       return;
3902     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3903                VT == MVT::v1f64) {
3904       SelectPostStoreLane(Node, 4, AArch64::ST4i64_POST);
3905       return;
3906     }
3907     break;
3908   }
3909   }
3910 
3911   // Select the default instruction
3912   SelectCode(Node);
3913 }
3914 
3915 /// createAArch64ISelDag - This pass converts a legalized DAG into a
3916 /// AArch64-specific DAG, ready for instruction scheduling.
3917 FunctionPass *llvm::createAArch64ISelDag(AArch64TargetMachine &TM,
3918                                          CodeGenOpt::Level OptLevel) {
3919   return new AArch64DAGToDAGISel(TM, OptLevel);
3920 }
3921