1 //===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines an instruction selector for the ARM target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ARM.h"
14 #include "ARMBaseInstrInfo.h"
15 #include "ARMTargetMachine.h"
16 #include "MCTargetDesc/ARMAddressingModes.h"
17 #include "Utils/ARMBaseInfo.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/CodeGen/TargetLowering.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicsARM.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Target/TargetOptions.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "arm-isel"
42 
43 static cl::opt<bool>
44 DisableShifterOp("disable-shifter-op", cl::Hidden,
45   cl::desc("Disable isel of shifter-op"),
46   cl::init(false));
47 
48 //===--------------------------------------------------------------------===//
49 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
50 /// instructions for SelectionDAG operations.
51 ///
52 namespace {
53 
54 class ARMDAGToDAGISel : public SelectionDAGISel {
55   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
56   /// make the right decision when generating code for different targets.
57   const ARMSubtarget *Subtarget;
58 
59 public:
60   explicit ARMDAGToDAGISel(ARMBaseTargetMachine &tm, CodeGenOpt::Level OptLevel)
61       : SelectionDAGISel(tm, OptLevel) {}
62 
63   bool runOnMachineFunction(MachineFunction &MF) override {
64     // Reset the subtarget each time through.
65     Subtarget = &MF.getSubtarget<ARMSubtarget>();
66     SelectionDAGISel::runOnMachineFunction(MF);
67     return true;
68   }
69 
70   StringRef getPassName() const override { return "ARM Instruction Selection"; }
71 
72   void PreprocessISelDAG() override;
73 
74   /// getI32Imm - Return a target constant of type i32 with the specified
75   /// value.
76   inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
77     return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
78   }
79 
80   void Select(SDNode *N) override;
81 
82   /// Return true as some complex patterns, like those that call
83   /// canExtractShiftFromMul can modify the DAG inplace.
84   bool ComplexPatternFuncMutatesDAG() const override { return true; }
85 
86   bool hasNoVMLxHazardUse(SDNode *N) const;
87   bool isShifterOpProfitable(const SDValue &Shift,
88                              ARM_AM::ShiftOpc ShOpcVal, unsigned ShAmt);
89   bool SelectRegShifterOperand(SDValue N, SDValue &A,
90                                SDValue &B, SDValue &C,
91                                bool CheckProfitability = true);
92   bool SelectImmShifterOperand(SDValue N, SDValue &A,
93                                SDValue &B, bool CheckProfitability = true);
94   bool SelectShiftRegShifterOperand(SDValue N, SDValue &A, SDValue &B,
95                                     SDValue &C) {
96     // Don't apply the profitability check
97     return SelectRegShifterOperand(N, A, B, C, false);
98   }
99   bool SelectShiftImmShifterOperand(SDValue N, SDValue &A, SDValue &B) {
100     // Don't apply the profitability check
101     return SelectImmShifterOperand(N, A, B, false);
102   }
103   bool SelectShiftImmShifterOperandOneUse(SDValue N, SDValue &A, SDValue &B) {
104     if (!N.hasOneUse())
105       return false;
106     return SelectImmShifterOperand(N, A, B, false);
107   }
108 
109   bool SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out);
110 
111   bool SelectAddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
112   bool SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset, SDValue &Opc);
113 
114   bool SelectCMOVPred(SDValue N, SDValue &Pred, SDValue &Reg) {
115     const ConstantSDNode *CN = cast<ConstantSDNode>(N);
116     Pred = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);
117     Reg = CurDAG->getRegister(ARM::CPSR, MVT::i32);
118     return true;
119   }
120 
121   bool SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
122                              SDValue &Offset, SDValue &Opc);
123   bool SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
124                              SDValue &Offset, SDValue &Opc);
125   bool SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
126                              SDValue &Offset, SDValue &Opc);
127   bool SelectAddrOffsetNone(SDValue N, SDValue &Base);
128   bool SelectAddrMode3(SDValue N, SDValue &Base,
129                        SDValue &Offset, SDValue &Opc);
130   bool SelectAddrMode3Offset(SDNode *Op, SDValue N,
131                              SDValue &Offset, SDValue &Opc);
132   bool IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset, bool FP16);
133   bool SelectAddrMode5(SDValue N, SDValue &Base, SDValue &Offset);
134   bool SelectAddrMode5FP16(SDValue N, SDValue &Base, SDValue &Offset);
135   bool SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,SDValue &Align);
136   bool SelectAddrMode6Offset(SDNode *Op, SDValue N, SDValue &Offset);
137 
138   bool SelectAddrModePC(SDValue N, SDValue &Offset, SDValue &Label);
139 
140   // Thumb Addressing Modes:
141   bool SelectThumbAddrModeRR(SDValue N, SDValue &Base, SDValue &Offset);
142   bool SelectThumbAddrModeRRSext(SDValue N, SDValue &Base, SDValue &Offset);
143   bool SelectThumbAddrModeImm5S(SDValue N, unsigned Scale, SDValue &Base,
144                                 SDValue &OffImm);
145   bool SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
146                                  SDValue &OffImm);
147   bool SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
148                                  SDValue &OffImm);
149   bool SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
150                                  SDValue &OffImm);
151   bool SelectThumbAddrModeSP(SDValue N, SDValue &Base, SDValue &OffImm);
152   template <unsigned Shift>
153   bool SelectTAddrModeImm7(SDValue N, SDValue &Base, SDValue &OffImm);
154 
155   // Thumb 2 Addressing Modes:
156   bool SelectT2AddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
157   template <unsigned Shift>
158   bool SelectT2AddrModeImm8(SDValue N, SDValue &Base, SDValue &OffImm);
159   bool SelectT2AddrModeImm8(SDValue N, SDValue &Base,
160                             SDValue &OffImm);
161   bool SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
162                                  SDValue &OffImm);
163   template <unsigned Shift>
164   bool SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N, SDValue &OffImm);
165   bool SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N, SDValue &OffImm,
166                                   unsigned Shift);
167   template <unsigned Shift>
168   bool SelectT2AddrModeImm7(SDValue N, SDValue &Base, SDValue &OffImm);
169   bool SelectT2AddrModeSoReg(SDValue N, SDValue &Base,
170                              SDValue &OffReg, SDValue &ShImm);
171   bool SelectT2AddrModeExclusive(SDValue N, SDValue &Base, SDValue &OffImm);
172 
173   template<int Min, int Max>
174   bool SelectImmediateInRange(SDValue N, SDValue &OffImm);
175 
176   inline bool is_so_imm(unsigned Imm) const {
177     return ARM_AM::getSOImmVal(Imm) != -1;
178   }
179 
180   inline bool is_so_imm_not(unsigned Imm) const {
181     return ARM_AM::getSOImmVal(~Imm) != -1;
182   }
183 
184   inline bool is_t2_so_imm(unsigned Imm) const {
185     return ARM_AM::getT2SOImmVal(Imm) != -1;
186   }
187 
188   inline bool is_t2_so_imm_not(unsigned Imm) const {
189     return ARM_AM::getT2SOImmVal(~Imm) != -1;
190   }
191 
192   // Include the pieces autogenerated from the target description.
193 #include "ARMGenDAGISel.inc"
194 
195 private:
196   void transferMemOperands(SDNode *Src, SDNode *Dst);
197 
198   /// Indexed (pre/post inc/dec) load matching code for ARM.
199   bool tryARMIndexedLoad(SDNode *N);
200   bool tryT1IndexedLoad(SDNode *N);
201   bool tryT2IndexedLoad(SDNode *N);
202   bool tryMVEIndexedLoad(SDNode *N);
203   bool tryFMULFixed(SDNode *N, SDLoc dl);
204   bool tryFP_TO_INT(SDNode *N, SDLoc dl);
205   bool transformFixedFloatingPointConversion(SDNode *N, SDNode *FMul,
206                                              bool IsUnsigned,
207                                              bool FixedToFloat);
208 
209   /// SelectVLD - Select NEON load intrinsics.  NumVecs should be
210   /// 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
211   /// loads of D registers and even subregs and odd subregs of Q registers.
212   /// For NumVecs <= 2, QOpcodes1 is not used.
213   void SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
214                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
215                  const uint16_t *QOpcodes1);
216 
217   /// SelectVST - Select NEON store intrinsics.  NumVecs should
218   /// be 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
219   /// stores of D registers and even subregs and odd subregs of Q registers.
220   /// For NumVecs <= 2, QOpcodes1 is not used.
221   void SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
222                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
223                  const uint16_t *QOpcodes1);
224 
225   /// SelectVLDSTLane - Select NEON load/store lane intrinsics.  NumVecs should
226   /// be 2, 3 or 4.  The opcode arrays specify the instructions used for
227   /// load/store of D registers and Q registers.
228   void SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
229                        unsigned NumVecs, const uint16_t *DOpcodes,
230                        const uint16_t *QOpcodes);
231 
232   /// Helper functions for setting up clusters of MVE predication operands.
233   template <typename SDValueVector>
234   void AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
235                             SDValue PredicateMask);
236   template <typename SDValueVector>
237   void AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
238                             SDValue PredicateMask, SDValue Inactive);
239 
240   template <typename SDValueVector>
241   void AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc);
242   template <typename SDValueVector>
243   void AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc, EVT InactiveTy);
244 
245   /// SelectMVE_WB - Select MVE writeback load/store intrinsics.
246   void SelectMVE_WB(SDNode *N, const uint16_t *Opcodes, bool Predicated);
247 
248   /// SelectMVE_LongShift - Select MVE 64-bit scalar shift intrinsics.
249   void SelectMVE_LongShift(SDNode *N, uint16_t Opcode, bool Immediate,
250                            bool HasSaturationOperand);
251 
252   /// SelectMVE_VADCSBC - Select MVE vector add/sub-with-carry intrinsics.
253   void SelectMVE_VADCSBC(SDNode *N, uint16_t OpcodeWithCarry,
254                          uint16_t OpcodeWithNoCarry, bool Add, bool Predicated);
255 
256   /// SelectMVE_VSHLC - Select MVE intrinsics for a shift that carries between
257   /// vector lanes.
258   void SelectMVE_VSHLC(SDNode *N, bool Predicated);
259 
260   /// Select long MVE vector reductions with two vector operands
261   /// Stride is the number of vector element widths the instruction can operate
262   /// on:
263   /// 2 for long non-rounding variants, vml{a,s}ldav[a][x]: [i16, i32]
264   /// 1 for long rounding variants: vrml{a,s}ldavh[a][x]: [i32]
265   /// Stride is used when addressing the OpcodesS array which contains multiple
266   /// opcodes for each element width.
267   /// TySize is the index into the list of element types listed above
268   void SelectBaseMVE_VMLLDAV(SDNode *N, bool Predicated,
269                              const uint16_t *OpcodesS, const uint16_t *OpcodesU,
270                              size_t Stride, size_t TySize);
271 
272   /// Select a 64-bit MVE vector reduction with two vector operands
273   /// arm_mve_vmlldava_[predicated]
274   void SelectMVE_VMLLDAV(SDNode *N, bool Predicated, const uint16_t *OpcodesS,
275                          const uint16_t *OpcodesU);
276   /// Select a 72-bit MVE vector rounding reduction with two vector operands
277   /// int_arm_mve_vrmlldavha[_predicated]
278   void SelectMVE_VRMLLDAVH(SDNode *N, bool Predicated, const uint16_t *OpcodesS,
279                            const uint16_t *OpcodesU);
280 
281   /// SelectMVE_VLD - Select MVE interleaving load intrinsics. NumVecs
282   /// should be 2 or 4. The opcode array specifies the instructions
283   /// used for 8, 16 and 32-bit lane sizes respectively, and each
284   /// pointer points to a set of NumVecs sub-opcodes used for the
285   /// different stages (e.g. VLD20 versus VLD21) of each load family.
286   void SelectMVE_VLD(SDNode *N, unsigned NumVecs,
287                      const uint16_t *const *Opcodes, bool HasWriteback);
288 
289   /// SelectMVE_VxDUP - Select MVE incrementing-dup instructions. Opcodes is an
290   /// array of 3 elements for the 8, 16 and 32-bit lane sizes.
291   void SelectMVE_VxDUP(SDNode *N, const uint16_t *Opcodes,
292                        bool Wrapping, bool Predicated);
293 
294   /// Select SelectCDE_CXxD - Select CDE dual-GPR instruction (one of CX1D,
295   /// CX1DA, CX2D, CX2DA, CX3, CX3DA).
296   /// \arg \c NumExtraOps number of extra operands besides the coprocossor,
297   ///                     the accumulator and the immediate operand, i.e. 0
298   ///                     for CX1*, 1 for CX2*, 2 for CX3*
299   /// \arg \c HasAccum whether the instruction has an accumulator operand
300   void SelectCDE_CXxD(SDNode *N, uint16_t Opcode, size_t NumExtraOps,
301                       bool HasAccum);
302 
303   /// SelectVLDDup - Select NEON load-duplicate intrinsics.  NumVecs
304   /// should be 1, 2, 3 or 4.  The opcode array specifies the instructions used
305   /// for loading D registers.
306   void SelectVLDDup(SDNode *N, bool IsIntrinsic, bool isUpdating,
307                     unsigned NumVecs, const uint16_t *DOpcodes,
308                     const uint16_t *QOpcodes0 = nullptr,
309                     const uint16_t *QOpcodes1 = nullptr);
310 
311   /// Try to select SBFX/UBFX instructions for ARM.
312   bool tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned);
313 
314   bool tryInsertVectorElt(SDNode *N);
315 
316   // Select special operations if node forms integer ABS pattern
317   bool tryABSOp(SDNode *N);
318 
319   bool tryReadRegister(SDNode *N);
320   bool tryWriteRegister(SDNode *N);
321 
322   bool tryInlineAsm(SDNode *N);
323 
324   void SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI);
325 
326   void SelectCMP_SWAP(SDNode *N);
327 
328   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
329   /// inline asm expressions.
330   bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
331                                     std::vector<SDValue> &OutOps) override;
332 
333   // Form pairs of consecutive R, S, D, or Q registers.
334   SDNode *createGPRPairNode(EVT VT, SDValue V0, SDValue V1);
335   SDNode *createSRegPairNode(EVT VT, SDValue V0, SDValue V1);
336   SDNode *createDRegPairNode(EVT VT, SDValue V0, SDValue V1);
337   SDNode *createQRegPairNode(EVT VT, SDValue V0, SDValue V1);
338 
339   // Form sequences of 4 consecutive S, D, or Q registers.
340   SDNode *createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
341   SDNode *createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
342   SDNode *createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
343 
344   // Get the alignment operand for a NEON VLD or VST instruction.
345   SDValue GetVLDSTAlign(SDValue Align, const SDLoc &dl, unsigned NumVecs,
346                         bool is64BitVector);
347 
348   /// Checks if N is a multiplication by a constant where we can extract out a
349   /// power of two from the constant so that it can be used in a shift, but only
350   /// if it simplifies the materialization of the constant. Returns true if it
351   /// is, and assigns to PowerOfTwo the power of two that should be extracted
352   /// out and to NewMulConst the new constant to be multiplied by.
353   bool canExtractShiftFromMul(const SDValue &N, unsigned MaxShift,
354                               unsigned &PowerOfTwo, SDValue &NewMulConst) const;
355 
356   /// Replace N with M in CurDAG, in a way that also ensures that M gets
357   /// selected when N would have been selected.
358   void replaceDAGValue(const SDValue &N, SDValue M);
359 };
360 }
361 
362 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
363 /// operand. If so Imm will receive the 32-bit value.
364 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
365   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
366     Imm = cast<ConstantSDNode>(N)->getZExtValue();
367     return true;
368   }
369   return false;
370 }
371 
372 // isInt32Immediate - This method tests to see if a constant operand.
373 // If so Imm will receive the 32 bit value.
374 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
375   return isInt32Immediate(N.getNode(), Imm);
376 }
377 
378 // isOpcWithIntImmediate - This method tests to see if the node is a specific
379 // opcode and that it has a immediate integer right operand.
380 // If so Imm will receive the 32 bit value.
381 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
382   return N->getOpcode() == Opc &&
383          isInt32Immediate(N->getOperand(1).getNode(), Imm);
384 }
385 
386 /// Check whether a particular node is a constant value representable as
387 /// (N * Scale) where (N in [\p RangeMin, \p RangeMax).
388 ///
389 /// \param ScaledConstant [out] - On success, the pre-scaled constant value.
390 static bool isScaledConstantInRange(SDValue Node, int Scale,
391                                     int RangeMin, int RangeMax,
392                                     int &ScaledConstant) {
393   assert(Scale > 0 && "Invalid scale!");
394 
395   // Check that this is a constant.
396   const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Node);
397   if (!C)
398     return false;
399 
400   ScaledConstant = (int) C->getZExtValue();
401   if ((ScaledConstant % Scale) != 0)
402     return false;
403 
404   ScaledConstant /= Scale;
405   return ScaledConstant >= RangeMin && ScaledConstant < RangeMax;
406 }
407 
408 void ARMDAGToDAGISel::PreprocessISelDAG() {
409   if (!Subtarget->hasV6T2Ops())
410     return;
411 
412   bool isThumb2 = Subtarget->isThumb();
413   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
414        E = CurDAG->allnodes_end(); I != E; ) {
415     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
416 
417     if (N->getOpcode() != ISD::ADD)
418       continue;
419 
420     // Look for (add X1, (and (srl X2, c1), c2)) where c2 is constant with
421     // leading zeros, followed by consecutive set bits, followed by 1 or 2
422     // trailing zeros, e.g. 1020.
423     // Transform the expression to
424     // (add X1, (shl (and (srl X2, c1), (c2>>tz)), tz)) where tz is the number
425     // of trailing zeros of c2. The left shift would be folded as an shifter
426     // operand of 'add' and the 'and' and 'srl' would become a bits extraction
427     // node (UBFX).
428 
429     SDValue N0 = N->getOperand(0);
430     SDValue N1 = N->getOperand(1);
431     unsigned And_imm = 0;
432     if (!isOpcWithIntImmediate(N1.getNode(), ISD::AND, And_imm)) {
433       if (isOpcWithIntImmediate(N0.getNode(), ISD::AND, And_imm))
434         std::swap(N0, N1);
435     }
436     if (!And_imm)
437       continue;
438 
439     // Check if the AND mask is an immediate of the form: 000.....1111111100
440     unsigned TZ = countTrailingZeros(And_imm);
441     if (TZ != 1 && TZ != 2)
442       // Be conservative here. Shifter operands aren't always free. e.g. On
443       // Swift, left shifter operand of 1 / 2 for free but others are not.
444       // e.g.
445       //  ubfx   r3, r1, #16, #8
446       //  ldr.w  r3, [r0, r3, lsl #2]
447       // vs.
448       //  mov.w  r9, #1020
449       //  and.w  r2, r9, r1, lsr #14
450       //  ldr    r2, [r0, r2]
451       continue;
452     And_imm >>= TZ;
453     if (And_imm & (And_imm + 1))
454       continue;
455 
456     // Look for (and (srl X, c1), c2).
457     SDValue Srl = N1.getOperand(0);
458     unsigned Srl_imm = 0;
459     if (!isOpcWithIntImmediate(Srl.getNode(), ISD::SRL, Srl_imm) ||
460         (Srl_imm <= 2))
461       continue;
462 
463     // Make sure first operand is not a shifter operand which would prevent
464     // folding of the left shift.
465     SDValue CPTmp0;
466     SDValue CPTmp1;
467     SDValue CPTmp2;
468     if (isThumb2) {
469       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1))
470         continue;
471     } else {
472       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1) ||
473           SelectRegShifterOperand(N0, CPTmp0, CPTmp1, CPTmp2))
474         continue;
475     }
476 
477     // Now make the transformation.
478     Srl = CurDAG->getNode(ISD::SRL, SDLoc(Srl), MVT::i32,
479                           Srl.getOperand(0),
480                           CurDAG->getConstant(Srl_imm + TZ, SDLoc(Srl),
481                                               MVT::i32));
482     N1 = CurDAG->getNode(ISD::AND, SDLoc(N1), MVT::i32,
483                          Srl,
484                          CurDAG->getConstant(And_imm, SDLoc(Srl), MVT::i32));
485     N1 = CurDAG->getNode(ISD::SHL, SDLoc(N1), MVT::i32,
486                          N1, CurDAG->getConstant(TZ, SDLoc(Srl), MVT::i32));
487     CurDAG->UpdateNodeOperands(N, N0, N1);
488   }
489 }
490 
491 /// hasNoVMLxHazardUse - Return true if it's desirable to select a FP MLA / MLS
492 /// node. VFP / NEON fp VMLA / VMLS instructions have special RAW hazards (at
493 /// least on current ARM implementations) which should be avoidded.
494 bool ARMDAGToDAGISel::hasNoVMLxHazardUse(SDNode *N) const {
495   if (OptLevel == CodeGenOpt::None)
496     return true;
497 
498   if (!Subtarget->hasVMLxHazards())
499     return true;
500 
501   if (!N->hasOneUse())
502     return false;
503 
504   SDNode *Use = *N->use_begin();
505   if (Use->getOpcode() == ISD::CopyToReg)
506     return true;
507   if (Use->isMachineOpcode()) {
508     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
509         CurDAG->getSubtarget().getInstrInfo());
510 
511     const MCInstrDesc &MCID = TII->get(Use->getMachineOpcode());
512     if (MCID.mayStore())
513       return true;
514     unsigned Opcode = MCID.getOpcode();
515     if (Opcode == ARM::VMOVRS || Opcode == ARM::VMOVRRD)
516       return true;
517     // vmlx feeding into another vmlx. We actually want to unfold
518     // the use later in the MLxExpansion pass. e.g.
519     // vmla
520     // vmla (stall 8 cycles)
521     //
522     // vmul (5 cycles)
523     // vadd (5 cycles)
524     // vmla
525     // This adds up to about 18 - 19 cycles.
526     //
527     // vmla
528     // vmul (stall 4 cycles)
529     // vadd adds up to about 14 cycles.
530     return TII->isFpMLxInstruction(Opcode);
531   }
532 
533   return false;
534 }
535 
536 bool ARMDAGToDAGISel::isShifterOpProfitable(const SDValue &Shift,
537                                             ARM_AM::ShiftOpc ShOpcVal,
538                                             unsigned ShAmt) {
539   if (!Subtarget->isLikeA9() && !Subtarget->isSwift())
540     return true;
541   if (Shift.hasOneUse())
542     return true;
543   // R << 2 is free.
544   return ShOpcVal == ARM_AM::lsl &&
545          (ShAmt == 2 || (Subtarget->isSwift() && ShAmt == 1));
546 }
547 
548 bool ARMDAGToDAGISel::canExtractShiftFromMul(const SDValue &N,
549                                              unsigned MaxShift,
550                                              unsigned &PowerOfTwo,
551                                              SDValue &NewMulConst) const {
552   assert(N.getOpcode() == ISD::MUL);
553   assert(MaxShift > 0);
554 
555   // If the multiply is used in more than one place then changing the constant
556   // will make other uses incorrect, so don't.
557   if (!N.hasOneUse()) return false;
558   // Check if the multiply is by a constant
559   ConstantSDNode *MulConst = dyn_cast<ConstantSDNode>(N.getOperand(1));
560   if (!MulConst) return false;
561   // If the constant is used in more than one place then modifying it will mean
562   // we need to materialize two constants instead of one, which is a bad idea.
563   if (!MulConst->hasOneUse()) return false;
564   unsigned MulConstVal = MulConst->getZExtValue();
565   if (MulConstVal == 0) return false;
566 
567   // Find the largest power of 2 that MulConstVal is a multiple of
568   PowerOfTwo = MaxShift;
569   while ((MulConstVal % (1 << PowerOfTwo)) != 0) {
570     --PowerOfTwo;
571     if (PowerOfTwo == 0) return false;
572   }
573 
574   // Only optimise if the new cost is better
575   unsigned NewMulConstVal = MulConstVal / (1 << PowerOfTwo);
576   NewMulConst = CurDAG->getConstant(NewMulConstVal, SDLoc(N), MVT::i32);
577   unsigned OldCost = ConstantMaterializationCost(MulConstVal, Subtarget);
578   unsigned NewCost = ConstantMaterializationCost(NewMulConstVal, Subtarget);
579   return NewCost < OldCost;
580 }
581 
582 void ARMDAGToDAGISel::replaceDAGValue(const SDValue &N, SDValue M) {
583   CurDAG->RepositionNode(N.getNode()->getIterator(), M.getNode());
584   ReplaceUses(N, M);
585 }
586 
587 bool ARMDAGToDAGISel::SelectImmShifterOperand(SDValue N,
588                                               SDValue &BaseReg,
589                                               SDValue &Opc,
590                                               bool CheckProfitability) {
591   if (DisableShifterOp)
592     return false;
593 
594   // If N is a multiply-by-constant and it's profitable to extract a shift and
595   // use it in a shifted operand do so.
596   if (N.getOpcode() == ISD::MUL) {
597     unsigned PowerOfTwo = 0;
598     SDValue NewMulConst;
599     if (canExtractShiftFromMul(N, 31, PowerOfTwo, NewMulConst)) {
600       HandleSDNode Handle(N);
601       SDLoc Loc(N);
602       replaceDAGValue(N.getOperand(1), NewMulConst);
603       BaseReg = Handle.getValue();
604       Opc = CurDAG->getTargetConstant(
605           ARM_AM::getSORegOpc(ARM_AM::lsl, PowerOfTwo), Loc, MVT::i32);
606       return true;
607     }
608   }
609 
610   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
611 
612   // Don't match base register only case. That is matched to a separate
613   // lower complexity pattern with explicit register operand.
614   if (ShOpcVal == ARM_AM::no_shift) return false;
615 
616   BaseReg = N.getOperand(0);
617   unsigned ShImmVal = 0;
618   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
619   if (!RHS) return false;
620   ShImmVal = RHS->getZExtValue() & 31;
621   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
622                                   SDLoc(N), MVT::i32);
623   return true;
624 }
625 
626 bool ARMDAGToDAGISel::SelectRegShifterOperand(SDValue N,
627                                               SDValue &BaseReg,
628                                               SDValue &ShReg,
629                                               SDValue &Opc,
630                                               bool CheckProfitability) {
631   if (DisableShifterOp)
632     return false;
633 
634   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
635 
636   // Don't match base register only case. That is matched to a separate
637   // lower complexity pattern with explicit register operand.
638   if (ShOpcVal == ARM_AM::no_shift) return false;
639 
640   BaseReg = N.getOperand(0);
641   unsigned ShImmVal = 0;
642   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
643   if (RHS) return false;
644 
645   ShReg = N.getOperand(1);
646   if (CheckProfitability && !isShifterOpProfitable(N, ShOpcVal, ShImmVal))
647     return false;
648   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
649                                   SDLoc(N), MVT::i32);
650   return true;
651 }
652 
653 // Determine whether an ISD::OR's operands are suitable to turn the operation
654 // into an addition, which often has more compact encodings.
655 bool ARMDAGToDAGISel::SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out) {
656   assert(Parent->getOpcode() == ISD::OR && "unexpected parent");
657   Out = N;
658   return CurDAG->haveNoCommonBitsSet(N, Parent->getOperand(1));
659 }
660 
661 
662 bool ARMDAGToDAGISel::SelectAddrModeImm12(SDValue N,
663                                           SDValue &Base,
664                                           SDValue &OffImm) {
665   // Match simple R + imm12 operands.
666 
667   // Base only.
668   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
669       !CurDAG->isBaseWithConstantOffset(N)) {
670     if (N.getOpcode() == ISD::FrameIndex) {
671       // Match frame index.
672       int FI = cast<FrameIndexSDNode>(N)->getIndex();
673       Base = CurDAG->getTargetFrameIndex(
674           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
675       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
676       return true;
677     }
678 
679     if (N.getOpcode() == ARMISD::Wrapper &&
680         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
681         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
682         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
683       Base = N.getOperand(0);
684     } else
685       Base = N;
686     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
687     return true;
688   }
689 
690   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
691     int RHSC = (int)RHS->getSExtValue();
692     if (N.getOpcode() == ISD::SUB)
693       RHSC = -RHSC;
694 
695     if (RHSC > -0x1000 && RHSC < 0x1000) { // 12 bits
696       Base   = N.getOperand(0);
697       if (Base.getOpcode() == ISD::FrameIndex) {
698         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
699         Base = CurDAG->getTargetFrameIndex(
700             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
701       }
702       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
703       return true;
704     }
705   }
706 
707   // Base only.
708   Base = N;
709   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
710   return true;
711 }
712 
713 
714 
715 bool ARMDAGToDAGISel::SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset,
716                                       SDValue &Opc) {
717   if (N.getOpcode() == ISD::MUL &&
718       ((!Subtarget->isLikeA9() && !Subtarget->isSwift()) || N.hasOneUse())) {
719     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
720       // X * [3,5,9] -> X + X * [2,4,8] etc.
721       int RHSC = (int)RHS->getZExtValue();
722       if (RHSC & 1) {
723         RHSC = RHSC & ~1;
724         ARM_AM::AddrOpc AddSub = ARM_AM::add;
725         if (RHSC < 0) {
726           AddSub = ARM_AM::sub;
727           RHSC = - RHSC;
728         }
729         if (isPowerOf2_32(RHSC)) {
730           unsigned ShAmt = Log2_32(RHSC);
731           Base = Offset = N.getOperand(0);
732           Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt,
733                                                             ARM_AM::lsl),
734                                           SDLoc(N), MVT::i32);
735           return true;
736         }
737       }
738     }
739   }
740 
741   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
742       // ISD::OR that is equivalent to an ISD::ADD.
743       !CurDAG->isBaseWithConstantOffset(N))
744     return false;
745 
746   // Leave simple R +/- imm12 operands for LDRi12
747   if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
748     int RHSC;
749     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
750                                 -0x1000+1, 0x1000, RHSC)) // 12 bits.
751       return false;
752   }
753 
754   // Otherwise this is R +/- [possibly shifted] R.
755   ARM_AM::AddrOpc AddSub = N.getOpcode() == ISD::SUB ? ARM_AM::sub:ARM_AM::add;
756   ARM_AM::ShiftOpc ShOpcVal =
757     ARM_AM::getShiftOpcForNode(N.getOperand(1).getOpcode());
758   unsigned ShAmt = 0;
759 
760   Base   = N.getOperand(0);
761   Offset = N.getOperand(1);
762 
763   if (ShOpcVal != ARM_AM::no_shift) {
764     // Check to see if the RHS of the shift is a constant, if not, we can't fold
765     // it.
766     if (ConstantSDNode *Sh =
767            dyn_cast<ConstantSDNode>(N.getOperand(1).getOperand(1))) {
768       ShAmt = Sh->getZExtValue();
769       if (isShifterOpProfitable(Offset, ShOpcVal, ShAmt))
770         Offset = N.getOperand(1).getOperand(0);
771       else {
772         ShAmt = 0;
773         ShOpcVal = ARM_AM::no_shift;
774       }
775     } else {
776       ShOpcVal = ARM_AM::no_shift;
777     }
778   }
779 
780   // Try matching (R shl C) + (R).
781   if (N.getOpcode() != ISD::SUB && ShOpcVal == ARM_AM::no_shift &&
782       !(Subtarget->isLikeA9() || Subtarget->isSwift() ||
783         N.getOperand(0).hasOneUse())) {
784     ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOperand(0).getOpcode());
785     if (ShOpcVal != ARM_AM::no_shift) {
786       // Check to see if the RHS of the shift is a constant, if not, we can't
787       // fold it.
788       if (ConstantSDNode *Sh =
789           dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
790         ShAmt = Sh->getZExtValue();
791         if (isShifterOpProfitable(N.getOperand(0), ShOpcVal, ShAmt)) {
792           Offset = N.getOperand(0).getOperand(0);
793           Base = N.getOperand(1);
794         } else {
795           ShAmt = 0;
796           ShOpcVal = ARM_AM::no_shift;
797         }
798       } else {
799         ShOpcVal = ARM_AM::no_shift;
800       }
801     }
802   }
803 
804   // If Offset is a multiply-by-constant and it's profitable to extract a shift
805   // and use it in a shifted operand do so.
806   if (Offset.getOpcode() == ISD::MUL && N.hasOneUse()) {
807     unsigned PowerOfTwo = 0;
808     SDValue NewMulConst;
809     if (canExtractShiftFromMul(Offset, 31, PowerOfTwo, NewMulConst)) {
810       HandleSDNode Handle(Offset);
811       replaceDAGValue(Offset.getOperand(1), NewMulConst);
812       Offset = Handle.getValue();
813       ShAmt = PowerOfTwo;
814       ShOpcVal = ARM_AM::lsl;
815     }
816   }
817 
818   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
819                                   SDLoc(N), MVT::i32);
820   return true;
821 }
822 
823 bool ARMDAGToDAGISel::SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
824                                             SDValue &Offset, SDValue &Opc) {
825   unsigned Opcode = Op->getOpcode();
826   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
827     ? cast<LoadSDNode>(Op)->getAddressingMode()
828     : cast<StoreSDNode>(Op)->getAddressingMode();
829   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
830     ? ARM_AM::add : ARM_AM::sub;
831   int Val;
832   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val))
833     return false;
834 
835   Offset = N;
836   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
837   unsigned ShAmt = 0;
838   if (ShOpcVal != ARM_AM::no_shift) {
839     // Check to see if the RHS of the shift is a constant, if not, we can't fold
840     // it.
841     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
842       ShAmt = Sh->getZExtValue();
843       if (isShifterOpProfitable(N, ShOpcVal, ShAmt))
844         Offset = N.getOperand(0);
845       else {
846         ShAmt = 0;
847         ShOpcVal = ARM_AM::no_shift;
848       }
849     } else {
850       ShOpcVal = ARM_AM::no_shift;
851     }
852   }
853 
854   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
855                                   SDLoc(N), MVT::i32);
856   return true;
857 }
858 
859 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
860                                             SDValue &Offset, SDValue &Opc) {
861   unsigned Opcode = Op->getOpcode();
862   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
863     ? cast<LoadSDNode>(Op)->getAddressingMode()
864     : cast<StoreSDNode>(Op)->getAddressingMode();
865   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
866     ? ARM_AM::add : ARM_AM::sub;
867   int Val;
868   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
869     if (AddSub == ARM_AM::sub) Val *= -1;
870     Offset = CurDAG->getRegister(0, MVT::i32);
871     Opc = CurDAG->getTargetConstant(Val, SDLoc(Op), MVT::i32);
872     return true;
873   }
874 
875   return false;
876 }
877 
878 
879 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
880                                             SDValue &Offset, SDValue &Opc) {
881   unsigned Opcode = Op->getOpcode();
882   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
883     ? cast<LoadSDNode>(Op)->getAddressingMode()
884     : cast<StoreSDNode>(Op)->getAddressingMode();
885   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
886     ? ARM_AM::add : ARM_AM::sub;
887   int Val;
888   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
889     Offset = CurDAG->getRegister(0, MVT::i32);
890     Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, Val,
891                                                       ARM_AM::no_shift),
892                                     SDLoc(Op), MVT::i32);
893     return true;
894   }
895 
896   return false;
897 }
898 
899 bool ARMDAGToDAGISel::SelectAddrOffsetNone(SDValue N, SDValue &Base) {
900   Base = N;
901   return true;
902 }
903 
904 bool ARMDAGToDAGISel::SelectAddrMode3(SDValue N,
905                                       SDValue &Base, SDValue &Offset,
906                                       SDValue &Opc) {
907   if (N.getOpcode() == ISD::SUB) {
908     // X - C  is canonicalize to X + -C, no need to handle it here.
909     Base = N.getOperand(0);
910     Offset = N.getOperand(1);
911     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::sub, 0), SDLoc(N),
912                                     MVT::i32);
913     return true;
914   }
915 
916   if (!CurDAG->isBaseWithConstantOffset(N)) {
917     Base = N;
918     if (N.getOpcode() == ISD::FrameIndex) {
919       int FI = cast<FrameIndexSDNode>(N)->getIndex();
920       Base = CurDAG->getTargetFrameIndex(
921           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
922     }
923     Offset = CurDAG->getRegister(0, MVT::i32);
924     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
925                                     MVT::i32);
926     return true;
927   }
928 
929   // If the RHS is +/- imm8, fold into addr mode.
930   int RHSC;
931   if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
932                               -256 + 1, 256, RHSC)) { // 8 bits.
933     Base = N.getOperand(0);
934     if (Base.getOpcode() == ISD::FrameIndex) {
935       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
936       Base = CurDAG->getTargetFrameIndex(
937           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
938     }
939     Offset = CurDAG->getRegister(0, MVT::i32);
940 
941     ARM_AM::AddrOpc AddSub = ARM_AM::add;
942     if (RHSC < 0) {
943       AddSub = ARM_AM::sub;
944       RHSC = -RHSC;
945     }
946     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, RHSC), SDLoc(N),
947                                     MVT::i32);
948     return true;
949   }
950 
951   Base = N.getOperand(0);
952   Offset = N.getOperand(1);
953   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
954                                   MVT::i32);
955   return true;
956 }
957 
958 bool ARMDAGToDAGISel::SelectAddrMode3Offset(SDNode *Op, SDValue N,
959                                             SDValue &Offset, SDValue &Opc) {
960   unsigned Opcode = Op->getOpcode();
961   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
962     ? cast<LoadSDNode>(Op)->getAddressingMode()
963     : cast<StoreSDNode>(Op)->getAddressingMode();
964   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
965     ? ARM_AM::add : ARM_AM::sub;
966   int Val;
967   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 256, Val)) { // 12 bits.
968     Offset = CurDAG->getRegister(0, MVT::i32);
969     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, Val), SDLoc(Op),
970                                     MVT::i32);
971     return true;
972   }
973 
974   Offset = N;
975   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, 0), SDLoc(Op),
976                                   MVT::i32);
977   return true;
978 }
979 
980 bool ARMDAGToDAGISel::IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset,
981                                         bool FP16) {
982   if (!CurDAG->isBaseWithConstantOffset(N)) {
983     Base = N;
984     if (N.getOpcode() == ISD::FrameIndex) {
985       int FI = cast<FrameIndexSDNode>(N)->getIndex();
986       Base = CurDAG->getTargetFrameIndex(
987           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
988     } else if (N.getOpcode() == ARMISD::Wrapper &&
989                N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
990                N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
991                N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
992       Base = N.getOperand(0);
993     }
994     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
995                                        SDLoc(N), MVT::i32);
996     return true;
997   }
998 
999   // If the RHS is +/- imm8, fold into addr mode.
1000   int RHSC;
1001   const int Scale = FP16 ? 2 : 4;
1002 
1003   if (isScaledConstantInRange(N.getOperand(1), Scale, -255, 256, RHSC)) {
1004     Base = N.getOperand(0);
1005     if (Base.getOpcode() == ISD::FrameIndex) {
1006       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1007       Base = CurDAG->getTargetFrameIndex(
1008           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1009     }
1010 
1011     ARM_AM::AddrOpc AddSub = ARM_AM::add;
1012     if (RHSC < 0) {
1013       AddSub = ARM_AM::sub;
1014       RHSC = -RHSC;
1015     }
1016 
1017     if (FP16)
1018       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(AddSub, RHSC),
1019                                          SDLoc(N), MVT::i32);
1020     else
1021       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(AddSub, RHSC),
1022                                          SDLoc(N), MVT::i32);
1023 
1024     return true;
1025   }
1026 
1027   Base = N;
1028 
1029   if (FP16)
1030     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(ARM_AM::add, 0),
1031                                        SDLoc(N), MVT::i32);
1032   else
1033     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
1034                                        SDLoc(N), MVT::i32);
1035 
1036   return true;
1037 }
1038 
1039 bool ARMDAGToDAGISel::SelectAddrMode5(SDValue N,
1040                                       SDValue &Base, SDValue &Offset) {
1041   return IsAddressingMode5(N, Base, Offset, /*FP16=*/ false);
1042 }
1043 
1044 bool ARMDAGToDAGISel::SelectAddrMode5FP16(SDValue N,
1045                                           SDValue &Base, SDValue &Offset) {
1046   return IsAddressingMode5(N, Base, Offset, /*FP16=*/ true);
1047 }
1048 
1049 bool ARMDAGToDAGISel::SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,
1050                                       SDValue &Align) {
1051   Addr = N;
1052 
1053   unsigned Alignment = 0;
1054 
1055   MemSDNode *MemN = cast<MemSDNode>(Parent);
1056 
1057   if (isa<LSBaseSDNode>(MemN) ||
1058       ((MemN->getOpcode() == ARMISD::VST1_UPD ||
1059         MemN->getOpcode() == ARMISD::VLD1_UPD) &&
1060        MemN->getConstantOperandVal(MemN->getNumOperands() - 1) == 1)) {
1061     // This case occurs only for VLD1-lane/dup and VST1-lane instructions.
1062     // The maximum alignment is equal to the memory size being referenced.
1063     unsigned MMOAlign = MemN->getAlignment();
1064     unsigned MemSize = MemN->getMemoryVT().getSizeInBits() / 8;
1065     if (MMOAlign >= MemSize && MemSize > 1)
1066       Alignment = MemSize;
1067   } else {
1068     // All other uses of addrmode6 are for intrinsics.  For now just record
1069     // the raw alignment value; it will be refined later based on the legal
1070     // alignment operands for the intrinsic.
1071     Alignment = MemN->getAlignment();
1072   }
1073 
1074   Align = CurDAG->getTargetConstant(Alignment, SDLoc(N), MVT::i32);
1075   return true;
1076 }
1077 
1078 bool ARMDAGToDAGISel::SelectAddrMode6Offset(SDNode *Op, SDValue N,
1079                                             SDValue &Offset) {
1080   LSBaseSDNode *LdSt = cast<LSBaseSDNode>(Op);
1081   ISD::MemIndexedMode AM = LdSt->getAddressingMode();
1082   if (AM != ISD::POST_INC)
1083     return false;
1084   Offset = N;
1085   if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N)) {
1086     if (NC->getZExtValue() * 8 == LdSt->getMemoryVT().getSizeInBits())
1087       Offset = CurDAG->getRegister(0, MVT::i32);
1088   }
1089   return true;
1090 }
1091 
1092 bool ARMDAGToDAGISel::SelectAddrModePC(SDValue N,
1093                                        SDValue &Offset, SDValue &Label) {
1094   if (N.getOpcode() == ARMISD::PIC_ADD && N.hasOneUse()) {
1095     Offset = N.getOperand(0);
1096     SDValue N1 = N.getOperand(1);
1097     Label = CurDAG->getTargetConstant(cast<ConstantSDNode>(N1)->getZExtValue(),
1098                                       SDLoc(N), MVT::i32);
1099     return true;
1100   }
1101 
1102   return false;
1103 }
1104 
1105 
1106 //===----------------------------------------------------------------------===//
1107 //                         Thumb Addressing Modes
1108 //===----------------------------------------------------------------------===//
1109 
1110 static bool shouldUseZeroOffsetLdSt(SDValue N) {
1111   // Negative numbers are difficult to materialise in thumb1. If we are
1112   // selecting the add of a negative, instead try to select ri with a zero
1113   // offset, so create the add node directly which will become a sub.
1114   if (N.getOpcode() != ISD::ADD)
1115     return false;
1116 
1117   // Look for an imm which is not legal for ld/st, but is legal for sub.
1118   if (auto C = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1119     return C->getSExtValue() < 0 && C->getSExtValue() >= -255;
1120 
1121   return false;
1122 }
1123 
1124 bool ARMDAGToDAGISel::SelectThumbAddrModeRRSext(SDValue N, SDValue &Base,
1125                                                 SDValue &Offset) {
1126   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N)) {
1127     ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N);
1128     if (!NC || !NC->isNullValue())
1129       return false;
1130 
1131     Base = Offset = N;
1132     return true;
1133   }
1134 
1135   Base = N.getOperand(0);
1136   Offset = N.getOperand(1);
1137   return true;
1138 }
1139 
1140 bool ARMDAGToDAGISel::SelectThumbAddrModeRR(SDValue N, SDValue &Base,
1141                                             SDValue &Offset) {
1142   if (shouldUseZeroOffsetLdSt(N))
1143     return false; // Select ri instead
1144   return SelectThumbAddrModeRRSext(N, Base, Offset);
1145 }
1146 
1147 bool
1148 ARMDAGToDAGISel::SelectThumbAddrModeImm5S(SDValue N, unsigned Scale,
1149                                           SDValue &Base, SDValue &OffImm) {
1150   if (shouldUseZeroOffsetLdSt(N)) {
1151     Base = N;
1152     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1153     return true;
1154   }
1155 
1156   if (!CurDAG->isBaseWithConstantOffset(N)) {
1157     if (N.getOpcode() == ISD::ADD) {
1158       return false; // We want to select register offset instead
1159     } else if (N.getOpcode() == ARMISD::Wrapper &&
1160         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1161         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1162         N.getOperand(0).getOpcode() != ISD::TargetConstantPool &&
1163         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1164       Base = N.getOperand(0);
1165     } else {
1166       Base = N;
1167     }
1168 
1169     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1170     return true;
1171   }
1172 
1173   // If the RHS is + imm5 * scale, fold into addr mode.
1174   int RHSC;
1175   if (isScaledConstantInRange(N.getOperand(1), Scale, 0, 32, RHSC)) {
1176     Base = N.getOperand(0);
1177     OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1178     return true;
1179   }
1180 
1181   // Offset is too large, so use register offset instead.
1182   return false;
1183 }
1184 
1185 bool
1186 ARMDAGToDAGISel::SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
1187                                            SDValue &OffImm) {
1188   return SelectThumbAddrModeImm5S(N, 4, Base, OffImm);
1189 }
1190 
1191 bool
1192 ARMDAGToDAGISel::SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
1193                                            SDValue &OffImm) {
1194   return SelectThumbAddrModeImm5S(N, 2, Base, OffImm);
1195 }
1196 
1197 bool
1198 ARMDAGToDAGISel::SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
1199                                            SDValue &OffImm) {
1200   return SelectThumbAddrModeImm5S(N, 1, Base, OffImm);
1201 }
1202 
1203 bool ARMDAGToDAGISel::SelectThumbAddrModeSP(SDValue N,
1204                                             SDValue &Base, SDValue &OffImm) {
1205   if (N.getOpcode() == ISD::FrameIndex) {
1206     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1207     // Only multiples of 4 are allowed for the offset, so the frame object
1208     // alignment must be at least 4.
1209     MachineFrameInfo &MFI = MF->getFrameInfo();
1210     if (MFI.getObjectAlign(FI) < Align(4))
1211       MFI.setObjectAlignment(FI, Align(4));
1212     Base = CurDAG->getTargetFrameIndex(
1213         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1214     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1215     return true;
1216   }
1217 
1218   if (!CurDAG->isBaseWithConstantOffset(N))
1219     return false;
1220 
1221   if (N.getOperand(0).getOpcode() == ISD::FrameIndex) {
1222     // If the RHS is + imm8 * scale, fold into addr mode.
1223     int RHSC;
1224     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/4, 0, 256, RHSC)) {
1225       Base = N.getOperand(0);
1226       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1227       // Make sure the offset is inside the object, or we might fail to
1228       // allocate an emergency spill slot. (An out-of-range access is UB, but
1229       // it could show up anyway.)
1230       MachineFrameInfo &MFI = MF->getFrameInfo();
1231       if (RHSC * 4 < MFI.getObjectSize(FI)) {
1232         // For LHS+RHS to result in an offset that's a multiple of 4 the object
1233         // indexed by the LHS must be 4-byte aligned.
1234         if (!MFI.isFixedObjectIndex(FI) && MFI.getObjectAlign(FI) < Align(4))
1235           MFI.setObjectAlignment(FI, Align(4));
1236         if (MFI.getObjectAlign(FI) >= Align(4)) {
1237           Base = CurDAG->getTargetFrameIndex(
1238               FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1239           OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1240           return true;
1241         }
1242       }
1243     }
1244   }
1245 
1246   return false;
1247 }
1248 
1249 template <unsigned Shift>
1250 bool ARMDAGToDAGISel::SelectTAddrModeImm7(SDValue N, SDValue &Base,
1251                                           SDValue &OffImm) {
1252   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1253     int RHSC;
1254     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -0x7f, 0x80,
1255                                 RHSC)) {
1256       Base = N.getOperand(0);
1257       if (N.getOpcode() == ISD::SUB)
1258         RHSC = -RHSC;
1259       OffImm =
1260           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1261       return true;
1262     }
1263   }
1264 
1265   // Base only.
1266   Base = N;
1267   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1268   return true;
1269 }
1270 
1271 
1272 //===----------------------------------------------------------------------===//
1273 //                        Thumb 2 Addressing Modes
1274 //===----------------------------------------------------------------------===//
1275 
1276 
1277 bool ARMDAGToDAGISel::SelectT2AddrModeImm12(SDValue N,
1278                                             SDValue &Base, SDValue &OffImm) {
1279   // Match simple R + imm12 operands.
1280 
1281   // Base only.
1282   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1283       !CurDAG->isBaseWithConstantOffset(N)) {
1284     if (N.getOpcode() == ISD::FrameIndex) {
1285       // Match frame index.
1286       int FI = cast<FrameIndexSDNode>(N)->getIndex();
1287       Base = CurDAG->getTargetFrameIndex(
1288           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1289       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1290       return true;
1291     }
1292 
1293     if (N.getOpcode() == ARMISD::Wrapper &&
1294         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1295         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1296         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1297       Base = N.getOperand(0);
1298       if (Base.getOpcode() == ISD::TargetConstantPool)
1299         return false;  // We want to select t2LDRpci instead.
1300     } else
1301       Base = N;
1302     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1303     return true;
1304   }
1305 
1306   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1307     if (SelectT2AddrModeImm8(N, Base, OffImm))
1308       // Let t2LDRi8 handle (R - imm8).
1309       return false;
1310 
1311     int RHSC = (int)RHS->getZExtValue();
1312     if (N.getOpcode() == ISD::SUB)
1313       RHSC = -RHSC;
1314 
1315     if (RHSC >= 0 && RHSC < 0x1000) { // 12 bits (unsigned)
1316       Base   = N.getOperand(0);
1317       if (Base.getOpcode() == ISD::FrameIndex) {
1318         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1319         Base = CurDAG->getTargetFrameIndex(
1320             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1321       }
1322       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1323       return true;
1324     }
1325   }
1326 
1327   // Base only.
1328   Base = N;
1329   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1330   return true;
1331 }
1332 
1333 template <unsigned Shift>
1334 bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N, SDValue &Base,
1335                                            SDValue &OffImm) {
1336   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1337     int RHSC;
1338     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -255, 256, RHSC)) {
1339       Base = N.getOperand(0);
1340       if (Base.getOpcode() == ISD::FrameIndex) {
1341         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1342         Base = CurDAG->getTargetFrameIndex(
1343             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1344       }
1345 
1346       if (N.getOpcode() == ISD::SUB)
1347         RHSC = -RHSC;
1348       OffImm =
1349           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1350       return true;
1351     }
1352   }
1353 
1354   // Base only.
1355   Base = N;
1356   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1357   return true;
1358 }
1359 
1360 bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N,
1361                                            SDValue &Base, SDValue &OffImm) {
1362   // Match simple R - imm8 operands.
1363   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1364       !CurDAG->isBaseWithConstantOffset(N))
1365     return false;
1366 
1367   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1368     int RHSC = (int)RHS->getSExtValue();
1369     if (N.getOpcode() == ISD::SUB)
1370       RHSC = -RHSC;
1371 
1372     if ((RHSC >= -255) && (RHSC < 0)) { // 8 bits (always negative)
1373       Base = N.getOperand(0);
1374       if (Base.getOpcode() == ISD::FrameIndex) {
1375         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1376         Base = CurDAG->getTargetFrameIndex(
1377             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1378       }
1379       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1380       return true;
1381     }
1382   }
1383 
1384   return false;
1385 }
1386 
1387 bool ARMDAGToDAGISel::SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
1388                                                  SDValue &OffImm){
1389   unsigned Opcode = Op->getOpcode();
1390   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
1391     ? cast<LoadSDNode>(Op)->getAddressingMode()
1392     : cast<StoreSDNode>(Op)->getAddressingMode();
1393   int RHSC;
1394   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x100, RHSC)) { // 8 bits.
1395     OffImm = ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
1396       ? CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32)
1397       : CurDAG->getTargetConstant(-RHSC, SDLoc(N), MVT::i32);
1398     return true;
1399   }
1400 
1401   return false;
1402 }
1403 
1404 template <unsigned Shift>
1405 bool ARMDAGToDAGISel::SelectT2AddrModeImm7(SDValue N, SDValue &Base,
1406                                            SDValue &OffImm) {
1407   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1408     int RHSC;
1409     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -0x7f, 0x80,
1410                                 RHSC)) {
1411       Base = N.getOperand(0);
1412       if (Base.getOpcode() == ISD::FrameIndex) {
1413         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1414         Base = CurDAG->getTargetFrameIndex(
1415             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1416       }
1417 
1418       if (N.getOpcode() == ISD::SUB)
1419         RHSC = -RHSC;
1420       OffImm =
1421           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1422       return true;
1423     }
1424   }
1425 
1426   // Base only.
1427   Base = N;
1428   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1429   return true;
1430 }
1431 
1432 template <unsigned Shift>
1433 bool ARMDAGToDAGISel::SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N,
1434                                                  SDValue &OffImm) {
1435   return SelectT2AddrModeImm7Offset(Op, N, OffImm, Shift);
1436 }
1437 
1438 bool ARMDAGToDAGISel::SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N,
1439                                                  SDValue &OffImm,
1440                                                  unsigned Shift) {
1441   unsigned Opcode = Op->getOpcode();
1442   ISD::MemIndexedMode AM;
1443   switch (Opcode) {
1444   case ISD::LOAD:
1445     AM = cast<LoadSDNode>(Op)->getAddressingMode();
1446     break;
1447   case ISD::STORE:
1448     AM = cast<StoreSDNode>(Op)->getAddressingMode();
1449     break;
1450   case ISD::MLOAD:
1451     AM = cast<MaskedLoadSDNode>(Op)->getAddressingMode();
1452     break;
1453   case ISD::MSTORE:
1454     AM = cast<MaskedStoreSDNode>(Op)->getAddressingMode();
1455     break;
1456   default:
1457     llvm_unreachable("Unexpected Opcode for Imm7Offset");
1458   }
1459 
1460   int RHSC;
1461   // 7 bit constant, shifted by Shift.
1462   if (isScaledConstantInRange(N, 1 << Shift, 0, 0x80, RHSC)) {
1463     OffImm =
1464         ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
1465             ? CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32)
1466             : CurDAG->getTargetConstant(-RHSC * (1 << Shift), SDLoc(N),
1467                                         MVT::i32);
1468     return true;
1469   }
1470   return false;
1471 }
1472 
1473 template <int Min, int Max>
1474 bool ARMDAGToDAGISel::SelectImmediateInRange(SDValue N, SDValue &OffImm) {
1475   int Val;
1476   if (isScaledConstantInRange(N, 1, Min, Max, Val)) {
1477     OffImm = CurDAG->getTargetConstant(Val, SDLoc(N), MVT::i32);
1478     return true;
1479   }
1480   return false;
1481 }
1482 
1483 bool ARMDAGToDAGISel::SelectT2AddrModeSoReg(SDValue N,
1484                                             SDValue &Base,
1485                                             SDValue &OffReg, SDValue &ShImm) {
1486   // (R - imm8) should be handled by t2LDRi8. The rest are handled by t2LDRi12.
1487   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N))
1488     return false;
1489 
1490   // Leave (R + imm12) for t2LDRi12, (R - imm8) for t2LDRi8.
1491   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1492     int RHSC = (int)RHS->getZExtValue();
1493     if (RHSC >= 0 && RHSC < 0x1000) // 12 bits (unsigned)
1494       return false;
1495     else if (RHSC < 0 && RHSC >= -255) // 8 bits
1496       return false;
1497   }
1498 
1499   // Look for (R + R) or (R + (R << [1,2,3])).
1500   unsigned ShAmt = 0;
1501   Base   = N.getOperand(0);
1502   OffReg = N.getOperand(1);
1503 
1504   // Swap if it is ((R << c) + R).
1505   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(OffReg.getOpcode());
1506   if (ShOpcVal != ARM_AM::lsl) {
1507     ShOpcVal = ARM_AM::getShiftOpcForNode(Base.getOpcode());
1508     if (ShOpcVal == ARM_AM::lsl)
1509       std::swap(Base, OffReg);
1510   }
1511 
1512   if (ShOpcVal == ARM_AM::lsl) {
1513     // Check to see if the RHS of the shift is a constant, if not, we can't fold
1514     // it.
1515     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(OffReg.getOperand(1))) {
1516       ShAmt = Sh->getZExtValue();
1517       if (ShAmt < 4 && isShifterOpProfitable(OffReg, ShOpcVal, ShAmt))
1518         OffReg = OffReg.getOperand(0);
1519       else {
1520         ShAmt = 0;
1521       }
1522     }
1523   }
1524 
1525   // If OffReg is a multiply-by-constant and it's profitable to extract a shift
1526   // and use it in a shifted operand do so.
1527   if (OffReg.getOpcode() == ISD::MUL && N.hasOneUse()) {
1528     unsigned PowerOfTwo = 0;
1529     SDValue NewMulConst;
1530     if (canExtractShiftFromMul(OffReg, 3, PowerOfTwo, NewMulConst)) {
1531       HandleSDNode Handle(OffReg);
1532       replaceDAGValue(OffReg.getOperand(1), NewMulConst);
1533       OffReg = Handle.getValue();
1534       ShAmt = PowerOfTwo;
1535     }
1536   }
1537 
1538   ShImm = CurDAG->getTargetConstant(ShAmt, SDLoc(N), MVT::i32);
1539 
1540   return true;
1541 }
1542 
1543 bool ARMDAGToDAGISel::SelectT2AddrModeExclusive(SDValue N, SDValue &Base,
1544                                                 SDValue &OffImm) {
1545   // This *must* succeed since it's used for the irreplaceable ldrex and strex
1546   // instructions.
1547   Base = N;
1548   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1549 
1550   if (N.getOpcode() != ISD::ADD || !CurDAG->isBaseWithConstantOffset(N))
1551     return true;
1552 
1553   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
1554   if (!RHS)
1555     return true;
1556 
1557   uint32_t RHSC = (int)RHS->getZExtValue();
1558   if (RHSC > 1020 || RHSC % 4 != 0)
1559     return true;
1560 
1561   Base = N.getOperand(0);
1562   if (Base.getOpcode() == ISD::FrameIndex) {
1563     int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1564     Base = CurDAG->getTargetFrameIndex(
1565         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1566   }
1567 
1568   OffImm = CurDAG->getTargetConstant(RHSC/4, SDLoc(N), MVT::i32);
1569   return true;
1570 }
1571 
1572 //===--------------------------------------------------------------------===//
1573 
1574 /// getAL - Returns a ARMCC::AL immediate node.
1575 static inline SDValue getAL(SelectionDAG *CurDAG, const SDLoc &dl) {
1576   return CurDAG->getTargetConstant((uint64_t)ARMCC::AL, dl, MVT::i32);
1577 }
1578 
1579 void ARMDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
1580   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
1581   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
1582 }
1583 
1584 bool ARMDAGToDAGISel::tryARMIndexedLoad(SDNode *N) {
1585   LoadSDNode *LD = cast<LoadSDNode>(N);
1586   ISD::MemIndexedMode AM = LD->getAddressingMode();
1587   if (AM == ISD::UNINDEXED)
1588     return false;
1589 
1590   EVT LoadedVT = LD->getMemoryVT();
1591   SDValue Offset, AMOpc;
1592   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1593   unsigned Opcode = 0;
1594   bool Match = false;
1595   if (LoadedVT == MVT::i32 && isPre &&
1596       SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1597     Opcode = ARM::LDR_PRE_IMM;
1598     Match = true;
1599   } else if (LoadedVT == MVT::i32 && !isPre &&
1600       SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1601     Opcode = ARM::LDR_POST_IMM;
1602     Match = true;
1603   } else if (LoadedVT == MVT::i32 &&
1604       SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1605     Opcode = isPre ? ARM::LDR_PRE_REG : ARM::LDR_POST_REG;
1606     Match = true;
1607 
1608   } else if (LoadedVT == MVT::i16 &&
1609              SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1610     Match = true;
1611     Opcode = (LD->getExtensionType() == ISD::SEXTLOAD)
1612       ? (isPre ? ARM::LDRSH_PRE : ARM::LDRSH_POST)
1613       : (isPre ? ARM::LDRH_PRE : ARM::LDRH_POST);
1614   } else if (LoadedVT == MVT::i8 || LoadedVT == MVT::i1) {
1615     if (LD->getExtensionType() == ISD::SEXTLOAD) {
1616       if (SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1617         Match = true;
1618         Opcode = isPre ? ARM::LDRSB_PRE : ARM::LDRSB_POST;
1619       }
1620     } else {
1621       if (isPre &&
1622           SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1623         Match = true;
1624         Opcode = ARM::LDRB_PRE_IMM;
1625       } else if (!isPre &&
1626                   SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1627         Match = true;
1628         Opcode = ARM::LDRB_POST_IMM;
1629       } else if (SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1630         Match = true;
1631         Opcode = isPre ? ARM::LDRB_PRE_REG : ARM::LDRB_POST_REG;
1632       }
1633     }
1634   }
1635 
1636   if (Match) {
1637     if (Opcode == ARM::LDR_PRE_IMM || Opcode == ARM::LDRB_PRE_IMM) {
1638       SDValue Chain = LD->getChain();
1639       SDValue Base = LD->getBasePtr();
1640       SDValue Ops[]= { Base, AMOpc, getAL(CurDAG, SDLoc(N)),
1641                        CurDAG->getRegister(0, MVT::i32), Chain };
1642       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1643                                            MVT::Other, Ops);
1644       transferMemOperands(N, New);
1645       ReplaceNode(N, New);
1646       return true;
1647     } else {
1648       SDValue Chain = LD->getChain();
1649       SDValue Base = LD->getBasePtr();
1650       SDValue Ops[]= { Base, Offset, AMOpc, getAL(CurDAG, SDLoc(N)),
1651                        CurDAG->getRegister(0, MVT::i32), Chain };
1652       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1653                                            MVT::Other, Ops);
1654       transferMemOperands(N, New);
1655       ReplaceNode(N, New);
1656       return true;
1657     }
1658   }
1659 
1660   return false;
1661 }
1662 
1663 bool ARMDAGToDAGISel::tryT1IndexedLoad(SDNode *N) {
1664   LoadSDNode *LD = cast<LoadSDNode>(N);
1665   EVT LoadedVT = LD->getMemoryVT();
1666   ISD::MemIndexedMode AM = LD->getAddressingMode();
1667   if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD ||
1668       LoadedVT.getSimpleVT().SimpleTy != MVT::i32)
1669     return false;
1670 
1671   auto *COffs = dyn_cast<ConstantSDNode>(LD->getOffset());
1672   if (!COffs || COffs->getZExtValue() != 4)
1673     return false;
1674 
1675   // A T1 post-indexed load is just a single register LDM: LDM r0!, {r1}.
1676   // The encoding of LDM is not how the rest of ISel expects a post-inc load to
1677   // look however, so we use a pseudo here and switch it for a tLDMIA_UPD after
1678   // ISel.
1679   SDValue Chain = LD->getChain();
1680   SDValue Base = LD->getBasePtr();
1681   SDValue Ops[]= { Base, getAL(CurDAG, SDLoc(N)),
1682                    CurDAG->getRegister(0, MVT::i32), Chain };
1683   SDNode *New = CurDAG->getMachineNode(ARM::tLDR_postidx, SDLoc(N), MVT::i32,
1684                                        MVT::i32, MVT::Other, Ops);
1685   transferMemOperands(N, New);
1686   ReplaceNode(N, New);
1687   return true;
1688 }
1689 
1690 bool ARMDAGToDAGISel::tryT2IndexedLoad(SDNode *N) {
1691   LoadSDNode *LD = cast<LoadSDNode>(N);
1692   ISD::MemIndexedMode AM = LD->getAddressingMode();
1693   if (AM == ISD::UNINDEXED)
1694     return false;
1695 
1696   EVT LoadedVT = LD->getMemoryVT();
1697   bool isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1698   SDValue Offset;
1699   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1700   unsigned Opcode = 0;
1701   bool Match = false;
1702   if (SelectT2AddrModeImm8Offset(N, LD->getOffset(), Offset)) {
1703     switch (LoadedVT.getSimpleVT().SimpleTy) {
1704     case MVT::i32:
1705       Opcode = isPre ? ARM::t2LDR_PRE : ARM::t2LDR_POST;
1706       break;
1707     case MVT::i16:
1708       if (isSExtLd)
1709         Opcode = isPre ? ARM::t2LDRSH_PRE : ARM::t2LDRSH_POST;
1710       else
1711         Opcode = isPre ? ARM::t2LDRH_PRE : ARM::t2LDRH_POST;
1712       break;
1713     case MVT::i8:
1714     case MVT::i1:
1715       if (isSExtLd)
1716         Opcode = isPre ? ARM::t2LDRSB_PRE : ARM::t2LDRSB_POST;
1717       else
1718         Opcode = isPre ? ARM::t2LDRB_PRE : ARM::t2LDRB_POST;
1719       break;
1720     default:
1721       return false;
1722     }
1723     Match = true;
1724   }
1725 
1726   if (Match) {
1727     SDValue Chain = LD->getChain();
1728     SDValue Base = LD->getBasePtr();
1729     SDValue Ops[]= { Base, Offset, getAL(CurDAG, SDLoc(N)),
1730                      CurDAG->getRegister(0, MVT::i32), Chain };
1731     SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1732                                          MVT::Other, Ops);
1733     transferMemOperands(N, New);
1734     ReplaceNode(N, New);
1735     return true;
1736   }
1737 
1738   return false;
1739 }
1740 
1741 bool ARMDAGToDAGISel::tryMVEIndexedLoad(SDNode *N) {
1742   EVT LoadedVT;
1743   unsigned Opcode = 0;
1744   bool isSExtLd, isPre;
1745   Align Alignment;
1746   ARMVCC::VPTCodes Pred;
1747   SDValue PredReg;
1748   SDValue Chain, Base, Offset;
1749 
1750   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1751     ISD::MemIndexedMode AM = LD->getAddressingMode();
1752     if (AM == ISD::UNINDEXED)
1753       return false;
1754     LoadedVT = LD->getMemoryVT();
1755     if (!LoadedVT.isVector())
1756       return false;
1757 
1758     Chain = LD->getChain();
1759     Base = LD->getBasePtr();
1760     Offset = LD->getOffset();
1761     Alignment = LD->getAlign();
1762     isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1763     isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1764     Pred = ARMVCC::None;
1765     PredReg = CurDAG->getRegister(0, MVT::i32);
1766   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
1767     ISD::MemIndexedMode AM = LD->getAddressingMode();
1768     if (AM == ISD::UNINDEXED)
1769       return false;
1770     LoadedVT = LD->getMemoryVT();
1771     if (!LoadedVT.isVector())
1772       return false;
1773 
1774     Chain = LD->getChain();
1775     Base = LD->getBasePtr();
1776     Offset = LD->getOffset();
1777     Alignment = LD->getAlign();
1778     isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1779     isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1780     Pred = ARMVCC::Then;
1781     PredReg = LD->getMask();
1782   } else
1783     llvm_unreachable("Expected a Load or a Masked Load!");
1784 
1785   // We allow LE non-masked loads to change the type (for example use a vldrb.8
1786   // as opposed to a vldrw.32). This can allow extra addressing modes or
1787   // alignments for what is otherwise an equivalent instruction.
1788   bool CanChangeType = Subtarget->isLittle() && !isa<MaskedLoadSDNode>(N);
1789 
1790   SDValue NewOffset;
1791   if (Alignment >= Align(2) && LoadedVT == MVT::v4i16 &&
1792       SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 1)) {
1793     if (isSExtLd)
1794       Opcode = isPre ? ARM::MVE_VLDRHS32_pre : ARM::MVE_VLDRHS32_post;
1795     else
1796       Opcode = isPre ? ARM::MVE_VLDRHU32_pre : ARM::MVE_VLDRHU32_post;
1797   } else if (LoadedVT == MVT::v8i8 &&
1798              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0)) {
1799     if (isSExtLd)
1800       Opcode = isPre ? ARM::MVE_VLDRBS16_pre : ARM::MVE_VLDRBS16_post;
1801     else
1802       Opcode = isPre ? ARM::MVE_VLDRBU16_pre : ARM::MVE_VLDRBU16_post;
1803   } else if (LoadedVT == MVT::v4i8 &&
1804              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0)) {
1805     if (isSExtLd)
1806       Opcode = isPre ? ARM::MVE_VLDRBS32_pre : ARM::MVE_VLDRBS32_post;
1807     else
1808       Opcode = isPre ? ARM::MVE_VLDRBU32_pre : ARM::MVE_VLDRBU32_post;
1809   } else if (Alignment >= Align(4) &&
1810              (CanChangeType || LoadedVT == MVT::v4i32 ||
1811               LoadedVT == MVT::v4f32) &&
1812              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 2))
1813     Opcode = isPre ? ARM::MVE_VLDRWU32_pre : ARM::MVE_VLDRWU32_post;
1814   else if (Alignment >= Align(2) &&
1815            (CanChangeType || LoadedVT == MVT::v8i16 ||
1816             LoadedVT == MVT::v8f16) &&
1817            SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 1))
1818     Opcode = isPre ? ARM::MVE_VLDRHU16_pre : ARM::MVE_VLDRHU16_post;
1819   else if ((CanChangeType || LoadedVT == MVT::v16i8) &&
1820            SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0))
1821     Opcode = isPre ? ARM::MVE_VLDRBU8_pre : ARM::MVE_VLDRBU8_post;
1822   else
1823     return false;
1824 
1825   SDValue Ops[] = {Base,
1826                    NewOffset,
1827                    CurDAG->getTargetConstant(Pred, SDLoc(N), MVT::i32),
1828                    PredReg,
1829                    CurDAG->getRegister(0, MVT::i32), // tp_reg
1830                    Chain};
1831   SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32,
1832                                        N->getValueType(0), MVT::Other, Ops);
1833   transferMemOperands(N, New);
1834   ReplaceUses(SDValue(N, 0), SDValue(New, 1));
1835   ReplaceUses(SDValue(N, 1), SDValue(New, 0));
1836   ReplaceUses(SDValue(N, 2), SDValue(New, 2));
1837   CurDAG->RemoveDeadNode(N);
1838   return true;
1839 }
1840 
1841 /// Form a GPRPair pseudo register from a pair of GPR regs.
1842 SDNode *ARMDAGToDAGISel::createGPRPairNode(EVT VT, SDValue V0, SDValue V1) {
1843   SDLoc dl(V0.getNode());
1844   SDValue RegClass =
1845     CurDAG->getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
1846   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
1847   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
1848   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1849   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1850 }
1851 
1852 /// Form a D register from a pair of S registers.
1853 SDNode *ARMDAGToDAGISel::createSRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1854   SDLoc dl(V0.getNode());
1855   SDValue RegClass =
1856     CurDAG->getTargetConstant(ARM::DPR_VFP2RegClassID, dl, MVT::i32);
1857   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1858   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1859   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1860   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1861 }
1862 
1863 /// Form a quad register from a pair of D registers.
1864 SDNode *ARMDAGToDAGISel::createDRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1865   SDLoc dl(V0.getNode());
1866   SDValue RegClass = CurDAG->getTargetConstant(ARM::QPRRegClassID, dl,
1867                                                MVT::i32);
1868   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1869   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1870   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1871   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1872 }
1873 
1874 /// Form 4 consecutive D registers from a pair of Q registers.
1875 SDNode *ARMDAGToDAGISel::createQRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1876   SDLoc dl(V0.getNode());
1877   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1878                                                MVT::i32);
1879   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1880   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1881   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1882   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1883 }
1884 
1885 /// Form 4 consecutive S registers.
1886 SDNode *ARMDAGToDAGISel::createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1,
1887                                    SDValue V2, SDValue V3) {
1888   SDLoc dl(V0.getNode());
1889   SDValue RegClass =
1890     CurDAG->getTargetConstant(ARM::QPR_VFP2RegClassID, dl, MVT::i32);
1891   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1892   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1893   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::ssub_2, dl, MVT::i32);
1894   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::ssub_3, dl, MVT::i32);
1895   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1896                                     V2, SubReg2, V3, SubReg3 };
1897   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1898 }
1899 
1900 /// Form 4 consecutive D registers.
1901 SDNode *ARMDAGToDAGISel::createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1,
1902                                    SDValue V2, SDValue V3) {
1903   SDLoc dl(V0.getNode());
1904   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1905                                                MVT::i32);
1906   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1907   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1908   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::dsub_2, dl, MVT::i32);
1909   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::dsub_3, dl, MVT::i32);
1910   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1911                                     V2, SubReg2, V3, SubReg3 };
1912   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1913 }
1914 
1915 /// Form 4 consecutive Q registers.
1916 SDNode *ARMDAGToDAGISel::createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1,
1917                                    SDValue V2, SDValue V3) {
1918   SDLoc dl(V0.getNode());
1919   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQQQPRRegClassID, dl,
1920                                                MVT::i32);
1921   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1922   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1923   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::qsub_2, dl, MVT::i32);
1924   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::qsub_3, dl, MVT::i32);
1925   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1926                                     V2, SubReg2, V3, SubReg3 };
1927   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1928 }
1929 
1930 /// GetVLDSTAlign - Get the alignment (in bytes) for the alignment operand
1931 /// of a NEON VLD or VST instruction.  The supported values depend on the
1932 /// number of registers being loaded.
1933 SDValue ARMDAGToDAGISel::GetVLDSTAlign(SDValue Align, const SDLoc &dl,
1934                                        unsigned NumVecs, bool is64BitVector) {
1935   unsigned NumRegs = NumVecs;
1936   if (!is64BitVector && NumVecs < 3)
1937     NumRegs *= 2;
1938 
1939   unsigned Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
1940   if (Alignment >= 32 && NumRegs == 4)
1941     Alignment = 32;
1942   else if (Alignment >= 16 && (NumRegs == 2 || NumRegs == 4))
1943     Alignment = 16;
1944   else if (Alignment >= 8)
1945     Alignment = 8;
1946   else
1947     Alignment = 0;
1948 
1949   return CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
1950 }
1951 
1952 static bool isVLDfixed(unsigned Opc)
1953 {
1954   switch (Opc) {
1955   default: return false;
1956   case ARM::VLD1d8wb_fixed : return true;
1957   case ARM::VLD1d16wb_fixed : return true;
1958   case ARM::VLD1d64Qwb_fixed : return true;
1959   case ARM::VLD1d32wb_fixed : return true;
1960   case ARM::VLD1d64wb_fixed : return true;
1961   case ARM::VLD1d8TPseudoWB_fixed : return true;
1962   case ARM::VLD1d16TPseudoWB_fixed : return true;
1963   case ARM::VLD1d32TPseudoWB_fixed : return true;
1964   case ARM::VLD1d64TPseudoWB_fixed : return true;
1965   case ARM::VLD1d8QPseudoWB_fixed : return true;
1966   case ARM::VLD1d16QPseudoWB_fixed : return true;
1967   case ARM::VLD1d32QPseudoWB_fixed : return true;
1968   case ARM::VLD1d64QPseudoWB_fixed : return true;
1969   case ARM::VLD1q8wb_fixed : return true;
1970   case ARM::VLD1q16wb_fixed : return true;
1971   case ARM::VLD1q32wb_fixed : return true;
1972   case ARM::VLD1q64wb_fixed : return true;
1973   case ARM::VLD1DUPd8wb_fixed : return true;
1974   case ARM::VLD1DUPd16wb_fixed : return true;
1975   case ARM::VLD1DUPd32wb_fixed : return true;
1976   case ARM::VLD1DUPq8wb_fixed : return true;
1977   case ARM::VLD1DUPq16wb_fixed : return true;
1978   case ARM::VLD1DUPq32wb_fixed : return true;
1979   case ARM::VLD2d8wb_fixed : return true;
1980   case ARM::VLD2d16wb_fixed : return true;
1981   case ARM::VLD2d32wb_fixed : return true;
1982   case ARM::VLD2q8PseudoWB_fixed : return true;
1983   case ARM::VLD2q16PseudoWB_fixed : return true;
1984   case ARM::VLD2q32PseudoWB_fixed : return true;
1985   case ARM::VLD2DUPd8wb_fixed : return true;
1986   case ARM::VLD2DUPd16wb_fixed : return true;
1987   case ARM::VLD2DUPd32wb_fixed : return true;
1988   case ARM::VLD2DUPq8OddPseudoWB_fixed: return true;
1989   case ARM::VLD2DUPq16OddPseudoWB_fixed: return true;
1990   case ARM::VLD2DUPq32OddPseudoWB_fixed: return true;
1991   }
1992 }
1993 
1994 static bool isVSTfixed(unsigned Opc)
1995 {
1996   switch (Opc) {
1997   default: return false;
1998   case ARM::VST1d8wb_fixed : return true;
1999   case ARM::VST1d16wb_fixed : return true;
2000   case ARM::VST1d32wb_fixed : return true;
2001   case ARM::VST1d64wb_fixed : return true;
2002   case ARM::VST1q8wb_fixed : return true;
2003   case ARM::VST1q16wb_fixed : return true;
2004   case ARM::VST1q32wb_fixed : return true;
2005   case ARM::VST1q64wb_fixed : return true;
2006   case ARM::VST1d8TPseudoWB_fixed : return true;
2007   case ARM::VST1d16TPseudoWB_fixed : return true;
2008   case ARM::VST1d32TPseudoWB_fixed : return true;
2009   case ARM::VST1d64TPseudoWB_fixed : return true;
2010   case ARM::VST1d8QPseudoWB_fixed : return true;
2011   case ARM::VST1d16QPseudoWB_fixed : return true;
2012   case ARM::VST1d32QPseudoWB_fixed : return true;
2013   case ARM::VST1d64QPseudoWB_fixed : return true;
2014   case ARM::VST2d8wb_fixed : return true;
2015   case ARM::VST2d16wb_fixed : return true;
2016   case ARM::VST2d32wb_fixed : return true;
2017   case ARM::VST2q8PseudoWB_fixed : return true;
2018   case ARM::VST2q16PseudoWB_fixed : return true;
2019   case ARM::VST2q32PseudoWB_fixed : return true;
2020   }
2021 }
2022 
2023 // Get the register stride update opcode of a VLD/VST instruction that
2024 // is otherwise equivalent to the given fixed stride updating instruction.
2025 static unsigned getVLDSTRegisterUpdateOpcode(unsigned Opc) {
2026   assert((isVLDfixed(Opc) || isVSTfixed(Opc))
2027     && "Incorrect fixed stride updating instruction.");
2028   switch (Opc) {
2029   default: break;
2030   case ARM::VLD1d8wb_fixed: return ARM::VLD1d8wb_register;
2031   case ARM::VLD1d16wb_fixed: return ARM::VLD1d16wb_register;
2032   case ARM::VLD1d32wb_fixed: return ARM::VLD1d32wb_register;
2033   case ARM::VLD1d64wb_fixed: return ARM::VLD1d64wb_register;
2034   case ARM::VLD1q8wb_fixed: return ARM::VLD1q8wb_register;
2035   case ARM::VLD1q16wb_fixed: return ARM::VLD1q16wb_register;
2036   case ARM::VLD1q32wb_fixed: return ARM::VLD1q32wb_register;
2037   case ARM::VLD1q64wb_fixed: return ARM::VLD1q64wb_register;
2038   case ARM::VLD1d64Twb_fixed: return ARM::VLD1d64Twb_register;
2039   case ARM::VLD1d64Qwb_fixed: return ARM::VLD1d64Qwb_register;
2040   case ARM::VLD1d8TPseudoWB_fixed: return ARM::VLD1d8TPseudoWB_register;
2041   case ARM::VLD1d16TPseudoWB_fixed: return ARM::VLD1d16TPseudoWB_register;
2042   case ARM::VLD1d32TPseudoWB_fixed: return ARM::VLD1d32TPseudoWB_register;
2043   case ARM::VLD1d64TPseudoWB_fixed: return ARM::VLD1d64TPseudoWB_register;
2044   case ARM::VLD1d8QPseudoWB_fixed: return ARM::VLD1d8QPseudoWB_register;
2045   case ARM::VLD1d16QPseudoWB_fixed: return ARM::VLD1d16QPseudoWB_register;
2046   case ARM::VLD1d32QPseudoWB_fixed: return ARM::VLD1d32QPseudoWB_register;
2047   case ARM::VLD1d64QPseudoWB_fixed: return ARM::VLD1d64QPseudoWB_register;
2048   case ARM::VLD1DUPd8wb_fixed : return ARM::VLD1DUPd8wb_register;
2049   case ARM::VLD1DUPd16wb_fixed : return ARM::VLD1DUPd16wb_register;
2050   case ARM::VLD1DUPd32wb_fixed : return ARM::VLD1DUPd32wb_register;
2051   case ARM::VLD1DUPq8wb_fixed : return ARM::VLD1DUPq8wb_register;
2052   case ARM::VLD1DUPq16wb_fixed : return ARM::VLD1DUPq16wb_register;
2053   case ARM::VLD1DUPq32wb_fixed : return ARM::VLD1DUPq32wb_register;
2054   case ARM::VLD2DUPq8OddPseudoWB_fixed: return ARM::VLD2DUPq8OddPseudoWB_register;
2055   case ARM::VLD2DUPq16OddPseudoWB_fixed: return ARM::VLD2DUPq16OddPseudoWB_register;
2056   case ARM::VLD2DUPq32OddPseudoWB_fixed: return ARM::VLD2DUPq32OddPseudoWB_register;
2057 
2058   case ARM::VST1d8wb_fixed: return ARM::VST1d8wb_register;
2059   case ARM::VST1d16wb_fixed: return ARM::VST1d16wb_register;
2060   case ARM::VST1d32wb_fixed: return ARM::VST1d32wb_register;
2061   case ARM::VST1d64wb_fixed: return ARM::VST1d64wb_register;
2062   case ARM::VST1q8wb_fixed: return ARM::VST1q8wb_register;
2063   case ARM::VST1q16wb_fixed: return ARM::VST1q16wb_register;
2064   case ARM::VST1q32wb_fixed: return ARM::VST1q32wb_register;
2065   case ARM::VST1q64wb_fixed: return ARM::VST1q64wb_register;
2066   case ARM::VST1d8TPseudoWB_fixed: return ARM::VST1d8TPseudoWB_register;
2067   case ARM::VST1d16TPseudoWB_fixed: return ARM::VST1d16TPseudoWB_register;
2068   case ARM::VST1d32TPseudoWB_fixed: return ARM::VST1d32TPseudoWB_register;
2069   case ARM::VST1d64TPseudoWB_fixed: return ARM::VST1d64TPseudoWB_register;
2070   case ARM::VST1d8QPseudoWB_fixed: return ARM::VST1d8QPseudoWB_register;
2071   case ARM::VST1d16QPseudoWB_fixed: return ARM::VST1d16QPseudoWB_register;
2072   case ARM::VST1d32QPseudoWB_fixed: return ARM::VST1d32QPseudoWB_register;
2073   case ARM::VST1d64QPseudoWB_fixed: return ARM::VST1d64QPseudoWB_register;
2074 
2075   case ARM::VLD2d8wb_fixed: return ARM::VLD2d8wb_register;
2076   case ARM::VLD2d16wb_fixed: return ARM::VLD2d16wb_register;
2077   case ARM::VLD2d32wb_fixed: return ARM::VLD2d32wb_register;
2078   case ARM::VLD2q8PseudoWB_fixed: return ARM::VLD2q8PseudoWB_register;
2079   case ARM::VLD2q16PseudoWB_fixed: return ARM::VLD2q16PseudoWB_register;
2080   case ARM::VLD2q32PseudoWB_fixed: return ARM::VLD2q32PseudoWB_register;
2081 
2082   case ARM::VST2d8wb_fixed: return ARM::VST2d8wb_register;
2083   case ARM::VST2d16wb_fixed: return ARM::VST2d16wb_register;
2084   case ARM::VST2d32wb_fixed: return ARM::VST2d32wb_register;
2085   case ARM::VST2q8PseudoWB_fixed: return ARM::VST2q8PseudoWB_register;
2086   case ARM::VST2q16PseudoWB_fixed: return ARM::VST2q16PseudoWB_register;
2087   case ARM::VST2q32PseudoWB_fixed: return ARM::VST2q32PseudoWB_register;
2088 
2089   case ARM::VLD2DUPd8wb_fixed: return ARM::VLD2DUPd8wb_register;
2090   case ARM::VLD2DUPd16wb_fixed: return ARM::VLD2DUPd16wb_register;
2091   case ARM::VLD2DUPd32wb_fixed: return ARM::VLD2DUPd32wb_register;
2092   }
2093   return Opc; // If not one we handle, return it unchanged.
2094 }
2095 
2096 /// Returns true if the given increment is a Constant known to be equal to the
2097 /// access size performed by a NEON load/store. This means the "[rN]!" form can
2098 /// be used.
2099 static bool isPerfectIncrement(SDValue Inc, EVT VecTy, unsigned NumVecs) {
2100   auto C = dyn_cast<ConstantSDNode>(Inc);
2101   return C && C->getZExtValue() == VecTy.getSizeInBits() / 8 * NumVecs;
2102 }
2103 
2104 void ARMDAGToDAGISel::SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
2105                                 const uint16_t *DOpcodes,
2106                                 const uint16_t *QOpcodes0,
2107                                 const uint16_t *QOpcodes1) {
2108   assert(Subtarget->hasNEON());
2109   assert(NumVecs >= 1 && NumVecs <= 4 && "VLD NumVecs out-of-range");
2110   SDLoc dl(N);
2111 
2112   SDValue MemAddr, Align;
2113   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2114                                    // nodes are not intrinsics.
2115   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2116   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2117     return;
2118 
2119   SDValue Chain = N->getOperand(0);
2120   EVT VT = N->getValueType(0);
2121   bool is64BitVector = VT.is64BitVector();
2122   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
2123 
2124   unsigned OpcodeIndex;
2125   switch (VT.getSimpleVT().SimpleTy) {
2126   default: llvm_unreachable("unhandled vld type");
2127     // Double-register operations:
2128   case MVT::v8i8:  OpcodeIndex = 0; break;
2129   case MVT::v4f16:
2130   case MVT::v4bf16:
2131   case MVT::v4i16: OpcodeIndex = 1; break;
2132   case MVT::v2f32:
2133   case MVT::v2i32: OpcodeIndex = 2; break;
2134   case MVT::v1i64: OpcodeIndex = 3; break;
2135     // Quad-register operations:
2136   case MVT::v16i8: OpcodeIndex = 0; break;
2137   case MVT::v8f16:
2138   case MVT::v8bf16:
2139   case MVT::v8i16: OpcodeIndex = 1; break;
2140   case MVT::v4f32:
2141   case MVT::v4i32: OpcodeIndex = 2; break;
2142   case MVT::v2f64:
2143   case MVT::v2i64: OpcodeIndex = 3; break;
2144   }
2145 
2146   EVT ResTy;
2147   if (NumVecs == 1)
2148     ResTy = VT;
2149   else {
2150     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2151     if (!is64BitVector)
2152       ResTyElts *= 2;
2153     ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
2154   }
2155   std::vector<EVT> ResTys;
2156   ResTys.push_back(ResTy);
2157   if (isUpdating)
2158     ResTys.push_back(MVT::i32);
2159   ResTys.push_back(MVT::Other);
2160 
2161   SDValue Pred = getAL(CurDAG, dl);
2162   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2163   SDNode *VLd;
2164   SmallVector<SDValue, 7> Ops;
2165 
2166   // Double registers and VLD1/VLD2 quad registers are directly supported.
2167   if (is64BitVector || NumVecs <= 2) {
2168     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2169                     QOpcodes0[OpcodeIndex]);
2170     Ops.push_back(MemAddr);
2171     Ops.push_back(Align);
2172     if (isUpdating) {
2173       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2174       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
2175       if (!IsImmUpdate) {
2176         // We use a VLD1 for v1i64 even if the pseudo says vld2/3/4, so
2177         // check for the opcode rather than the number of vector elements.
2178         if (isVLDfixed(Opc))
2179           Opc = getVLDSTRegisterUpdateOpcode(Opc);
2180         Ops.push_back(Inc);
2181       // VLD1/VLD2 fixed increment does not need Reg0 so only include it in
2182       // the operands if not such an opcode.
2183       } else if (!isVLDfixed(Opc))
2184         Ops.push_back(Reg0);
2185     }
2186     Ops.push_back(Pred);
2187     Ops.push_back(Reg0);
2188     Ops.push_back(Chain);
2189     VLd = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2190 
2191   } else {
2192     // Otherwise, quad registers are loaded with two separate instructions,
2193     // where one loads the even registers and the other loads the odd registers.
2194     EVT AddrTy = MemAddr.getValueType();
2195 
2196     // Load the even subregs.  This is always an updating load, so that it
2197     // provides the address to the second load for the odd subregs.
2198     SDValue ImplDef =
2199       SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
2200     const SDValue OpsA[] = { MemAddr, Align, Reg0, ImplDef, Pred, Reg0, Chain };
2201     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
2202                                           ResTy, AddrTy, MVT::Other, OpsA);
2203     Chain = SDValue(VLdA, 2);
2204 
2205     // Load the odd subregs.
2206     Ops.push_back(SDValue(VLdA, 1));
2207     Ops.push_back(Align);
2208     if (isUpdating) {
2209       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2210       assert(isa<ConstantSDNode>(Inc.getNode()) &&
2211              "only constant post-increment update allowed for VLD3/4");
2212       (void)Inc;
2213       Ops.push_back(Reg0);
2214     }
2215     Ops.push_back(SDValue(VLdA, 0));
2216     Ops.push_back(Pred);
2217     Ops.push_back(Reg0);
2218     Ops.push_back(Chain);
2219     VLd = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, Ops);
2220   }
2221 
2222   // Transfer memoperands.
2223   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2224   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLd), {MemOp});
2225 
2226   if (NumVecs == 1) {
2227     ReplaceNode(N, VLd);
2228     return;
2229   }
2230 
2231   // Extract out the subregisters.
2232   SDValue SuperReg = SDValue(VLd, 0);
2233   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
2234                     ARM::qsub_3 == ARM::qsub_0 + 3,
2235                 "Unexpected subreg numbering");
2236   unsigned Sub0 = (is64BitVector ? ARM::dsub_0 : ARM::qsub_0);
2237   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2238     ReplaceUses(SDValue(N, Vec),
2239                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
2240   ReplaceUses(SDValue(N, NumVecs), SDValue(VLd, 1));
2241   if (isUpdating)
2242     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLd, 2));
2243   CurDAG->RemoveDeadNode(N);
2244 }
2245 
2246 void ARMDAGToDAGISel::SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
2247                                 const uint16_t *DOpcodes,
2248                                 const uint16_t *QOpcodes0,
2249                                 const uint16_t *QOpcodes1) {
2250   assert(Subtarget->hasNEON());
2251   assert(NumVecs >= 1 && NumVecs <= 4 && "VST NumVecs out-of-range");
2252   SDLoc dl(N);
2253 
2254   SDValue MemAddr, Align;
2255   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2256                                    // nodes are not intrinsics.
2257   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2258   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
2259   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2260     return;
2261 
2262   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2263 
2264   SDValue Chain = N->getOperand(0);
2265   EVT VT = N->getOperand(Vec0Idx).getValueType();
2266   bool is64BitVector = VT.is64BitVector();
2267   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
2268 
2269   unsigned OpcodeIndex;
2270   switch (VT.getSimpleVT().SimpleTy) {
2271   default: llvm_unreachable("unhandled vst type");
2272     // Double-register operations:
2273   case MVT::v8i8:  OpcodeIndex = 0; break;
2274   case MVT::v4f16:
2275   case MVT::v4bf16:
2276   case MVT::v4i16: OpcodeIndex = 1; break;
2277   case MVT::v2f32:
2278   case MVT::v2i32: OpcodeIndex = 2; break;
2279   case MVT::v1i64: OpcodeIndex = 3; break;
2280     // Quad-register operations:
2281   case MVT::v16i8: OpcodeIndex = 0; break;
2282   case MVT::v8f16:
2283   case MVT::v8bf16:
2284   case MVT::v8i16: OpcodeIndex = 1; break;
2285   case MVT::v4f32:
2286   case MVT::v4i32: OpcodeIndex = 2; break;
2287   case MVT::v2f64:
2288   case MVT::v2i64: OpcodeIndex = 3; break;
2289   }
2290 
2291   std::vector<EVT> ResTys;
2292   if (isUpdating)
2293     ResTys.push_back(MVT::i32);
2294   ResTys.push_back(MVT::Other);
2295 
2296   SDValue Pred = getAL(CurDAG, dl);
2297   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2298   SmallVector<SDValue, 7> Ops;
2299 
2300   // Double registers and VST1/VST2 quad registers are directly supported.
2301   if (is64BitVector || NumVecs <= 2) {
2302     SDValue SrcReg;
2303     if (NumVecs == 1) {
2304       SrcReg = N->getOperand(Vec0Idx);
2305     } else if (is64BitVector) {
2306       // Form a REG_SEQUENCE to force register allocation.
2307       SDValue V0 = N->getOperand(Vec0Idx + 0);
2308       SDValue V1 = N->getOperand(Vec0Idx + 1);
2309       if (NumVecs == 2)
2310         SrcReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
2311       else {
2312         SDValue V2 = N->getOperand(Vec0Idx + 2);
2313         // If it's a vst3, form a quad D-register and leave the last part as
2314         // an undef.
2315         SDValue V3 = (NumVecs == 3)
2316           ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,dl,VT), 0)
2317           : N->getOperand(Vec0Idx + 3);
2318         SrcReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
2319       }
2320     } else {
2321       // Form a QQ register.
2322       SDValue Q0 = N->getOperand(Vec0Idx);
2323       SDValue Q1 = N->getOperand(Vec0Idx + 1);
2324       SrcReg = SDValue(createQRegPairNode(MVT::v4i64, Q0, Q1), 0);
2325     }
2326 
2327     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2328                     QOpcodes0[OpcodeIndex]);
2329     Ops.push_back(MemAddr);
2330     Ops.push_back(Align);
2331     if (isUpdating) {
2332       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2333       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
2334       if (!IsImmUpdate) {
2335         // We use a VST1 for v1i64 even if the pseudo says VST2/3/4, so
2336         // check for the opcode rather than the number of vector elements.
2337         if (isVSTfixed(Opc))
2338           Opc = getVLDSTRegisterUpdateOpcode(Opc);
2339         Ops.push_back(Inc);
2340       }
2341       // VST1/VST2 fixed increment does not need Reg0 so only include it in
2342       // the operands if not such an opcode.
2343       else if (!isVSTfixed(Opc))
2344         Ops.push_back(Reg0);
2345     }
2346     Ops.push_back(SrcReg);
2347     Ops.push_back(Pred);
2348     Ops.push_back(Reg0);
2349     Ops.push_back(Chain);
2350     SDNode *VSt = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2351 
2352     // Transfer memoperands.
2353     CurDAG->setNodeMemRefs(cast<MachineSDNode>(VSt), {MemOp});
2354 
2355     ReplaceNode(N, VSt);
2356     return;
2357   }
2358 
2359   // Otherwise, quad registers are stored with two separate instructions,
2360   // where one stores the even registers and the other stores the odd registers.
2361 
2362   // Form the QQQQ REG_SEQUENCE.
2363   SDValue V0 = N->getOperand(Vec0Idx + 0);
2364   SDValue V1 = N->getOperand(Vec0Idx + 1);
2365   SDValue V2 = N->getOperand(Vec0Idx + 2);
2366   SDValue V3 = (NumVecs == 3)
2367     ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
2368     : N->getOperand(Vec0Idx + 3);
2369   SDValue RegSeq = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
2370 
2371   // Store the even D registers.  This is always an updating store, so that it
2372   // provides the address to the second store for the odd subregs.
2373   const SDValue OpsA[] = { MemAddr, Align, Reg0, RegSeq, Pred, Reg0, Chain };
2374   SDNode *VStA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
2375                                         MemAddr.getValueType(),
2376                                         MVT::Other, OpsA);
2377   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStA), {MemOp});
2378   Chain = SDValue(VStA, 1);
2379 
2380   // Store the odd D registers.
2381   Ops.push_back(SDValue(VStA, 0));
2382   Ops.push_back(Align);
2383   if (isUpdating) {
2384     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2385     assert(isa<ConstantSDNode>(Inc.getNode()) &&
2386            "only constant post-increment update allowed for VST3/4");
2387     (void)Inc;
2388     Ops.push_back(Reg0);
2389   }
2390   Ops.push_back(RegSeq);
2391   Ops.push_back(Pred);
2392   Ops.push_back(Reg0);
2393   Ops.push_back(Chain);
2394   SDNode *VStB = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys,
2395                                         Ops);
2396   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStB), {MemOp});
2397   ReplaceNode(N, VStB);
2398 }
2399 
2400 void ARMDAGToDAGISel::SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
2401                                       unsigned NumVecs,
2402                                       const uint16_t *DOpcodes,
2403                                       const uint16_t *QOpcodes) {
2404   assert(Subtarget->hasNEON());
2405   assert(NumVecs >=2 && NumVecs <= 4 && "VLDSTLane NumVecs out-of-range");
2406   SDLoc dl(N);
2407 
2408   SDValue MemAddr, Align;
2409   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2410                                    // nodes are not intrinsics.
2411   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2412   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
2413   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2414     return;
2415 
2416   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2417 
2418   SDValue Chain = N->getOperand(0);
2419   unsigned Lane =
2420     cast<ConstantSDNode>(N->getOperand(Vec0Idx + NumVecs))->getZExtValue();
2421   EVT VT = N->getOperand(Vec0Idx).getValueType();
2422   bool is64BitVector = VT.is64BitVector();
2423 
2424   unsigned Alignment = 0;
2425   if (NumVecs != 3) {
2426     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2427     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2428     if (Alignment > NumBytes)
2429       Alignment = NumBytes;
2430     if (Alignment < 8 && Alignment < NumBytes)
2431       Alignment = 0;
2432     // Alignment must be a power of two; make sure of that.
2433     Alignment = (Alignment & -Alignment);
2434     if (Alignment == 1)
2435       Alignment = 0;
2436   }
2437   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2438 
2439   unsigned OpcodeIndex;
2440   switch (VT.getSimpleVT().SimpleTy) {
2441   default: llvm_unreachable("unhandled vld/vst lane type");
2442     // Double-register operations:
2443   case MVT::v8i8:  OpcodeIndex = 0; break;
2444   case MVT::v4f16:
2445   case MVT::v4bf16:
2446   case MVT::v4i16: OpcodeIndex = 1; break;
2447   case MVT::v2f32:
2448   case MVT::v2i32: OpcodeIndex = 2; break;
2449     // Quad-register operations:
2450   case MVT::v8f16:
2451   case MVT::v8bf16:
2452   case MVT::v8i16: OpcodeIndex = 0; break;
2453   case MVT::v4f32:
2454   case MVT::v4i32: OpcodeIndex = 1; break;
2455   }
2456 
2457   std::vector<EVT> ResTys;
2458   if (IsLoad) {
2459     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2460     if (!is64BitVector)
2461       ResTyElts *= 2;
2462     ResTys.push_back(EVT::getVectorVT(*CurDAG->getContext(),
2463                                       MVT::i64, ResTyElts));
2464   }
2465   if (isUpdating)
2466     ResTys.push_back(MVT::i32);
2467   ResTys.push_back(MVT::Other);
2468 
2469   SDValue Pred = getAL(CurDAG, dl);
2470   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2471 
2472   SmallVector<SDValue, 8> Ops;
2473   Ops.push_back(MemAddr);
2474   Ops.push_back(Align);
2475   if (isUpdating) {
2476     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2477     bool IsImmUpdate =
2478         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
2479     Ops.push_back(IsImmUpdate ? Reg0 : Inc);
2480   }
2481 
2482   SDValue SuperReg;
2483   SDValue V0 = N->getOperand(Vec0Idx + 0);
2484   SDValue V1 = N->getOperand(Vec0Idx + 1);
2485   if (NumVecs == 2) {
2486     if (is64BitVector)
2487       SuperReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
2488     else
2489       SuperReg = SDValue(createQRegPairNode(MVT::v4i64, V0, V1), 0);
2490   } else {
2491     SDValue V2 = N->getOperand(Vec0Idx + 2);
2492     SDValue V3 = (NumVecs == 3)
2493       ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
2494       : N->getOperand(Vec0Idx + 3);
2495     if (is64BitVector)
2496       SuperReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
2497     else
2498       SuperReg = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
2499   }
2500   Ops.push_back(SuperReg);
2501   Ops.push_back(getI32Imm(Lane, dl));
2502   Ops.push_back(Pred);
2503   Ops.push_back(Reg0);
2504   Ops.push_back(Chain);
2505 
2506   unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2507                                   QOpcodes[OpcodeIndex]);
2508   SDNode *VLdLn = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2509   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdLn), {MemOp});
2510   if (!IsLoad) {
2511     ReplaceNode(N, VLdLn);
2512     return;
2513   }
2514 
2515   // Extract the subregisters.
2516   SuperReg = SDValue(VLdLn, 0);
2517   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
2518                     ARM::qsub_3 == ARM::qsub_0 + 3,
2519                 "Unexpected subreg numbering");
2520   unsigned Sub0 = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
2521   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2522     ReplaceUses(SDValue(N, Vec),
2523                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
2524   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdLn, 1));
2525   if (isUpdating)
2526     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdLn, 2));
2527   CurDAG->RemoveDeadNode(N);
2528 }
2529 
2530 template <typename SDValueVector>
2531 void ARMDAGToDAGISel::AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2532                                            SDValue PredicateMask) {
2533   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::Then, Loc, MVT::i32));
2534   Ops.push_back(PredicateMask);
2535   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2536 }
2537 
2538 template <typename SDValueVector>
2539 void ARMDAGToDAGISel::AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2540                                            SDValue PredicateMask,
2541                                            SDValue Inactive) {
2542   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::Then, Loc, MVT::i32));
2543   Ops.push_back(PredicateMask);
2544   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2545   Ops.push_back(Inactive);
2546 }
2547 
2548 template <typename SDValueVector>
2549 void ARMDAGToDAGISel::AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc) {
2550   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::None, Loc, MVT::i32));
2551   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2552   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2553 }
2554 
2555 template <typename SDValueVector>
2556 void ARMDAGToDAGISel::AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2557                                                 EVT InactiveTy) {
2558   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::None, Loc, MVT::i32));
2559   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2560   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2561   Ops.push_back(SDValue(
2562       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, Loc, InactiveTy), 0));
2563 }
2564 
2565 void ARMDAGToDAGISel::SelectMVE_WB(SDNode *N, const uint16_t *Opcodes,
2566                                    bool Predicated) {
2567   SDLoc Loc(N);
2568   SmallVector<SDValue, 8> Ops;
2569 
2570   uint16_t Opcode;
2571   switch (N->getValueType(1).getVectorElementType().getSizeInBits()) {
2572   case 32:
2573     Opcode = Opcodes[0];
2574     break;
2575   case 64:
2576     Opcode = Opcodes[1];
2577     break;
2578   default:
2579     llvm_unreachable("bad vector element size in SelectMVE_WB");
2580   }
2581 
2582   Ops.push_back(N->getOperand(2)); // vector of base addresses
2583 
2584   int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2585   Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate offset
2586 
2587   if (Predicated)
2588     AddMVEPredicateToOps(Ops, Loc, N->getOperand(4));
2589   else
2590     AddEmptyMVEPredicateToOps(Ops, Loc);
2591 
2592   Ops.push_back(N->getOperand(0)); // chain
2593 
2594   SmallVector<EVT, 8> VTs;
2595   VTs.push_back(N->getValueType(1));
2596   VTs.push_back(N->getValueType(0));
2597   VTs.push_back(N->getValueType(2));
2598 
2599   SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), VTs, Ops);
2600   ReplaceUses(SDValue(N, 0), SDValue(New, 1));
2601   ReplaceUses(SDValue(N, 1), SDValue(New, 0));
2602   ReplaceUses(SDValue(N, 2), SDValue(New, 2));
2603   transferMemOperands(N, New);
2604   CurDAG->RemoveDeadNode(N);
2605 }
2606 
2607 void ARMDAGToDAGISel::SelectMVE_LongShift(SDNode *N, uint16_t Opcode,
2608                                           bool Immediate,
2609                                           bool HasSaturationOperand) {
2610   SDLoc Loc(N);
2611   SmallVector<SDValue, 8> Ops;
2612 
2613   // Two 32-bit halves of the value to be shifted
2614   Ops.push_back(N->getOperand(1));
2615   Ops.push_back(N->getOperand(2));
2616 
2617   // The shift count
2618   if (Immediate) {
2619     int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2620     Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate shift count
2621   } else {
2622     Ops.push_back(N->getOperand(3));
2623   }
2624 
2625   // The immediate saturation operand, if any
2626   if (HasSaturationOperand) {
2627     int32_t SatOp = cast<ConstantSDNode>(N->getOperand(4))->getZExtValue();
2628     int SatBit = (SatOp == 64 ? 0 : 1);
2629     Ops.push_back(getI32Imm(SatBit, Loc));
2630   }
2631 
2632   // MVE scalar shifts are IT-predicable, so include the standard
2633   // predicate arguments.
2634   Ops.push_back(getAL(CurDAG, Loc));
2635   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2636 
2637   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), makeArrayRef(Ops));
2638 }
2639 
2640 void ARMDAGToDAGISel::SelectMVE_VADCSBC(SDNode *N, uint16_t OpcodeWithCarry,
2641                                         uint16_t OpcodeWithNoCarry,
2642                                         bool Add, bool Predicated) {
2643   SDLoc Loc(N);
2644   SmallVector<SDValue, 8> Ops;
2645   uint16_t Opcode;
2646 
2647   unsigned FirstInputOp = Predicated ? 2 : 1;
2648 
2649   // Two input vectors and the input carry flag
2650   Ops.push_back(N->getOperand(FirstInputOp));
2651   Ops.push_back(N->getOperand(FirstInputOp + 1));
2652   SDValue CarryIn = N->getOperand(FirstInputOp + 2);
2653   ConstantSDNode *CarryInConstant = dyn_cast<ConstantSDNode>(CarryIn);
2654   uint32_t CarryMask = 1 << 29;
2655   uint32_t CarryExpected = Add ? 0 : CarryMask;
2656   if (CarryInConstant &&
2657       (CarryInConstant->getZExtValue() & CarryMask) == CarryExpected) {
2658     Opcode = OpcodeWithNoCarry;
2659   } else {
2660     Ops.push_back(CarryIn);
2661     Opcode = OpcodeWithCarry;
2662   }
2663 
2664   if (Predicated)
2665     AddMVEPredicateToOps(Ops, Loc,
2666                          N->getOperand(FirstInputOp + 3),  // predicate
2667                          N->getOperand(FirstInputOp - 1)); // inactive
2668   else
2669     AddEmptyMVEPredicateToOps(Ops, Loc, N->getValueType(0));
2670 
2671   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), makeArrayRef(Ops));
2672 }
2673 
2674 void ARMDAGToDAGISel::SelectMVE_VSHLC(SDNode *N, bool Predicated) {
2675   SDLoc Loc(N);
2676   SmallVector<SDValue, 8> Ops;
2677 
2678   // One vector input, followed by a 32-bit word of bits to shift in
2679   // and then an immediate shift count
2680   Ops.push_back(N->getOperand(1));
2681   Ops.push_back(N->getOperand(2));
2682   int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2683   Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate shift count
2684 
2685   if (Predicated)
2686     AddMVEPredicateToOps(Ops, Loc, N->getOperand(4));
2687   else
2688     AddEmptyMVEPredicateToOps(Ops, Loc);
2689 
2690   CurDAG->SelectNodeTo(N, ARM::MVE_VSHLC, N->getVTList(), makeArrayRef(Ops));
2691 }
2692 
2693 static bool SDValueToConstBool(SDValue SDVal) {
2694   assert(isa<ConstantSDNode>(SDVal) && "expected a compile-time constant");
2695   ConstantSDNode *SDValConstant = dyn_cast<ConstantSDNode>(SDVal);
2696   uint64_t Value = SDValConstant->getZExtValue();
2697   assert((Value == 0 || Value == 1) && "expected value 0 or 1");
2698   return Value;
2699 }
2700 
2701 void ARMDAGToDAGISel::SelectBaseMVE_VMLLDAV(SDNode *N, bool Predicated,
2702                                             const uint16_t *OpcodesS,
2703                                             const uint16_t *OpcodesU,
2704                                             size_t Stride, size_t TySize) {
2705   assert(TySize < Stride && "Invalid TySize");
2706   bool IsUnsigned = SDValueToConstBool(N->getOperand(1));
2707   bool IsSub = SDValueToConstBool(N->getOperand(2));
2708   bool IsExchange = SDValueToConstBool(N->getOperand(3));
2709   if (IsUnsigned) {
2710     assert(!IsSub &&
2711            "Unsigned versions of vmlsldav[a]/vrmlsldavh[a] do not exist");
2712     assert(!IsExchange &&
2713            "Unsigned versions of vmlaldav[a]x/vrmlaldavh[a]x do not exist");
2714   }
2715 
2716   auto OpIsZero = [N](size_t OpNo) {
2717     if (ConstantSDNode *OpConst = dyn_cast<ConstantSDNode>(N->getOperand(OpNo)))
2718       if (OpConst->getZExtValue() == 0)
2719         return true;
2720     return false;
2721   };
2722 
2723   // If the input accumulator value is not zero, select an instruction with
2724   // accumulator, otherwise select an instruction without accumulator
2725   bool IsAccum = !(OpIsZero(4) && OpIsZero(5));
2726 
2727   const uint16_t *Opcodes = IsUnsigned ? OpcodesU : OpcodesS;
2728   if (IsSub)
2729     Opcodes += 4 * Stride;
2730   if (IsExchange)
2731     Opcodes += 2 * Stride;
2732   if (IsAccum)
2733     Opcodes += Stride;
2734   uint16_t Opcode = Opcodes[TySize];
2735 
2736   SDLoc Loc(N);
2737   SmallVector<SDValue, 8> Ops;
2738   // Push the accumulator operands, if they are used
2739   if (IsAccum) {
2740     Ops.push_back(N->getOperand(4));
2741     Ops.push_back(N->getOperand(5));
2742   }
2743   // Push the two vector operands
2744   Ops.push_back(N->getOperand(6));
2745   Ops.push_back(N->getOperand(7));
2746 
2747   if (Predicated)
2748     AddMVEPredicateToOps(Ops, Loc, N->getOperand(8));
2749   else
2750     AddEmptyMVEPredicateToOps(Ops, Loc);
2751 
2752   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), makeArrayRef(Ops));
2753 }
2754 
2755 void ARMDAGToDAGISel::SelectMVE_VMLLDAV(SDNode *N, bool Predicated,
2756                                         const uint16_t *OpcodesS,
2757                                         const uint16_t *OpcodesU) {
2758   EVT VecTy = N->getOperand(6).getValueType();
2759   size_t SizeIndex;
2760   switch (VecTy.getVectorElementType().getSizeInBits()) {
2761   case 16:
2762     SizeIndex = 0;
2763     break;
2764   case 32:
2765     SizeIndex = 1;
2766     break;
2767   default:
2768     llvm_unreachable("bad vector element size");
2769   }
2770 
2771   SelectBaseMVE_VMLLDAV(N, Predicated, OpcodesS, OpcodesU, 2, SizeIndex);
2772 }
2773 
2774 void ARMDAGToDAGISel::SelectMVE_VRMLLDAVH(SDNode *N, bool Predicated,
2775                                           const uint16_t *OpcodesS,
2776                                           const uint16_t *OpcodesU) {
2777   assert(
2778       N->getOperand(6).getValueType().getVectorElementType().getSizeInBits() ==
2779           32 &&
2780       "bad vector element size");
2781   SelectBaseMVE_VMLLDAV(N, Predicated, OpcodesS, OpcodesU, 1, 0);
2782 }
2783 
2784 void ARMDAGToDAGISel::SelectMVE_VLD(SDNode *N, unsigned NumVecs,
2785                                     const uint16_t *const *Opcodes,
2786                                     bool HasWriteback) {
2787   EVT VT = N->getValueType(0);
2788   SDLoc Loc(N);
2789 
2790   const uint16_t *OurOpcodes;
2791   switch (VT.getVectorElementType().getSizeInBits()) {
2792   case 8:
2793     OurOpcodes = Opcodes[0];
2794     break;
2795   case 16:
2796     OurOpcodes = Opcodes[1];
2797     break;
2798   case 32:
2799     OurOpcodes = Opcodes[2];
2800     break;
2801   default:
2802     llvm_unreachable("bad vector element size in SelectMVE_VLD");
2803   }
2804 
2805   EVT DataTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, NumVecs * 2);
2806   SmallVector<EVT, 4> ResultTys = {DataTy, MVT::Other};
2807   unsigned PtrOperand = HasWriteback ? 1 : 2;
2808 
2809   auto Data = SDValue(
2810       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, Loc, DataTy), 0);
2811   SDValue Chain = N->getOperand(0);
2812   // Add a MVE_VLDn instruction for each Vec, except the last
2813   for (unsigned Stage = 0; Stage < NumVecs - 1; ++Stage) {
2814     SDValue Ops[] = {Data, N->getOperand(PtrOperand), Chain};
2815     auto LoadInst =
2816         CurDAG->getMachineNode(OurOpcodes[Stage], Loc, ResultTys, Ops);
2817     Data = SDValue(LoadInst, 0);
2818     Chain = SDValue(LoadInst, 1);
2819     transferMemOperands(N, LoadInst);
2820   }
2821   // The last may need a writeback on it
2822   if (HasWriteback)
2823     ResultTys = {DataTy, MVT::i32, MVT::Other};
2824   SDValue Ops[] = {Data, N->getOperand(PtrOperand), Chain};
2825   auto LoadInst =
2826       CurDAG->getMachineNode(OurOpcodes[NumVecs - 1], Loc, ResultTys, Ops);
2827   transferMemOperands(N, LoadInst);
2828 
2829   unsigned i;
2830   for (i = 0; i < NumVecs; i++)
2831     ReplaceUses(SDValue(N, i),
2832                 CurDAG->getTargetExtractSubreg(ARM::qsub_0 + i, Loc, VT,
2833                                                SDValue(LoadInst, 0)));
2834   if (HasWriteback)
2835     ReplaceUses(SDValue(N, i++), SDValue(LoadInst, 1));
2836   ReplaceUses(SDValue(N, i), SDValue(LoadInst, HasWriteback ? 2 : 1));
2837   CurDAG->RemoveDeadNode(N);
2838 }
2839 
2840 void ARMDAGToDAGISel::SelectMVE_VxDUP(SDNode *N, const uint16_t *Opcodes,
2841                                       bool Wrapping, bool Predicated) {
2842   EVT VT = N->getValueType(0);
2843   SDLoc Loc(N);
2844 
2845   uint16_t Opcode;
2846   switch (VT.getScalarSizeInBits()) {
2847   case 8:
2848     Opcode = Opcodes[0];
2849     break;
2850   case 16:
2851     Opcode = Opcodes[1];
2852     break;
2853   case 32:
2854     Opcode = Opcodes[2];
2855     break;
2856   default:
2857     llvm_unreachable("bad vector element size in SelectMVE_VxDUP");
2858   }
2859 
2860   SmallVector<SDValue, 8> Ops;
2861   unsigned OpIdx = 1;
2862 
2863   SDValue Inactive;
2864   if (Predicated)
2865     Inactive = N->getOperand(OpIdx++);
2866 
2867   Ops.push_back(N->getOperand(OpIdx++));     // base
2868   if (Wrapping)
2869     Ops.push_back(N->getOperand(OpIdx++));   // limit
2870 
2871   SDValue ImmOp = N->getOperand(OpIdx++);    // step
2872   int ImmValue = cast<ConstantSDNode>(ImmOp)->getZExtValue();
2873   Ops.push_back(getI32Imm(ImmValue, Loc));
2874 
2875   if (Predicated)
2876     AddMVEPredicateToOps(Ops, Loc, N->getOperand(OpIdx), Inactive);
2877   else
2878     AddEmptyMVEPredicateToOps(Ops, Loc, N->getValueType(0));
2879 
2880   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), makeArrayRef(Ops));
2881 }
2882 
2883 void ARMDAGToDAGISel::SelectCDE_CXxD(SDNode *N, uint16_t Opcode,
2884                                      size_t NumExtraOps, bool HasAccum) {
2885   bool IsBigEndian = CurDAG->getDataLayout().isBigEndian();
2886   SDLoc Loc(N);
2887   SmallVector<SDValue, 8> Ops;
2888 
2889   unsigned OpIdx = 1;
2890 
2891   // Convert and append the immediate operand designating the coprocessor.
2892   SDValue ImmCorpoc = N->getOperand(OpIdx++);
2893   uint32_t ImmCoprocVal = cast<ConstantSDNode>(ImmCorpoc)->getZExtValue();
2894   Ops.push_back(getI32Imm(ImmCoprocVal, Loc));
2895 
2896   // For accumulating variants copy the low and high order parts of the
2897   // accumulator into a register pair and add it to the operand vector.
2898   if (HasAccum) {
2899     SDValue AccLo = N->getOperand(OpIdx++);
2900     SDValue AccHi = N->getOperand(OpIdx++);
2901     if (IsBigEndian)
2902       std::swap(AccLo, AccHi);
2903     Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, AccLo, AccHi), 0));
2904   }
2905 
2906   // Copy extra operands as-is.
2907   for (size_t I = 0; I < NumExtraOps; I++)
2908     Ops.push_back(N->getOperand(OpIdx++));
2909 
2910   // Convert and append the immediate operand
2911   SDValue Imm = N->getOperand(OpIdx);
2912   uint32_t ImmVal = cast<ConstantSDNode>(Imm)->getZExtValue();
2913   Ops.push_back(getI32Imm(ImmVal, Loc));
2914 
2915   // Accumulating variants are IT-predicable, add predicate operands.
2916   if (HasAccum) {
2917     SDValue Pred = getAL(CurDAG, Loc);
2918     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
2919     Ops.push_back(Pred);
2920     Ops.push_back(PredReg);
2921   }
2922 
2923   // Create the CDE intruction
2924   SDNode *InstrNode = CurDAG->getMachineNode(Opcode, Loc, MVT::Untyped, Ops);
2925   SDValue ResultPair = SDValue(InstrNode, 0);
2926 
2927   // The original intrinsic had two outputs, and the output of the dual-register
2928   // CDE instruction is a register pair. We need to extract the two subregisters
2929   // and replace all uses of the original outputs with the extracted
2930   // subregisters.
2931   uint16_t SubRegs[2] = {ARM::gsub_0, ARM::gsub_1};
2932   if (IsBigEndian)
2933     std::swap(SubRegs[0], SubRegs[1]);
2934 
2935   for (size_t ResIdx = 0; ResIdx < 2; ResIdx++) {
2936     if (SDValue(N, ResIdx).use_empty())
2937       continue;
2938     SDValue SubReg = CurDAG->getTargetExtractSubreg(SubRegs[ResIdx], Loc,
2939                                                     MVT::i32, ResultPair);
2940     ReplaceUses(SDValue(N, ResIdx), SubReg);
2941   }
2942 
2943   CurDAG->RemoveDeadNode(N);
2944 }
2945 
2946 void ARMDAGToDAGISel::SelectVLDDup(SDNode *N, bool IsIntrinsic,
2947                                    bool isUpdating, unsigned NumVecs,
2948                                    const uint16_t *DOpcodes,
2949                                    const uint16_t *QOpcodes0,
2950                                    const uint16_t *QOpcodes1) {
2951   assert(Subtarget->hasNEON());
2952   assert(NumVecs >= 1 && NumVecs <= 4 && "VLDDup NumVecs out-of-range");
2953   SDLoc dl(N);
2954 
2955   SDValue MemAddr, Align;
2956   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2957   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2958     return;
2959 
2960   SDValue Chain = N->getOperand(0);
2961   EVT VT = N->getValueType(0);
2962   bool is64BitVector = VT.is64BitVector();
2963 
2964   unsigned Alignment = 0;
2965   if (NumVecs != 3) {
2966     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2967     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2968     if (Alignment > NumBytes)
2969       Alignment = NumBytes;
2970     if (Alignment < 8 && Alignment < NumBytes)
2971       Alignment = 0;
2972     // Alignment must be a power of two; make sure of that.
2973     Alignment = (Alignment & -Alignment);
2974     if (Alignment == 1)
2975       Alignment = 0;
2976   }
2977   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2978 
2979   unsigned OpcodeIndex;
2980   switch (VT.getSimpleVT().SimpleTy) {
2981   default: llvm_unreachable("unhandled vld-dup type");
2982   case MVT::v8i8:
2983   case MVT::v16i8: OpcodeIndex = 0; break;
2984   case MVT::v4i16:
2985   case MVT::v8i16:
2986   case MVT::v4f16:
2987   case MVT::v8f16:
2988   case MVT::v4bf16:
2989   case MVT::v8bf16:
2990                   OpcodeIndex = 1; break;
2991   case MVT::v2f32:
2992   case MVT::v2i32:
2993   case MVT::v4f32:
2994   case MVT::v4i32: OpcodeIndex = 2; break;
2995   case MVT::v1f64:
2996   case MVT::v1i64: OpcodeIndex = 3; break;
2997   }
2998 
2999   unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
3000   if (!is64BitVector)
3001     ResTyElts *= 2;
3002   EVT ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
3003 
3004   std::vector<EVT> ResTys;
3005   ResTys.push_back(ResTy);
3006   if (isUpdating)
3007     ResTys.push_back(MVT::i32);
3008   ResTys.push_back(MVT::Other);
3009 
3010   SDValue Pred = getAL(CurDAG, dl);
3011   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3012 
3013   SmallVector<SDValue, 6> Ops;
3014   Ops.push_back(MemAddr);
3015   Ops.push_back(Align);
3016   unsigned Opc = is64BitVector    ? DOpcodes[OpcodeIndex]
3017                  : (NumVecs == 1) ? QOpcodes0[OpcodeIndex]
3018                                   : QOpcodes1[OpcodeIndex];
3019   if (isUpdating) {
3020     SDValue Inc = N->getOperand(2);
3021     bool IsImmUpdate =
3022         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
3023     if (IsImmUpdate) {
3024       if (!isVLDfixed(Opc))
3025         Ops.push_back(Reg0);
3026     } else {
3027       if (isVLDfixed(Opc))
3028         Opc = getVLDSTRegisterUpdateOpcode(Opc);
3029       Ops.push_back(Inc);
3030     }
3031   }
3032   if (is64BitVector || NumVecs == 1) {
3033     // Double registers and VLD1 quad registers are directly supported.
3034   } else if (NumVecs == 2) {
3035     const SDValue OpsA[] = {MemAddr, Align, Pred, Reg0, Chain};
3036     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl, ResTy,
3037                                           MVT::Other, OpsA);
3038     Chain = SDValue(VLdA, 1);
3039   } else {
3040     SDValue ImplDef = SDValue(
3041         CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
3042     const SDValue OpsA[] = {MemAddr, Align, ImplDef, Pred, Reg0, Chain};
3043     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl, ResTy,
3044                                           MVT::Other, OpsA);
3045     Ops.push_back(SDValue(VLdA, 0));
3046     Chain = SDValue(VLdA, 1);
3047   }
3048 
3049   Ops.push_back(Pred);
3050   Ops.push_back(Reg0);
3051   Ops.push_back(Chain);
3052 
3053   SDNode *VLdDup = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
3054 
3055   // Transfer memoperands.
3056   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
3057   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdDup), {MemOp});
3058 
3059   // Extract the subregisters.
3060   if (NumVecs == 1) {
3061     ReplaceUses(SDValue(N, 0), SDValue(VLdDup, 0));
3062   } else {
3063     SDValue SuperReg = SDValue(VLdDup, 0);
3064     static_assert(ARM::dsub_7 == ARM::dsub_0 + 7, "Unexpected subreg numbering");
3065     unsigned SubIdx = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
3066     for (unsigned Vec = 0; Vec != NumVecs; ++Vec) {
3067       ReplaceUses(SDValue(N, Vec),
3068                   CurDAG->getTargetExtractSubreg(SubIdx+Vec, dl, VT, SuperReg));
3069     }
3070   }
3071   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdDup, 1));
3072   if (isUpdating)
3073     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdDup, 2));
3074   CurDAG->RemoveDeadNode(N);
3075 }
3076 
3077 bool ARMDAGToDAGISel::tryInsertVectorElt(SDNode *N) {
3078   if (!Subtarget->hasMVEIntegerOps())
3079     return false;
3080 
3081   SDLoc dl(N);
3082 
3083   // We are trying to use VMOV/VMOVX/VINS to more efficiently lower insert and
3084   // extracts of v8f16 and v8i16 vectors. Check that we have two adjacent
3085   // inserts of the correct type:
3086   SDValue Ins1 = SDValue(N, 0);
3087   SDValue Ins2 = N->getOperand(0);
3088   EVT VT = Ins1.getValueType();
3089   if (Ins2.getOpcode() != ISD::INSERT_VECTOR_ELT || !Ins2.hasOneUse() ||
3090       !isa<ConstantSDNode>(Ins1.getOperand(2)) ||
3091       !isa<ConstantSDNode>(Ins2.getOperand(2)) ||
3092       (VT != MVT::v8f16 && VT != MVT::v8i16) || (Ins2.getValueType() != VT))
3093     return false;
3094 
3095   unsigned Lane1 = Ins1.getConstantOperandVal(2);
3096   unsigned Lane2 = Ins2.getConstantOperandVal(2);
3097   if (Lane2 % 2 != 0 || Lane1 != Lane2 + 1)
3098     return false;
3099 
3100   // If the inserted values will be able to use T/B already, leave it to the
3101   // existing tablegen patterns. For example VCVTT/VCVTB.
3102   SDValue Val1 = Ins1.getOperand(1);
3103   SDValue Val2 = Ins2.getOperand(1);
3104   if (Val1.getOpcode() == ISD::FP_ROUND || Val2.getOpcode() == ISD::FP_ROUND)
3105     return false;
3106 
3107   // Check if the inserted values are both extracts.
3108   if ((Val1.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
3109        Val1.getOpcode() == ARMISD::VGETLANEu) &&
3110       (Val2.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
3111        Val2.getOpcode() == ARMISD::VGETLANEu) &&
3112       isa<ConstantSDNode>(Val1.getOperand(1)) &&
3113       isa<ConstantSDNode>(Val2.getOperand(1)) &&
3114       (Val1.getOperand(0).getValueType() == MVT::v8f16 ||
3115        Val1.getOperand(0).getValueType() == MVT::v8i16) &&
3116       (Val2.getOperand(0).getValueType() == MVT::v8f16 ||
3117        Val2.getOperand(0).getValueType() == MVT::v8i16)) {
3118     unsigned ExtractLane1 = Val1.getConstantOperandVal(1);
3119     unsigned ExtractLane2 = Val2.getConstantOperandVal(1);
3120 
3121     // If the two extracted lanes are from the same place and adjacent, this
3122     // simplifies into a f32 lane move.
3123     if (Val1.getOperand(0) == Val2.getOperand(0) && ExtractLane2 % 2 == 0 &&
3124         ExtractLane1 == ExtractLane2 + 1) {
3125       SDValue NewExt = CurDAG->getTargetExtractSubreg(
3126           ARM::ssub_0 + ExtractLane2 / 2, dl, MVT::f32, Val1.getOperand(0));
3127       SDValue NewIns = CurDAG->getTargetInsertSubreg(
3128           ARM::ssub_0 + Lane2 / 2, dl, VT, Ins2.getOperand(0),
3129           NewExt);
3130       ReplaceUses(Ins1, NewIns);
3131       return true;
3132     }
3133 
3134     // Else v8i16 pattern of an extract and an insert, with a optional vmovx for
3135     // extracting odd lanes.
3136     if (VT == MVT::v8i16) {
3137       SDValue Inp1 = CurDAG->getTargetExtractSubreg(
3138           ARM::ssub_0 + ExtractLane1 / 2, dl, MVT::f32, Val1.getOperand(0));
3139       SDValue Inp2 = CurDAG->getTargetExtractSubreg(
3140           ARM::ssub_0 + ExtractLane2 / 2, dl, MVT::f32, Val2.getOperand(0));
3141       if (ExtractLane1 % 2 != 0)
3142         Inp1 = SDValue(CurDAG->getMachineNode(ARM::VMOVH, dl, MVT::f32, Inp1), 0);
3143       if (ExtractLane2 % 2 != 0)
3144         Inp2 = SDValue(CurDAG->getMachineNode(ARM::VMOVH, dl, MVT::f32, Inp2), 0);
3145       SDNode *VINS = CurDAG->getMachineNode(ARM::VINSH, dl, MVT::f32, Inp2, Inp1);
3146       SDValue NewIns =
3147           CurDAG->getTargetInsertSubreg(ARM::ssub_0 + Lane2 / 2, dl, MVT::v4f32,
3148                                         Ins2.getOperand(0), SDValue(VINS, 0));
3149       ReplaceUses(Ins1, NewIns);
3150       return true;
3151     }
3152   }
3153 
3154   // The inserted values are not extracted - if they are f16 then insert them
3155   // directly using a VINS.
3156   if (VT == MVT::v8f16) {
3157     SDNode *VINS = CurDAG->getMachineNode(ARM::VINSH, dl, MVT::f32, Val2, Val1);
3158     SDValue NewIns =
3159         CurDAG->getTargetInsertSubreg(ARM::ssub_0 + Lane2 / 2, dl, MVT::v4f32,
3160                                       Ins2.getOperand(0), SDValue(VINS, 0));
3161     ReplaceUses(Ins1, NewIns);
3162     return true;
3163   }
3164 
3165   return false;
3166 }
3167 
3168 bool ARMDAGToDAGISel::transformFixedFloatingPointConversion(SDNode *N,
3169                                                             SDNode *FMul,
3170                                                             bool IsUnsigned,
3171                                                             bool FixedToFloat) {
3172   auto Type = N->getValueType(0);
3173   unsigned ScalarBits = Type.getScalarSizeInBits();
3174   if (ScalarBits > 32)
3175     return false;
3176 
3177   SDNodeFlags FMulFlags = FMul->getFlags();
3178   // The fixed-point vcvt and vcvt+vmul are not always equivalent if inf is
3179   // allowed in 16 bit unsigned floats
3180   if (ScalarBits == 16 && !FMulFlags.hasNoInfs() && IsUnsigned)
3181     return false;
3182 
3183   SDValue ImmNode = FMul->getOperand(1);
3184   SDValue VecVal = FMul->getOperand(0);
3185   if (VecVal->getOpcode() == ISD::UINT_TO_FP ||
3186       VecVal->getOpcode() == ISD::SINT_TO_FP)
3187     VecVal = VecVal->getOperand(0);
3188 
3189   if (VecVal.getValueType().getScalarSizeInBits() != ScalarBits)
3190     return false;
3191 
3192   if (ImmNode.getOpcode() == ISD::BITCAST) {
3193     if (ImmNode.getValueType().getScalarSizeInBits() != ScalarBits)
3194       return false;
3195     ImmNode = ImmNode.getOperand(0);
3196   }
3197 
3198   if (ImmNode.getValueType().getScalarSizeInBits() != ScalarBits)
3199     return false;
3200 
3201   APFloat ImmAPF(0.0f);
3202   switch (ImmNode.getOpcode()) {
3203   case ARMISD::VMOVIMM:
3204   case ARMISD::VDUP: {
3205     if (!isa<ConstantSDNode>(ImmNode.getOperand(0)))
3206       return false;
3207     unsigned Imm = ImmNode.getConstantOperandVal(0);
3208     if (ImmNode.getOpcode() == ARMISD::VMOVIMM)
3209       Imm = ARM_AM::decodeVMOVModImm(Imm, ScalarBits);
3210     ImmAPF =
3211         APFloat(ScalarBits == 32 ? APFloat::IEEEsingle() : APFloat::IEEEhalf(),
3212                 APInt(ScalarBits, Imm));
3213     break;
3214   }
3215   case ARMISD::VMOVFPIMM: {
3216     ImmAPF = APFloat(ARM_AM::getFPImmFloat(ImmNode.getConstantOperandVal(0)));
3217     break;
3218   }
3219   default:
3220     return false;
3221   }
3222 
3223   // Where n is the number of fractional bits, multiplying by 2^n will convert
3224   // from float to fixed and multiplying by 2^-n will convert from fixed to
3225   // float. Taking log2 of the factor (after taking the inverse in the case of
3226   // float to fixed) will give n.
3227   APFloat ToConvert = ImmAPF;
3228   if (FixedToFloat) {
3229     if (!ImmAPF.getExactInverse(&ToConvert))
3230       return false;
3231   }
3232   APSInt Converted(64, 0);
3233   bool IsExact;
3234   ToConvert.convertToInteger(Converted, llvm::RoundingMode::NearestTiesToEven,
3235                              &IsExact);
3236   if (!IsExact || !Converted.isPowerOf2())
3237     return false;
3238 
3239   unsigned FracBits = Converted.logBase2();
3240   if (FracBits > ScalarBits)
3241     return false;
3242 
3243   SmallVector<SDValue, 3> Ops{
3244       VecVal, CurDAG->getConstant(FracBits, SDLoc(N), MVT::i32)};
3245   AddEmptyMVEPredicateToOps(Ops, SDLoc(N), Type);
3246 
3247   unsigned int Opcode;
3248   switch (ScalarBits) {
3249   case 16:
3250     if (FixedToFloat)
3251       Opcode = IsUnsigned ? ARM::MVE_VCVTf16u16_fix : ARM::MVE_VCVTf16s16_fix;
3252     else
3253       Opcode = IsUnsigned ? ARM::MVE_VCVTu16f16_fix : ARM::MVE_VCVTs16f16_fix;
3254     break;
3255   case 32:
3256     if (FixedToFloat)
3257       Opcode = IsUnsigned ? ARM::MVE_VCVTf32u32_fix : ARM::MVE_VCVTf32s32_fix;
3258     else
3259       Opcode = IsUnsigned ? ARM::MVE_VCVTu32f32_fix : ARM::MVE_VCVTs32f32_fix;
3260     break;
3261   default:
3262     llvm_unreachable("unexpected number of scalar bits");
3263     break;
3264   }
3265 
3266   ReplaceNode(N, CurDAG->getMachineNode(Opcode, SDLoc(N), Type, Ops));
3267   return true;
3268 }
3269 
3270 bool ARMDAGToDAGISel::tryFP_TO_INT(SDNode *N, SDLoc dl) {
3271   // Transform a floating-point to fixed-point conversion to a VCVT
3272   if (!Subtarget->hasMVEFloatOps())
3273     return false;
3274   EVT Type = N->getValueType(0);
3275   if (!Type.isVector())
3276     return false;
3277   unsigned int ScalarBits = Type.getScalarSizeInBits();
3278 
3279   bool IsUnsigned = N->getOpcode() == ISD::FP_TO_UINT;
3280   SDNode *Node = N->getOperand(0).getNode();
3281 
3282   // floating-point to fixed-point with one fractional bit gets turned into an
3283   // FP_TO_[U|S]INT(FADD (x, x)) rather than an FP_TO_[U|S]INT(FMUL (x, y))
3284   if (Node->getOpcode() == ISD::FADD) {
3285     if (Node->getOperand(0) != Node->getOperand(1))
3286       return false;
3287     SDNodeFlags Flags = Node->getFlags();
3288     // The fixed-point vcvt and vcvt+vmul are not always equivalent if inf is
3289     // allowed in 16 bit unsigned floats
3290     if (ScalarBits == 16 && !Flags.hasNoInfs() && IsUnsigned)
3291       return false;
3292 
3293     unsigned Opcode;
3294     switch (ScalarBits) {
3295     case 16:
3296       Opcode = IsUnsigned ? ARM::MVE_VCVTu16f16_fix : ARM::MVE_VCVTs16f16_fix;
3297       break;
3298     case 32:
3299       Opcode = IsUnsigned ? ARM::MVE_VCVTu32f32_fix : ARM::MVE_VCVTs32f32_fix;
3300       break;
3301     }
3302     SmallVector<SDValue, 3> Ops{Node->getOperand(0),
3303                                 CurDAG->getConstant(1, dl, MVT::i32)};
3304     AddEmptyMVEPredicateToOps(Ops, dl, Type);
3305 
3306     ReplaceNode(N, CurDAG->getMachineNode(Opcode, dl, Type, Ops));
3307     return true;
3308   }
3309 
3310   if (Node->getOpcode() != ISD::FMUL)
3311     return false;
3312 
3313   return transformFixedFloatingPointConversion(N, Node, IsUnsigned, false);
3314 }
3315 
3316 bool ARMDAGToDAGISel::tryFMULFixed(SDNode *N, SDLoc dl) {
3317   // Transform a fixed-point to floating-point conversion to a VCVT
3318   if (!Subtarget->hasMVEFloatOps())
3319     return false;
3320   auto Type = N->getValueType(0);
3321   if (!Type.isVector())
3322     return false;
3323 
3324   auto LHS = N->getOperand(0);
3325   if (LHS.getOpcode() != ISD::SINT_TO_FP && LHS.getOpcode() != ISD::UINT_TO_FP)
3326     return false;
3327 
3328   return transformFixedFloatingPointConversion(
3329       N, N, LHS.getOpcode() == ISD::UINT_TO_FP, true);
3330 }
3331 
3332 bool ARMDAGToDAGISel::tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned) {
3333   if (!Subtarget->hasV6T2Ops())
3334     return false;
3335 
3336   unsigned Opc = isSigned
3337     ? (Subtarget->isThumb() ? ARM::t2SBFX : ARM::SBFX)
3338     : (Subtarget->isThumb() ? ARM::t2UBFX : ARM::UBFX);
3339   SDLoc dl(N);
3340 
3341   // For unsigned extracts, check for a shift right and mask
3342   unsigned And_imm = 0;
3343   if (N->getOpcode() == ISD::AND) {
3344     if (isOpcWithIntImmediate(N, ISD::AND, And_imm)) {
3345 
3346       // The immediate is a mask of the low bits iff imm & (imm+1) == 0
3347       if (And_imm & (And_imm + 1))
3348         return false;
3349 
3350       unsigned Srl_imm = 0;
3351       if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL,
3352                                 Srl_imm)) {
3353         assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3354 
3355         // Mask off the unnecessary bits of the AND immediate; normally
3356         // DAGCombine will do this, but that might not happen if
3357         // targetShrinkDemandedConstant chooses a different immediate.
3358         And_imm &= -1U >> Srl_imm;
3359 
3360         // Note: The width operand is encoded as width-1.
3361         unsigned Width = countTrailingOnes(And_imm) - 1;
3362         unsigned LSB = Srl_imm;
3363 
3364         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3365 
3366         if ((LSB + Width + 1) == N->getValueType(0).getSizeInBits()) {
3367           // It's cheaper to use a right shift to extract the top bits.
3368           if (Subtarget->isThumb()) {
3369             Opc = isSigned ? ARM::t2ASRri : ARM::t2LSRri;
3370             SDValue Ops[] = { N->getOperand(0).getOperand(0),
3371                               CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3372                               getAL(CurDAG, dl), Reg0, Reg0 };
3373             CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3374             return true;
3375           }
3376 
3377           // ARM models shift instructions as MOVsi with shifter operand.
3378           ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(ISD::SRL);
3379           SDValue ShOpc =
3380             CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, LSB), dl,
3381                                       MVT::i32);
3382           SDValue Ops[] = { N->getOperand(0).getOperand(0), ShOpc,
3383                             getAL(CurDAG, dl), Reg0, Reg0 };
3384           CurDAG->SelectNodeTo(N, ARM::MOVsi, MVT::i32, Ops);
3385           return true;
3386         }
3387 
3388         assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3389         SDValue Ops[] = { N->getOperand(0).getOperand(0),
3390                           CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3391                           CurDAG->getTargetConstant(Width, dl, MVT::i32),
3392                           getAL(CurDAG, dl), Reg0 };
3393         CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3394         return true;
3395       }
3396     }
3397     return false;
3398   }
3399 
3400   // Otherwise, we're looking for a shift of a shift
3401   unsigned Shl_imm = 0;
3402   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, Shl_imm)) {
3403     assert(Shl_imm > 0 && Shl_imm < 32 && "bad amount in shift node!");
3404     unsigned Srl_imm = 0;
3405     if (isInt32Immediate(N->getOperand(1), Srl_imm)) {
3406       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3407       // Note: The width operand is encoded as width-1.
3408       unsigned Width = 32 - Srl_imm - 1;
3409       int LSB = Srl_imm - Shl_imm;
3410       if (LSB < 0)
3411         return false;
3412       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3413       assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3414       SDValue Ops[] = { N->getOperand(0).getOperand(0),
3415                         CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3416                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
3417                         getAL(CurDAG, dl), Reg0 };
3418       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3419       return true;
3420     }
3421   }
3422 
3423   // Or we are looking for a shift of an and, with a mask operand
3424   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, And_imm) &&
3425       isShiftedMask_32(And_imm)) {
3426     unsigned Srl_imm = 0;
3427     unsigned LSB = countTrailingZeros(And_imm);
3428     // Shift must be the same as the ands lsb
3429     if (isInt32Immediate(N->getOperand(1), Srl_imm) && Srl_imm == LSB) {
3430       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3431       unsigned MSB = 31 - countLeadingZeros(And_imm);
3432       // Note: The width operand is encoded as width-1.
3433       unsigned Width = MSB - LSB;
3434       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3435       assert(Srl_imm + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3436       SDValue Ops[] = { N->getOperand(0).getOperand(0),
3437                         CurDAG->getTargetConstant(Srl_imm, dl, MVT::i32),
3438                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
3439                         getAL(CurDAG, dl), Reg0 };
3440       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3441       return true;
3442     }
3443   }
3444 
3445   if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3446     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
3447     unsigned LSB = 0;
3448     if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL, LSB) &&
3449         !isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRA, LSB))
3450       return false;
3451 
3452     if (LSB + Width > 32)
3453       return false;
3454 
3455     SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3456     assert(LSB + Width <= 32 && "Shouldn't create an invalid ubfx");
3457     SDValue Ops[] = { N->getOperand(0).getOperand(0),
3458                       CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3459                       CurDAG->getTargetConstant(Width - 1, dl, MVT::i32),
3460                       getAL(CurDAG, dl), Reg0 };
3461     CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3462     return true;
3463   }
3464 
3465   return false;
3466 }
3467 
3468 /// Target-specific DAG combining for ISD::XOR.
3469 /// Target-independent combining lowers SELECT_CC nodes of the form
3470 /// select_cc setg[ge] X,  0,  X, -X
3471 /// select_cc setgt    X, -1,  X, -X
3472 /// select_cc setl[te] X,  0, -X,  X
3473 /// select_cc setlt    X,  1, -X,  X
3474 /// which represent Integer ABS into:
3475 /// Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3476 /// ARM instruction selection detects the latter and matches it to
3477 /// ARM::ABS or ARM::t2ABS machine node.
3478 bool ARMDAGToDAGISel::tryABSOp(SDNode *N){
3479   SDValue XORSrc0 = N->getOperand(0);
3480   SDValue XORSrc1 = N->getOperand(1);
3481   EVT VT = N->getValueType(0);
3482 
3483   if (Subtarget->isThumb1Only())
3484     return false;
3485 
3486   if (XORSrc0.getOpcode() != ISD::ADD || XORSrc1.getOpcode() != ISD::SRA)
3487     return false;
3488 
3489   SDValue ADDSrc0 = XORSrc0.getOperand(0);
3490   SDValue ADDSrc1 = XORSrc0.getOperand(1);
3491   SDValue SRASrc0 = XORSrc1.getOperand(0);
3492   SDValue SRASrc1 = XORSrc1.getOperand(1);
3493   ConstantSDNode *SRAConstant =  dyn_cast<ConstantSDNode>(SRASrc1);
3494   EVT XType = SRASrc0.getValueType();
3495   unsigned Size = XType.getSizeInBits() - 1;
3496 
3497   if (ADDSrc1 == XORSrc1 && ADDSrc0 == SRASrc0 &&
3498       XType.isInteger() && SRAConstant != nullptr &&
3499       Size == SRAConstant->getZExtValue()) {
3500     unsigned Opcode = Subtarget->isThumb2() ? ARM::t2ABS : ARM::ABS;
3501     CurDAG->SelectNodeTo(N, Opcode, VT, ADDSrc0);
3502     return true;
3503   }
3504 
3505   return false;
3506 }
3507 
3508 /// We've got special pseudo-instructions for these
3509 void ARMDAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
3510   unsigned Opcode;
3511   EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
3512   if (MemTy == MVT::i8)
3513     Opcode = Subtarget->isThumb() ? ARM::tCMP_SWAP_8 : ARM::CMP_SWAP_8;
3514   else if (MemTy == MVT::i16)
3515     Opcode = Subtarget->isThumb() ? ARM::tCMP_SWAP_16 : ARM::CMP_SWAP_16;
3516   else if (MemTy == MVT::i32)
3517     Opcode = ARM::CMP_SWAP_32;
3518   else
3519     llvm_unreachable("Unknown AtomicCmpSwap type");
3520 
3521   SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
3522                    N->getOperand(0)};
3523   SDNode *CmpSwap = CurDAG->getMachineNode(
3524       Opcode, SDLoc(N),
3525       CurDAG->getVTList(MVT::i32, MVT::i32, MVT::Other), Ops);
3526 
3527   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
3528   CurDAG->setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
3529 
3530   ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
3531   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
3532   CurDAG->RemoveDeadNode(N);
3533 }
3534 
3535 static Optional<std::pair<unsigned, unsigned>>
3536 getContiguousRangeOfSetBits(const APInt &A) {
3537   unsigned FirstOne = A.getBitWidth() - A.countLeadingZeros() - 1;
3538   unsigned LastOne = A.countTrailingZeros();
3539   if (A.countPopulation() != (FirstOne - LastOne + 1))
3540     return Optional<std::pair<unsigned,unsigned>>();
3541   return std::make_pair(FirstOne, LastOne);
3542 }
3543 
3544 void ARMDAGToDAGISel::SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI) {
3545   assert(N->getOpcode() == ARMISD::CMPZ);
3546   SwitchEQNEToPLMI = false;
3547 
3548   if (!Subtarget->isThumb())
3549     // FIXME: Work out whether it is profitable to do this in A32 mode - LSL and
3550     // LSR don't exist as standalone instructions - they need the barrel shifter.
3551     return;
3552 
3553   // select (cmpz (and X, C), #0) -> (LSLS X) or (LSRS X) or (LSRS (LSLS X))
3554   SDValue And = N->getOperand(0);
3555   if (!And->hasOneUse())
3556     return;
3557 
3558   SDValue Zero = N->getOperand(1);
3559   if (!isa<ConstantSDNode>(Zero) || !cast<ConstantSDNode>(Zero)->isNullValue() ||
3560       And->getOpcode() != ISD::AND)
3561     return;
3562   SDValue X = And.getOperand(0);
3563   auto C = dyn_cast<ConstantSDNode>(And.getOperand(1));
3564 
3565   if (!C)
3566     return;
3567   auto Range = getContiguousRangeOfSetBits(C->getAPIntValue());
3568   if (!Range)
3569     return;
3570 
3571   // There are several ways to lower this:
3572   SDNode *NewN;
3573   SDLoc dl(N);
3574 
3575   auto EmitShift = [&](unsigned Opc, SDValue Src, unsigned Imm) -> SDNode* {
3576     if (Subtarget->isThumb2()) {
3577       Opc = (Opc == ARM::tLSLri) ? ARM::t2LSLri : ARM::t2LSRri;
3578       SDValue Ops[] = { Src, CurDAG->getTargetConstant(Imm, dl, MVT::i32),
3579                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
3580                         CurDAG->getRegister(0, MVT::i32) };
3581       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
3582     } else {
3583       SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), Src,
3584                        CurDAG->getTargetConstant(Imm, dl, MVT::i32),
3585                        getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
3586       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
3587     }
3588   };
3589 
3590   if (Range->second == 0) {
3591     //  1. Mask includes the LSB -> Simply shift the top N bits off
3592     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3593     ReplaceNode(And.getNode(), NewN);
3594   } else if (Range->first == 31) {
3595     //  2. Mask includes the MSB -> Simply shift the bottom N bits off
3596     NewN = EmitShift(ARM::tLSRri, X, Range->second);
3597     ReplaceNode(And.getNode(), NewN);
3598   } else if (Range->first == Range->second) {
3599     //  3. Only one bit is set. We can shift this into the sign bit and use a
3600     //     PL/MI comparison.
3601     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3602     ReplaceNode(And.getNode(), NewN);
3603 
3604     SwitchEQNEToPLMI = true;
3605   } else if (!Subtarget->hasV6T2Ops()) {
3606     //  4. Do a double shift to clear bottom and top bits, but only in
3607     //     thumb-1 mode as in thumb-2 we can use UBFX.
3608     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3609     NewN = EmitShift(ARM::tLSRri, SDValue(NewN, 0),
3610                      Range->second + (31 - Range->first));
3611     ReplaceNode(And.getNode(), NewN);
3612   }
3613 
3614 }
3615 
3616 void ARMDAGToDAGISel::Select(SDNode *N) {
3617   SDLoc dl(N);
3618 
3619   if (N->isMachineOpcode()) {
3620     N->setNodeId(-1);
3621     return;   // Already selected.
3622   }
3623 
3624   switch (N->getOpcode()) {
3625   default: break;
3626   case ISD::STORE: {
3627     // For Thumb1, match an sp-relative store in C++. This is a little
3628     // unfortunate, but I don't think I can make the chain check work
3629     // otherwise.  (The chain of the store has to be the same as the chain
3630     // of the CopyFromReg, or else we can't replace the CopyFromReg with
3631     // a direct reference to "SP".)
3632     //
3633     // This is only necessary on Thumb1 because Thumb1 sp-relative stores use
3634     // a different addressing mode from other four-byte stores.
3635     //
3636     // This pattern usually comes up with call arguments.
3637     StoreSDNode *ST = cast<StoreSDNode>(N);
3638     SDValue Ptr = ST->getBasePtr();
3639     if (Subtarget->isThumb1Only() && ST->isUnindexed()) {
3640       int RHSC = 0;
3641       if (Ptr.getOpcode() == ISD::ADD &&
3642           isScaledConstantInRange(Ptr.getOperand(1), /*Scale=*/4, 0, 256, RHSC))
3643         Ptr = Ptr.getOperand(0);
3644 
3645       if (Ptr.getOpcode() == ISD::CopyFromReg &&
3646           cast<RegisterSDNode>(Ptr.getOperand(1))->getReg() == ARM::SP &&
3647           Ptr.getOperand(0) == ST->getChain()) {
3648         SDValue Ops[] = {ST->getValue(),
3649                          CurDAG->getRegister(ARM::SP, MVT::i32),
3650                          CurDAG->getTargetConstant(RHSC, dl, MVT::i32),
3651                          getAL(CurDAG, dl),
3652                          CurDAG->getRegister(0, MVT::i32),
3653                          ST->getChain()};
3654         MachineSDNode *ResNode =
3655             CurDAG->getMachineNode(ARM::tSTRspi, dl, MVT::Other, Ops);
3656         MachineMemOperand *MemOp = ST->getMemOperand();
3657         CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
3658         ReplaceNode(N, ResNode);
3659         return;
3660       }
3661     }
3662     break;
3663   }
3664   case ISD::WRITE_REGISTER:
3665     if (tryWriteRegister(N))
3666       return;
3667     break;
3668   case ISD::READ_REGISTER:
3669     if (tryReadRegister(N))
3670       return;
3671     break;
3672   case ISD::INLINEASM:
3673   case ISD::INLINEASM_BR:
3674     if (tryInlineAsm(N))
3675       return;
3676     break;
3677   case ISD::XOR:
3678     // Select special operations if XOR node forms integer ABS pattern
3679     if (tryABSOp(N))
3680       return;
3681     // Other cases are autogenerated.
3682     break;
3683   case ISD::Constant: {
3684     unsigned Val = cast<ConstantSDNode>(N)->getZExtValue();
3685     // If we can't materialize the constant we need to use a literal pool
3686     if (ConstantMaterializationCost(Val, Subtarget) > 2) {
3687       SDValue CPIdx = CurDAG->getTargetConstantPool(
3688           ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
3689           TLI->getPointerTy(CurDAG->getDataLayout()));
3690 
3691       SDNode *ResNode;
3692       if (Subtarget->isThumb()) {
3693         SDValue Ops[] = {
3694           CPIdx,
3695           getAL(CurDAG, dl),
3696           CurDAG->getRegister(0, MVT::i32),
3697           CurDAG->getEntryNode()
3698         };
3699         ResNode = CurDAG->getMachineNode(ARM::tLDRpci, dl, MVT::i32, MVT::Other,
3700                                          Ops);
3701       } else {
3702         SDValue Ops[] = {
3703           CPIdx,
3704           CurDAG->getTargetConstant(0, dl, MVT::i32),
3705           getAL(CurDAG, dl),
3706           CurDAG->getRegister(0, MVT::i32),
3707           CurDAG->getEntryNode()
3708         };
3709         ResNode = CurDAG->getMachineNode(ARM::LDRcp, dl, MVT::i32, MVT::Other,
3710                                          Ops);
3711       }
3712       // Annotate the Node with memory operand information so that MachineInstr
3713       // queries work properly. This e.g. gives the register allocation the
3714       // required information for rematerialization.
3715       MachineFunction& MF = CurDAG->getMachineFunction();
3716       MachineMemOperand *MemOp =
3717           MF.getMachineMemOperand(MachinePointerInfo::getConstantPool(MF),
3718                                   MachineMemOperand::MOLoad, 4, Align(4));
3719 
3720       CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
3721 
3722       ReplaceNode(N, ResNode);
3723       return;
3724     }
3725 
3726     // Other cases are autogenerated.
3727     break;
3728   }
3729   case ISD::FrameIndex: {
3730     // Selects to ADDri FI, 0 which in turn will become ADDri SP, imm.
3731     int FI = cast<FrameIndexSDNode>(N)->getIndex();
3732     SDValue TFI = CurDAG->getTargetFrameIndex(
3733         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
3734     if (Subtarget->isThumb1Only()) {
3735       // Set the alignment of the frame object to 4, to avoid having to generate
3736       // more than one ADD
3737       MachineFrameInfo &MFI = MF->getFrameInfo();
3738       if (MFI.getObjectAlign(FI) < Align(4))
3739         MFI.setObjectAlignment(FI, Align(4));
3740       CurDAG->SelectNodeTo(N, ARM::tADDframe, MVT::i32, TFI,
3741                            CurDAG->getTargetConstant(0, dl, MVT::i32));
3742       return;
3743     } else {
3744       unsigned Opc = ((Subtarget->isThumb() && Subtarget->hasThumb2()) ?
3745                       ARM::t2ADDri : ARM::ADDri);
3746       SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, dl, MVT::i32),
3747                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
3748                         CurDAG->getRegister(0, MVT::i32) };
3749       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3750       return;
3751     }
3752   }
3753   case ISD::INSERT_VECTOR_ELT: {
3754     if (tryInsertVectorElt(N))
3755       return;
3756     break;
3757   }
3758   case ISD::SRL:
3759     if (tryV6T2BitfieldExtractOp(N, false))
3760       return;
3761     break;
3762   case ISD::SIGN_EXTEND_INREG:
3763   case ISD::SRA:
3764     if (tryV6T2BitfieldExtractOp(N, true))
3765       return;
3766     break;
3767   case ISD::FP_TO_UINT:
3768   case ISD::FP_TO_SINT:
3769     if (tryFP_TO_INT(N, dl))
3770       return;
3771     break;
3772   case ISD::FMUL:
3773     if (tryFMULFixed(N, dl))
3774       return;
3775     break;
3776   case ISD::MUL:
3777     if (Subtarget->isThumb1Only())
3778       break;
3779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
3780       unsigned RHSV = C->getZExtValue();
3781       if (!RHSV) break;
3782       if (isPowerOf2_32(RHSV-1)) {  // 2^n+1?
3783         unsigned ShImm = Log2_32(RHSV-1);
3784         if (ShImm >= 32)
3785           break;
3786         SDValue V = N->getOperand(0);
3787         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
3788         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
3789         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3790         if (Subtarget->isThumb()) {
3791           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
3792           CurDAG->SelectNodeTo(N, ARM::t2ADDrs, MVT::i32, Ops);
3793           return;
3794         } else {
3795           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
3796                             Reg0 };
3797           CurDAG->SelectNodeTo(N, ARM::ADDrsi, MVT::i32, Ops);
3798           return;
3799         }
3800       }
3801       if (isPowerOf2_32(RHSV+1)) {  // 2^n-1?
3802         unsigned ShImm = Log2_32(RHSV+1);
3803         if (ShImm >= 32)
3804           break;
3805         SDValue V = N->getOperand(0);
3806         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
3807         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
3808         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3809         if (Subtarget->isThumb()) {
3810           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
3811           CurDAG->SelectNodeTo(N, ARM::t2RSBrs, MVT::i32, Ops);
3812           return;
3813         } else {
3814           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
3815                             Reg0 };
3816           CurDAG->SelectNodeTo(N, ARM::RSBrsi, MVT::i32, Ops);
3817           return;
3818         }
3819       }
3820     }
3821     break;
3822   case ISD::AND: {
3823     // Check for unsigned bitfield extract
3824     if (tryV6T2BitfieldExtractOp(N, false))
3825       return;
3826 
3827     // If an immediate is used in an AND node, it is possible that the immediate
3828     // can be more optimally materialized when negated. If this is the case we
3829     // can negate the immediate and use a BIC instead.
3830     auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3831     if (N1C && N1C->hasOneUse() && Subtarget->isThumb()) {
3832       uint32_t Imm = (uint32_t) N1C->getZExtValue();
3833 
3834       // In Thumb2 mode, an AND can take a 12-bit immediate. If this
3835       // immediate can be negated and fit in the immediate operand of
3836       // a t2BIC, don't do any manual transform here as this can be
3837       // handled by the generic ISel machinery.
3838       bool PreferImmediateEncoding =
3839         Subtarget->hasThumb2() && (is_t2_so_imm(Imm) || is_t2_so_imm_not(Imm));
3840       if (!PreferImmediateEncoding &&
3841           ConstantMaterializationCost(Imm, Subtarget) >
3842               ConstantMaterializationCost(~Imm, Subtarget)) {
3843         // The current immediate costs more to materialize than a negated
3844         // immediate, so negate the immediate and use a BIC.
3845         SDValue NewImm =
3846           CurDAG->getConstant(~N1C->getZExtValue(), dl, MVT::i32);
3847         // If the new constant didn't exist before, reposition it in the topological
3848         // ordering so it is just before N. Otherwise, don't touch its location.
3849         if (NewImm->getNodeId() == -1)
3850           CurDAG->RepositionNode(N->getIterator(), NewImm.getNode());
3851 
3852         if (!Subtarget->hasThumb2()) {
3853           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32),
3854                            N->getOperand(0), NewImm, getAL(CurDAG, dl),
3855                            CurDAG->getRegister(0, MVT::i32)};
3856           ReplaceNode(N, CurDAG->getMachineNode(ARM::tBIC, dl, MVT::i32, Ops));
3857           return;
3858         } else {
3859           SDValue Ops[] = {N->getOperand(0), NewImm, getAL(CurDAG, dl),
3860                            CurDAG->getRegister(0, MVT::i32),
3861                            CurDAG->getRegister(0, MVT::i32)};
3862           ReplaceNode(N,
3863                       CurDAG->getMachineNode(ARM::t2BICrr, dl, MVT::i32, Ops));
3864           return;
3865         }
3866       }
3867     }
3868 
3869     // (and (or x, c2), c1) and top 16-bits of c1 and c2 match, lower 16-bits
3870     // of c1 are 0xffff, and lower 16-bit of c2 are 0. That is, the top 16-bits
3871     // are entirely contributed by c2 and lower 16-bits are entirely contributed
3872     // by x. That's equal to (or (and x, 0xffff), (and c1, 0xffff0000)).
3873     // Select it to: "movt x, ((c1 & 0xffff) >> 16)
3874     EVT VT = N->getValueType(0);
3875     if (VT != MVT::i32)
3876       break;
3877     unsigned Opc = (Subtarget->isThumb() && Subtarget->hasThumb2())
3878       ? ARM::t2MOVTi16
3879       : (Subtarget->hasV6T2Ops() ? ARM::MOVTi16 : 0);
3880     if (!Opc)
3881       break;
3882     SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3883     N1C = dyn_cast<ConstantSDNode>(N1);
3884     if (!N1C)
3885       break;
3886     if (N0.getOpcode() == ISD::OR && N0.getNode()->hasOneUse()) {
3887       SDValue N2 = N0.getOperand(1);
3888       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3889       if (!N2C)
3890         break;
3891       unsigned N1CVal = N1C->getZExtValue();
3892       unsigned N2CVal = N2C->getZExtValue();
3893       if ((N1CVal & 0xffff0000U) == (N2CVal & 0xffff0000U) &&
3894           (N1CVal & 0xffffU) == 0xffffU &&
3895           (N2CVal & 0xffffU) == 0x0U) {
3896         SDValue Imm16 = CurDAG->getTargetConstant((N2CVal & 0xFFFF0000U) >> 16,
3897                                                   dl, MVT::i32);
3898         SDValue Ops[] = { N0.getOperand(0), Imm16,
3899                           getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32) };
3900         ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
3901         return;
3902       }
3903     }
3904 
3905     break;
3906   }
3907   case ARMISD::UMAAL: {
3908     unsigned Opc = Subtarget->isThumb() ? ARM::t2UMAAL : ARM::UMAAL;
3909     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
3910                       N->getOperand(2), N->getOperand(3),
3911                       getAL(CurDAG, dl),
3912                       CurDAG->getRegister(0, MVT::i32) };
3913     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::i32, Ops));
3914     return;
3915   }
3916   case ARMISD::UMLAL:{
3917     if (Subtarget->isThumb()) {
3918       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3919                         N->getOperand(3), getAL(CurDAG, dl),
3920                         CurDAG->getRegister(0, MVT::i32)};
3921       ReplaceNode(
3922           N, CurDAG->getMachineNode(ARM::t2UMLAL, dl, MVT::i32, MVT::i32, Ops));
3923       return;
3924     }else{
3925       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3926                         N->getOperand(3), getAL(CurDAG, dl),
3927                         CurDAG->getRegister(0, MVT::i32),
3928                         CurDAG->getRegister(0, MVT::i32) };
3929       ReplaceNode(N, CurDAG->getMachineNode(
3930                          Subtarget->hasV6Ops() ? ARM::UMLAL : ARM::UMLALv5, dl,
3931                          MVT::i32, MVT::i32, Ops));
3932       return;
3933     }
3934   }
3935   case ARMISD::SMLAL:{
3936     if (Subtarget->isThumb()) {
3937       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3938                         N->getOperand(3), getAL(CurDAG, dl),
3939                         CurDAG->getRegister(0, MVT::i32)};
3940       ReplaceNode(
3941           N, CurDAG->getMachineNode(ARM::t2SMLAL, dl, MVT::i32, MVT::i32, Ops));
3942       return;
3943     }else{
3944       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3945                         N->getOperand(3), getAL(CurDAG, dl),
3946                         CurDAG->getRegister(0, MVT::i32),
3947                         CurDAG->getRegister(0, MVT::i32) };
3948       ReplaceNode(N, CurDAG->getMachineNode(
3949                          Subtarget->hasV6Ops() ? ARM::SMLAL : ARM::SMLALv5, dl,
3950                          MVT::i32, MVT::i32, Ops));
3951       return;
3952     }
3953   }
3954   case ARMISD::SUBE: {
3955     if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
3956       break;
3957     // Look for a pattern to match SMMLS
3958     // (sube a, (smul_loHi a, b), (subc 0, (smul_LOhi(a, b))))
3959     if (N->getOperand(1).getOpcode() != ISD::SMUL_LOHI ||
3960         N->getOperand(2).getOpcode() != ARMISD::SUBC ||
3961         !SDValue(N, 1).use_empty())
3962       break;
3963 
3964     if (Subtarget->isThumb())
3965       assert(Subtarget->hasThumb2() &&
3966              "This pattern should not be generated for Thumb");
3967 
3968     SDValue SmulLoHi = N->getOperand(1);
3969     SDValue Subc = N->getOperand(2);
3970     auto *Zero = dyn_cast<ConstantSDNode>(Subc.getOperand(0));
3971 
3972     if (!Zero || Zero->getZExtValue() != 0 ||
3973         Subc.getOperand(1) != SmulLoHi.getValue(0) ||
3974         N->getOperand(1) != SmulLoHi.getValue(1) ||
3975         N->getOperand(2) != Subc.getValue(1))
3976       break;
3977 
3978     unsigned Opc = Subtarget->isThumb2() ? ARM::t2SMMLS : ARM::SMMLS;
3979     SDValue Ops[] = { SmulLoHi.getOperand(0), SmulLoHi.getOperand(1),
3980                       N->getOperand(0), getAL(CurDAG, dl),
3981                       CurDAG->getRegister(0, MVT::i32) };
3982     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops));
3983     return;
3984   }
3985   case ISD::LOAD: {
3986     if (Subtarget->hasMVEIntegerOps() && tryMVEIndexedLoad(N))
3987       return;
3988     if (Subtarget->isThumb() && Subtarget->hasThumb2()) {
3989       if (tryT2IndexedLoad(N))
3990         return;
3991     } else if (Subtarget->isThumb()) {
3992       if (tryT1IndexedLoad(N))
3993         return;
3994     } else if (tryARMIndexedLoad(N))
3995       return;
3996     // Other cases are autogenerated.
3997     break;
3998   }
3999   case ISD::MLOAD:
4000     if (Subtarget->hasMVEIntegerOps() && tryMVEIndexedLoad(N))
4001       return;
4002     // Other cases are autogenerated.
4003     break;
4004   case ARMISD::WLSSETUP: {
4005     SDNode *New = CurDAG->getMachineNode(ARM::t2WhileLoopSetup, dl, MVT::i32,
4006                                          N->getOperand(0));
4007     ReplaceUses(N, New);
4008     CurDAG->RemoveDeadNode(N);
4009     return;
4010   }
4011   case ARMISD::WLS: {
4012     SDNode *New = CurDAG->getMachineNode(ARM::t2WhileLoopStart, dl, MVT::Other,
4013                                          N->getOperand(1), N->getOperand(2),
4014                                          N->getOperand(0));
4015     ReplaceUses(N, New);
4016     CurDAG->RemoveDeadNode(N);
4017     return;
4018   }
4019   case ARMISD::LE: {
4020     SDValue Ops[] = { N->getOperand(1),
4021                       N->getOperand(2),
4022                       N->getOperand(0) };
4023     unsigned Opc = ARM::t2LoopEnd;
4024     SDNode *New = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
4025     ReplaceUses(N, New);
4026     CurDAG->RemoveDeadNode(N);
4027     return;
4028   }
4029   case ARMISD::LDRD: {
4030     if (Subtarget->isThumb2())
4031       break; // TableGen handles isel in this case.
4032     SDValue Base, RegOffset, ImmOffset;
4033     const SDValue &Chain = N->getOperand(0);
4034     const SDValue &Addr = N->getOperand(1);
4035     SelectAddrMode3(Addr, Base, RegOffset, ImmOffset);
4036     if (RegOffset != CurDAG->getRegister(0, MVT::i32)) {
4037       // The register-offset variant of LDRD mandates that the register
4038       // allocated to RegOffset is not reused in any of the remaining operands.
4039       // This restriction is currently not enforced. Therefore emitting this
4040       // variant is explicitly avoided.
4041       Base = Addr;
4042       RegOffset = CurDAG->getRegister(0, MVT::i32);
4043     }
4044     SDValue Ops[] = {Base, RegOffset, ImmOffset, Chain};
4045     SDNode *New = CurDAG->getMachineNode(ARM::LOADDUAL, dl,
4046                                          {MVT::Untyped, MVT::Other}, Ops);
4047     SDValue Lo = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
4048                                                 SDValue(New, 0));
4049     SDValue Hi = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
4050                                                 SDValue(New, 0));
4051     transferMemOperands(N, New);
4052     ReplaceUses(SDValue(N, 0), Lo);
4053     ReplaceUses(SDValue(N, 1), Hi);
4054     ReplaceUses(SDValue(N, 2), SDValue(New, 1));
4055     CurDAG->RemoveDeadNode(N);
4056     return;
4057   }
4058   case ARMISD::STRD: {
4059     if (Subtarget->isThumb2())
4060       break; // TableGen handles isel in this case.
4061     SDValue Base, RegOffset, ImmOffset;
4062     const SDValue &Chain = N->getOperand(0);
4063     const SDValue &Addr = N->getOperand(3);
4064     SelectAddrMode3(Addr, Base, RegOffset, ImmOffset);
4065     if (RegOffset != CurDAG->getRegister(0, MVT::i32)) {
4066       // The register-offset variant of STRD mandates that the register
4067       // allocated to RegOffset is not reused in any of the remaining operands.
4068       // This restriction is currently not enforced. Therefore emitting this
4069       // variant is explicitly avoided.
4070       Base = Addr;
4071       RegOffset = CurDAG->getRegister(0, MVT::i32);
4072     }
4073     SDNode *RegPair =
4074         createGPRPairNode(MVT::Untyped, N->getOperand(1), N->getOperand(2));
4075     SDValue Ops[] = {SDValue(RegPair, 0), Base, RegOffset, ImmOffset, Chain};
4076     SDNode *New = CurDAG->getMachineNode(ARM::STOREDUAL, dl, MVT::Other, Ops);
4077     transferMemOperands(N, New);
4078     ReplaceUses(SDValue(N, 0), SDValue(New, 0));
4079     CurDAG->RemoveDeadNode(N);
4080     return;
4081   }
4082   case ARMISD::LOOP_DEC: {
4083     SDValue Ops[] = { N->getOperand(1),
4084                       N->getOperand(2),
4085                       N->getOperand(0) };
4086     SDNode *Dec =
4087       CurDAG->getMachineNode(ARM::t2LoopDec, dl,
4088                              CurDAG->getVTList(MVT::i32, MVT::Other), Ops);
4089     ReplaceUses(N, Dec);
4090     CurDAG->RemoveDeadNode(N);
4091     return;
4092   }
4093   case ARMISD::BRCOND: {
4094     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4095     // Emits: (Bcc:void (bb:Other):$dst, (imm:i32):$cc)
4096     // Pattern complexity = 6  cost = 1  size = 0
4097 
4098     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4099     // Emits: (tBcc:void (bb:Other):$dst, (imm:i32):$cc)
4100     // Pattern complexity = 6  cost = 1  size = 0
4101 
4102     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4103     // Emits: (t2Bcc:void (bb:Other):$dst, (imm:i32):$cc)
4104     // Pattern complexity = 6  cost = 1  size = 0
4105 
4106     unsigned Opc = Subtarget->isThumb() ?
4107       ((Subtarget->hasThumb2()) ? ARM::t2Bcc : ARM::tBcc) : ARM::Bcc;
4108     SDValue Chain = N->getOperand(0);
4109     SDValue N1 = N->getOperand(1);
4110     SDValue N2 = N->getOperand(2);
4111     SDValue N3 = N->getOperand(3);
4112     SDValue InFlag = N->getOperand(4);
4113     assert(N1.getOpcode() == ISD::BasicBlock);
4114     assert(N2.getOpcode() == ISD::Constant);
4115     assert(N3.getOpcode() == ISD::Register);
4116 
4117     unsigned CC = (unsigned) cast<ConstantSDNode>(N2)->getZExtValue();
4118 
4119     if (InFlag.getOpcode() == ARMISD::CMPZ) {
4120       if (InFlag.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4121         SDValue Int = InFlag.getOperand(0);
4122         uint64_t ID = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
4123 
4124         // Handle low-overhead loops.
4125         if (ID == Intrinsic::loop_decrement_reg) {
4126           SDValue Elements = Int.getOperand(2);
4127           SDValue Size = CurDAG->getTargetConstant(
4128             cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl,
4129                                  MVT::i32);
4130 
4131           SDValue Args[] = { Elements, Size, Int.getOperand(0) };
4132           SDNode *LoopDec =
4133             CurDAG->getMachineNode(ARM::t2LoopDec, dl,
4134                                    CurDAG->getVTList(MVT::i32, MVT::Other),
4135                                    Args);
4136           ReplaceUses(Int.getNode(), LoopDec);
4137 
4138           SDValue EndArgs[] = { SDValue(LoopDec, 0), N1, Chain };
4139           SDNode *LoopEnd =
4140             CurDAG->getMachineNode(ARM::t2LoopEnd, dl, MVT::Other, EndArgs);
4141 
4142           ReplaceUses(N, LoopEnd);
4143           CurDAG->RemoveDeadNode(N);
4144           CurDAG->RemoveDeadNode(InFlag.getNode());
4145           CurDAG->RemoveDeadNode(Int.getNode());
4146           return;
4147         }
4148       }
4149 
4150       bool SwitchEQNEToPLMI;
4151       SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
4152       InFlag = N->getOperand(4);
4153 
4154       if (SwitchEQNEToPLMI) {
4155         switch ((ARMCC::CondCodes)CC) {
4156         default: llvm_unreachable("CMPZ must be either NE or EQ!");
4157         case ARMCC::NE:
4158           CC = (unsigned)ARMCC::MI;
4159           break;
4160         case ARMCC::EQ:
4161           CC = (unsigned)ARMCC::PL;
4162           break;
4163         }
4164       }
4165     }
4166 
4167     SDValue Tmp2 = CurDAG->getTargetConstant(CC, dl, MVT::i32);
4168     SDValue Ops[] = { N1, Tmp2, N3, Chain, InFlag };
4169     SDNode *ResNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
4170                                              MVT::Glue, Ops);
4171     Chain = SDValue(ResNode, 0);
4172     if (N->getNumValues() == 2) {
4173       InFlag = SDValue(ResNode, 1);
4174       ReplaceUses(SDValue(N, 1), InFlag);
4175     }
4176     ReplaceUses(SDValue(N, 0),
4177                 SDValue(Chain.getNode(), Chain.getResNo()));
4178     CurDAG->RemoveDeadNode(N);
4179     return;
4180   }
4181 
4182   case ARMISD::CMPZ: {
4183     // select (CMPZ X, #-C) -> (CMPZ (ADDS X, #C), #0)
4184     //   This allows us to avoid materializing the expensive negative constant.
4185     //   The CMPZ #0 is useless and will be peepholed away but we need to keep it
4186     //   for its glue output.
4187     SDValue X = N->getOperand(0);
4188     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1).getNode());
4189     if (C && C->getSExtValue() < 0 && Subtarget->isThumb()) {
4190       int64_t Addend = -C->getSExtValue();
4191 
4192       SDNode *Add = nullptr;
4193       // ADDS can be better than CMN if the immediate fits in a
4194       // 16-bit ADDS, which means either [0,256) for tADDi8 or [0,8) for tADDi3.
4195       // Outside that range we can just use a CMN which is 32-bit but has a
4196       // 12-bit immediate range.
4197       if (Addend < 1<<8) {
4198         if (Subtarget->isThumb2()) {
4199           SDValue Ops[] = { X, CurDAG->getTargetConstant(Addend, dl, MVT::i32),
4200                             getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
4201                             CurDAG->getRegister(0, MVT::i32) };
4202           Add = CurDAG->getMachineNode(ARM::t2ADDri, dl, MVT::i32, Ops);
4203         } else {
4204           unsigned Opc = (Addend < 1<<3) ? ARM::tADDi3 : ARM::tADDi8;
4205           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), X,
4206                            CurDAG->getTargetConstant(Addend, dl, MVT::i32),
4207                            getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
4208           Add = CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
4209         }
4210       }
4211       if (Add) {
4212         SDValue Ops2[] = {SDValue(Add, 0), CurDAG->getConstant(0, dl, MVT::i32)};
4213         CurDAG->MorphNodeTo(N, ARMISD::CMPZ, CurDAG->getVTList(MVT::Glue), Ops2);
4214       }
4215     }
4216     // Other cases are autogenerated.
4217     break;
4218   }
4219 
4220   case ARMISD::CMOV: {
4221     SDValue InFlag = N->getOperand(4);
4222 
4223     if (InFlag.getOpcode() == ARMISD::CMPZ) {
4224       bool SwitchEQNEToPLMI;
4225       SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
4226 
4227       if (SwitchEQNEToPLMI) {
4228         SDValue ARMcc = N->getOperand(2);
4229         ARMCC::CondCodes CC =
4230           (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
4231 
4232         switch (CC) {
4233         default: llvm_unreachable("CMPZ must be either NE or EQ!");
4234         case ARMCC::NE:
4235           CC = ARMCC::MI;
4236           break;
4237         case ARMCC::EQ:
4238           CC = ARMCC::PL;
4239           break;
4240         }
4241         SDValue NewARMcc = CurDAG->getConstant((unsigned)CC, dl, MVT::i32);
4242         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), NewARMcc,
4243                          N->getOperand(3), N->getOperand(4)};
4244         CurDAG->MorphNodeTo(N, ARMISD::CMOV, N->getVTList(), Ops);
4245       }
4246 
4247     }
4248     // Other cases are autogenerated.
4249     break;
4250   }
4251 
4252   case ARMISD::VZIP: {
4253     unsigned Opc = 0;
4254     EVT VT = N->getValueType(0);
4255     switch (VT.getSimpleVT().SimpleTy) {
4256     default: return;
4257     case MVT::v8i8:  Opc = ARM::VZIPd8; break;
4258     case MVT::v4f16:
4259     case MVT::v4i16: Opc = ARM::VZIPd16; break;
4260     case MVT::v2f32:
4261     // vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
4262     case MVT::v2i32: Opc = ARM::VTRNd32; break;
4263     case MVT::v16i8: Opc = ARM::VZIPq8; break;
4264     case MVT::v8f16:
4265     case MVT::v8i16: Opc = ARM::VZIPq16; break;
4266     case MVT::v4f32:
4267     case MVT::v4i32: Opc = ARM::VZIPq32; break;
4268     }
4269     SDValue Pred = getAL(CurDAG, dl);
4270     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4271     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
4272     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4273     return;
4274   }
4275   case ARMISD::VUZP: {
4276     unsigned Opc = 0;
4277     EVT VT = N->getValueType(0);
4278     switch (VT.getSimpleVT().SimpleTy) {
4279     default: return;
4280     case MVT::v8i8:  Opc = ARM::VUZPd8; break;
4281     case MVT::v4f16:
4282     case MVT::v4i16: Opc = ARM::VUZPd16; break;
4283     case MVT::v2f32:
4284     // vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
4285     case MVT::v2i32: Opc = ARM::VTRNd32; break;
4286     case MVT::v16i8: Opc = ARM::VUZPq8; break;
4287     case MVT::v8f16:
4288     case MVT::v8i16: Opc = ARM::VUZPq16; break;
4289     case MVT::v4f32:
4290     case MVT::v4i32: Opc = ARM::VUZPq32; break;
4291     }
4292     SDValue Pred = getAL(CurDAG, dl);
4293     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4294     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
4295     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4296     return;
4297   }
4298   case ARMISD::VTRN: {
4299     unsigned Opc = 0;
4300     EVT VT = N->getValueType(0);
4301     switch (VT.getSimpleVT().SimpleTy) {
4302     default: return;
4303     case MVT::v8i8:  Opc = ARM::VTRNd8; break;
4304     case MVT::v4f16:
4305     case MVT::v4i16: Opc = ARM::VTRNd16; break;
4306     case MVT::v2f32:
4307     case MVT::v2i32: Opc = ARM::VTRNd32; break;
4308     case MVT::v16i8: Opc = ARM::VTRNq8; break;
4309     case MVT::v8f16:
4310     case MVT::v8i16: Opc = ARM::VTRNq16; break;
4311     case MVT::v4f32:
4312     case MVT::v4i32: Opc = ARM::VTRNq32; break;
4313     }
4314     SDValue Pred = getAL(CurDAG, dl);
4315     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4316     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
4317     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4318     return;
4319   }
4320   case ARMISD::BUILD_VECTOR: {
4321     EVT VecVT = N->getValueType(0);
4322     EVT EltVT = VecVT.getVectorElementType();
4323     unsigned NumElts = VecVT.getVectorNumElements();
4324     if (EltVT == MVT::f64) {
4325       assert(NumElts == 2 && "unexpected type for BUILD_VECTOR");
4326       ReplaceNode(
4327           N, createDRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
4328       return;
4329     }
4330     assert(EltVT == MVT::f32 && "unexpected type for BUILD_VECTOR");
4331     if (NumElts == 2) {
4332       ReplaceNode(
4333           N, createSRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
4334       return;
4335     }
4336     assert(NumElts == 4 && "unexpected type for BUILD_VECTOR");
4337     ReplaceNode(N,
4338                 createQuadSRegsNode(VecVT, N->getOperand(0), N->getOperand(1),
4339                                     N->getOperand(2), N->getOperand(3)));
4340     return;
4341   }
4342 
4343   case ARMISD::VLD1DUP: {
4344     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8, ARM::VLD1DUPd16,
4345                                          ARM::VLD1DUPd32 };
4346     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8, ARM::VLD1DUPq16,
4347                                          ARM::VLD1DUPq32 };
4348     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 1, DOpcodes, QOpcodes);
4349     return;
4350   }
4351 
4352   case ARMISD::VLD2DUP: {
4353     static const uint16_t Opcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
4354                                         ARM::VLD2DUPd32 };
4355     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 2, Opcodes);
4356     return;
4357   }
4358 
4359   case ARMISD::VLD3DUP: {
4360     static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo,
4361                                         ARM::VLD3DUPd16Pseudo,
4362                                         ARM::VLD3DUPd32Pseudo };
4363     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 3, Opcodes);
4364     return;
4365   }
4366 
4367   case ARMISD::VLD4DUP: {
4368     static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo,
4369                                         ARM::VLD4DUPd16Pseudo,
4370                                         ARM::VLD4DUPd32Pseudo };
4371     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 4, Opcodes);
4372     return;
4373   }
4374 
4375   case ARMISD::VLD1DUP_UPD: {
4376     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8wb_fixed,
4377                                          ARM::VLD1DUPd16wb_fixed,
4378                                          ARM::VLD1DUPd32wb_fixed };
4379     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8wb_fixed,
4380                                          ARM::VLD1DUPq16wb_fixed,
4381                                          ARM::VLD1DUPq32wb_fixed };
4382     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 1, DOpcodes, QOpcodes);
4383     return;
4384   }
4385 
4386   case ARMISD::VLD2DUP_UPD: {
4387     static const uint16_t DOpcodes[] = { ARM::VLD2DUPd8wb_fixed,
4388                                          ARM::VLD2DUPd16wb_fixed,
4389                                          ARM::VLD2DUPd32wb_fixed,
4390                                          ARM::VLD1q64wb_fixed };
4391     static const uint16_t QOpcodes0[] = { ARM::VLD2DUPq8EvenPseudo,
4392                                           ARM::VLD2DUPq16EvenPseudo,
4393                                           ARM::VLD2DUPq32EvenPseudo };
4394     static const uint16_t QOpcodes1[] = { ARM::VLD2DUPq8OddPseudoWB_fixed,
4395                                           ARM::VLD2DUPq16OddPseudoWB_fixed,
4396                                           ARM::VLD2DUPq32OddPseudoWB_fixed };
4397     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 2, DOpcodes, QOpcodes0, QOpcodes1);
4398     return;
4399   }
4400 
4401   case ARMISD::VLD3DUP_UPD: {
4402     static const uint16_t DOpcodes[] = { ARM::VLD3DUPd8Pseudo_UPD,
4403                                          ARM::VLD3DUPd16Pseudo_UPD,
4404                                          ARM::VLD3DUPd32Pseudo_UPD,
4405                                          ARM::VLD1d64TPseudoWB_fixed };
4406     static const uint16_t QOpcodes0[] = { ARM::VLD3DUPq8EvenPseudo,
4407                                           ARM::VLD3DUPq16EvenPseudo,
4408                                           ARM::VLD3DUPq32EvenPseudo };
4409     static const uint16_t QOpcodes1[] = { ARM::VLD3DUPq8OddPseudo_UPD,
4410                                           ARM::VLD3DUPq16OddPseudo_UPD,
4411                                           ARM::VLD3DUPq32OddPseudo_UPD };
4412     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4413     return;
4414   }
4415 
4416   case ARMISD::VLD4DUP_UPD: {
4417     static const uint16_t DOpcodes[] = { ARM::VLD4DUPd8Pseudo_UPD,
4418                                          ARM::VLD4DUPd16Pseudo_UPD,
4419                                          ARM::VLD4DUPd32Pseudo_UPD,
4420                                          ARM::VLD1d64QPseudoWB_fixed };
4421     static const uint16_t QOpcodes0[] = { ARM::VLD4DUPq8EvenPseudo,
4422                                           ARM::VLD4DUPq16EvenPseudo,
4423                                           ARM::VLD4DUPq32EvenPseudo };
4424     static const uint16_t QOpcodes1[] = { ARM::VLD4DUPq8OddPseudo_UPD,
4425                                           ARM::VLD4DUPq16OddPseudo_UPD,
4426                                           ARM::VLD4DUPq32OddPseudo_UPD };
4427     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4428     return;
4429   }
4430 
4431   case ARMISD::VLD1_UPD: {
4432     static const uint16_t DOpcodes[] = { ARM::VLD1d8wb_fixed,
4433                                          ARM::VLD1d16wb_fixed,
4434                                          ARM::VLD1d32wb_fixed,
4435                                          ARM::VLD1d64wb_fixed };
4436     static const uint16_t QOpcodes[] = { ARM::VLD1q8wb_fixed,
4437                                          ARM::VLD1q16wb_fixed,
4438                                          ARM::VLD1q32wb_fixed,
4439                                          ARM::VLD1q64wb_fixed };
4440     SelectVLD(N, true, 1, DOpcodes, QOpcodes, nullptr);
4441     return;
4442   }
4443 
4444   case ARMISD::VLD2_UPD: {
4445     if (Subtarget->hasNEON()) {
4446       static const uint16_t DOpcodes[] = {
4447           ARM::VLD2d8wb_fixed, ARM::VLD2d16wb_fixed, ARM::VLD2d32wb_fixed,
4448           ARM::VLD1q64wb_fixed};
4449       static const uint16_t QOpcodes[] = {ARM::VLD2q8PseudoWB_fixed,
4450                                           ARM::VLD2q16PseudoWB_fixed,
4451                                           ARM::VLD2q32PseudoWB_fixed};
4452       SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
4453     } else {
4454       static const uint16_t Opcodes8[] = {ARM::MVE_VLD20_8,
4455                                           ARM::MVE_VLD21_8_wb};
4456       static const uint16_t Opcodes16[] = {ARM::MVE_VLD20_16,
4457                                            ARM::MVE_VLD21_16_wb};
4458       static const uint16_t Opcodes32[] = {ARM::MVE_VLD20_32,
4459                                            ARM::MVE_VLD21_32_wb};
4460       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
4461       SelectMVE_VLD(N, 2, Opcodes, true);
4462     }
4463     return;
4464   }
4465 
4466   case ARMISD::VLD3_UPD: {
4467     static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo_UPD,
4468                                          ARM::VLD3d16Pseudo_UPD,
4469                                          ARM::VLD3d32Pseudo_UPD,
4470                                          ARM::VLD1d64TPseudoWB_fixed};
4471     static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
4472                                           ARM::VLD3q16Pseudo_UPD,
4473                                           ARM::VLD3q32Pseudo_UPD };
4474     static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo_UPD,
4475                                           ARM::VLD3q16oddPseudo_UPD,
4476                                           ARM::VLD3q32oddPseudo_UPD };
4477     SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4478     return;
4479   }
4480 
4481   case ARMISD::VLD4_UPD: {
4482     if (Subtarget->hasNEON()) {
4483       static const uint16_t DOpcodes[] = {
4484           ARM::VLD4d8Pseudo_UPD, ARM::VLD4d16Pseudo_UPD, ARM::VLD4d32Pseudo_UPD,
4485           ARM::VLD1d64QPseudoWB_fixed};
4486       static const uint16_t QOpcodes0[] = {ARM::VLD4q8Pseudo_UPD,
4487                                            ARM::VLD4q16Pseudo_UPD,
4488                                            ARM::VLD4q32Pseudo_UPD};
4489       static const uint16_t QOpcodes1[] = {ARM::VLD4q8oddPseudo_UPD,
4490                                            ARM::VLD4q16oddPseudo_UPD,
4491                                            ARM::VLD4q32oddPseudo_UPD};
4492       SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4493     } else {
4494       static const uint16_t Opcodes8[] = {ARM::MVE_VLD40_8, ARM::MVE_VLD41_8,
4495                                           ARM::MVE_VLD42_8,
4496                                           ARM::MVE_VLD43_8_wb};
4497       static const uint16_t Opcodes16[] = {ARM::MVE_VLD40_16, ARM::MVE_VLD41_16,
4498                                            ARM::MVE_VLD42_16,
4499                                            ARM::MVE_VLD43_16_wb};
4500       static const uint16_t Opcodes32[] = {ARM::MVE_VLD40_32, ARM::MVE_VLD41_32,
4501                                            ARM::MVE_VLD42_32,
4502                                            ARM::MVE_VLD43_32_wb};
4503       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
4504       SelectMVE_VLD(N, 4, Opcodes, true);
4505     }
4506     return;
4507   }
4508 
4509   case ARMISD::VLD1x2_UPD: {
4510     if (Subtarget->hasNEON()) {
4511       static const uint16_t DOpcodes[] = {
4512           ARM::VLD1q8wb_fixed, ARM::VLD1q16wb_fixed, ARM::VLD1q32wb_fixed,
4513           ARM::VLD1q64wb_fixed};
4514       static const uint16_t QOpcodes[] = {
4515           ARM::VLD1d8QPseudoWB_fixed, ARM::VLD1d16QPseudoWB_fixed,
4516           ARM::VLD1d32QPseudoWB_fixed, ARM::VLD1d64QPseudoWB_fixed};
4517       SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
4518       return;
4519     }
4520     break;
4521   }
4522 
4523   case ARMISD::VLD1x3_UPD: {
4524     if (Subtarget->hasNEON()) {
4525       static const uint16_t DOpcodes[] = {
4526           ARM::VLD1d8TPseudoWB_fixed, ARM::VLD1d16TPseudoWB_fixed,
4527           ARM::VLD1d32TPseudoWB_fixed, ARM::VLD1d64TPseudoWB_fixed};
4528       static const uint16_t QOpcodes0[] = {
4529           ARM::VLD1q8LowTPseudo_UPD, ARM::VLD1q16LowTPseudo_UPD,
4530           ARM::VLD1q32LowTPseudo_UPD, ARM::VLD1q64LowTPseudo_UPD};
4531       static const uint16_t QOpcodes1[] = {
4532           ARM::VLD1q8HighTPseudo_UPD, ARM::VLD1q16HighTPseudo_UPD,
4533           ARM::VLD1q32HighTPseudo_UPD, ARM::VLD1q64HighTPseudo_UPD};
4534       SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4535       return;
4536     }
4537     break;
4538   }
4539 
4540   case ARMISD::VLD1x4_UPD: {
4541     if (Subtarget->hasNEON()) {
4542       static const uint16_t DOpcodes[] = {
4543           ARM::VLD1d8QPseudoWB_fixed, ARM::VLD1d16QPseudoWB_fixed,
4544           ARM::VLD1d32QPseudoWB_fixed, ARM::VLD1d64QPseudoWB_fixed};
4545       static const uint16_t QOpcodes0[] = {
4546           ARM::VLD1q8LowQPseudo_UPD, ARM::VLD1q16LowQPseudo_UPD,
4547           ARM::VLD1q32LowQPseudo_UPD, ARM::VLD1q64LowQPseudo_UPD};
4548       static const uint16_t QOpcodes1[] = {
4549           ARM::VLD1q8HighQPseudo_UPD, ARM::VLD1q16HighQPseudo_UPD,
4550           ARM::VLD1q32HighQPseudo_UPD, ARM::VLD1q64HighQPseudo_UPD};
4551       SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4552       return;
4553     }
4554     break;
4555   }
4556 
4557   case ARMISD::VLD2LN_UPD: {
4558     static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo_UPD,
4559                                          ARM::VLD2LNd16Pseudo_UPD,
4560                                          ARM::VLD2LNd32Pseudo_UPD };
4561     static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo_UPD,
4562                                          ARM::VLD2LNq32Pseudo_UPD };
4563     SelectVLDSTLane(N, true, true, 2, DOpcodes, QOpcodes);
4564     return;
4565   }
4566 
4567   case ARMISD::VLD3LN_UPD: {
4568     static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo_UPD,
4569                                          ARM::VLD3LNd16Pseudo_UPD,
4570                                          ARM::VLD3LNd32Pseudo_UPD };
4571     static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo_UPD,
4572                                          ARM::VLD3LNq32Pseudo_UPD };
4573     SelectVLDSTLane(N, true, true, 3, DOpcodes, QOpcodes);
4574     return;
4575   }
4576 
4577   case ARMISD::VLD4LN_UPD: {
4578     static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo_UPD,
4579                                          ARM::VLD4LNd16Pseudo_UPD,
4580                                          ARM::VLD4LNd32Pseudo_UPD };
4581     static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo_UPD,
4582                                          ARM::VLD4LNq32Pseudo_UPD };
4583     SelectVLDSTLane(N, true, true, 4, DOpcodes, QOpcodes);
4584     return;
4585   }
4586 
4587   case ARMISD::VST1_UPD: {
4588     static const uint16_t DOpcodes[] = { ARM::VST1d8wb_fixed,
4589                                          ARM::VST1d16wb_fixed,
4590                                          ARM::VST1d32wb_fixed,
4591                                          ARM::VST1d64wb_fixed };
4592     static const uint16_t QOpcodes[] = { ARM::VST1q8wb_fixed,
4593                                          ARM::VST1q16wb_fixed,
4594                                          ARM::VST1q32wb_fixed,
4595                                          ARM::VST1q64wb_fixed };
4596     SelectVST(N, true, 1, DOpcodes, QOpcodes, nullptr);
4597     return;
4598   }
4599 
4600   case ARMISD::VST2_UPD: {
4601     if (Subtarget->hasNEON()) {
4602       static const uint16_t DOpcodes[] = {
4603           ARM::VST2d8wb_fixed, ARM::VST2d16wb_fixed, ARM::VST2d32wb_fixed,
4604           ARM::VST1q64wb_fixed};
4605       static const uint16_t QOpcodes[] = {ARM::VST2q8PseudoWB_fixed,
4606                                           ARM::VST2q16PseudoWB_fixed,
4607                                           ARM::VST2q32PseudoWB_fixed};
4608       SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
4609       return;
4610     }
4611     break;
4612   }
4613 
4614   case ARMISD::VST3_UPD: {
4615     static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo_UPD,
4616                                          ARM::VST3d16Pseudo_UPD,
4617                                          ARM::VST3d32Pseudo_UPD,
4618                                          ARM::VST1d64TPseudoWB_fixed};
4619     static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
4620                                           ARM::VST3q16Pseudo_UPD,
4621                                           ARM::VST3q32Pseudo_UPD };
4622     static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo_UPD,
4623                                           ARM::VST3q16oddPseudo_UPD,
4624                                           ARM::VST3q32oddPseudo_UPD };
4625     SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4626     return;
4627   }
4628 
4629   case ARMISD::VST4_UPD: {
4630     if (Subtarget->hasNEON()) {
4631       static const uint16_t DOpcodes[] = {
4632           ARM::VST4d8Pseudo_UPD, ARM::VST4d16Pseudo_UPD, ARM::VST4d32Pseudo_UPD,
4633           ARM::VST1d64QPseudoWB_fixed};
4634       static const uint16_t QOpcodes0[] = {ARM::VST4q8Pseudo_UPD,
4635                                            ARM::VST4q16Pseudo_UPD,
4636                                            ARM::VST4q32Pseudo_UPD};
4637       static const uint16_t QOpcodes1[] = {ARM::VST4q8oddPseudo_UPD,
4638                                            ARM::VST4q16oddPseudo_UPD,
4639                                            ARM::VST4q32oddPseudo_UPD};
4640       SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4641       return;
4642     }
4643     break;
4644   }
4645 
4646   case ARMISD::VST1x2_UPD: {
4647     if (Subtarget->hasNEON()) {
4648       static const uint16_t DOpcodes[] = { ARM::VST1q8wb_fixed,
4649                                            ARM::VST1q16wb_fixed,
4650                                            ARM::VST1q32wb_fixed,
4651                                            ARM::VST1q64wb_fixed};
4652       static const uint16_t QOpcodes[] = { ARM::VST1d8QPseudoWB_fixed,
4653                                            ARM::VST1d16QPseudoWB_fixed,
4654                                            ARM::VST1d32QPseudoWB_fixed,
4655                                            ARM::VST1d64QPseudoWB_fixed };
4656       SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
4657       return;
4658     }
4659     break;
4660   }
4661 
4662   case ARMISD::VST1x3_UPD: {
4663     if (Subtarget->hasNEON()) {
4664       static const uint16_t DOpcodes[] = { ARM::VST1d8TPseudoWB_fixed,
4665                                            ARM::VST1d16TPseudoWB_fixed,
4666                                            ARM::VST1d32TPseudoWB_fixed,
4667                                            ARM::VST1d64TPseudoWB_fixed };
4668       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowTPseudo_UPD,
4669                                             ARM::VST1q16LowTPseudo_UPD,
4670                                             ARM::VST1q32LowTPseudo_UPD,
4671                                             ARM::VST1q64LowTPseudo_UPD };
4672       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighTPseudo_UPD,
4673                                             ARM::VST1q16HighTPseudo_UPD,
4674                                             ARM::VST1q32HighTPseudo_UPD,
4675                                             ARM::VST1q64HighTPseudo_UPD };
4676       SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4677       return;
4678     }
4679     break;
4680   }
4681 
4682   case ARMISD::VST1x4_UPD: {
4683     if (Subtarget->hasNEON()) {
4684       static const uint16_t DOpcodes[] = { ARM::VST1d8QPseudoWB_fixed,
4685                                            ARM::VST1d16QPseudoWB_fixed,
4686                                            ARM::VST1d32QPseudoWB_fixed,
4687                                            ARM::VST1d64QPseudoWB_fixed };
4688       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowQPseudo_UPD,
4689                                             ARM::VST1q16LowQPseudo_UPD,
4690                                             ARM::VST1q32LowQPseudo_UPD,
4691                                             ARM::VST1q64LowQPseudo_UPD };
4692       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighQPseudo_UPD,
4693                                             ARM::VST1q16HighQPseudo_UPD,
4694                                             ARM::VST1q32HighQPseudo_UPD,
4695                                             ARM::VST1q64HighQPseudo_UPD };
4696       SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4697       return;
4698     }
4699     break;
4700   }
4701   case ARMISD::VST2LN_UPD: {
4702     static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo_UPD,
4703                                          ARM::VST2LNd16Pseudo_UPD,
4704                                          ARM::VST2LNd32Pseudo_UPD };
4705     static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo_UPD,
4706                                          ARM::VST2LNq32Pseudo_UPD };
4707     SelectVLDSTLane(N, false, true, 2, DOpcodes, QOpcodes);
4708     return;
4709   }
4710 
4711   case ARMISD::VST3LN_UPD: {
4712     static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo_UPD,
4713                                          ARM::VST3LNd16Pseudo_UPD,
4714                                          ARM::VST3LNd32Pseudo_UPD };
4715     static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo_UPD,
4716                                          ARM::VST3LNq32Pseudo_UPD };
4717     SelectVLDSTLane(N, false, true, 3, DOpcodes, QOpcodes);
4718     return;
4719   }
4720 
4721   case ARMISD::VST4LN_UPD: {
4722     static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo_UPD,
4723                                          ARM::VST4LNd16Pseudo_UPD,
4724                                          ARM::VST4LNd32Pseudo_UPD };
4725     static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo_UPD,
4726                                          ARM::VST4LNq32Pseudo_UPD };
4727     SelectVLDSTLane(N, false, true, 4, DOpcodes, QOpcodes);
4728     return;
4729   }
4730 
4731   case ISD::INTRINSIC_VOID:
4732   case ISD::INTRINSIC_W_CHAIN: {
4733     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
4734     switch (IntNo) {
4735     default:
4736       break;
4737 
4738     case Intrinsic::arm_mrrc:
4739     case Intrinsic::arm_mrrc2: {
4740       SDLoc dl(N);
4741       SDValue Chain = N->getOperand(0);
4742       unsigned Opc;
4743 
4744       if (Subtarget->isThumb())
4745         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::t2MRRC : ARM::t2MRRC2);
4746       else
4747         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::MRRC : ARM::MRRC2);
4748 
4749       SmallVector<SDValue, 5> Ops;
4750       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(), dl)); /* coproc */
4751       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(3))->getZExtValue(), dl)); /* opc */
4752       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(4))->getZExtValue(), dl)); /* CRm */
4753 
4754       // The mrrc2 instruction in ARM doesn't allow predicates, the top 4 bits of the encoded
4755       // instruction will always be '1111' but it is possible in assembly language to specify
4756       // AL as a predicate to mrrc2 but it doesn't make any difference to the encoded instruction.
4757       if (Opc != ARM::MRRC2) {
4758         Ops.push_back(getAL(CurDAG, dl));
4759         Ops.push_back(CurDAG->getRegister(0, MVT::i32));
4760       }
4761 
4762       Ops.push_back(Chain);
4763 
4764       // Writes to two registers.
4765       const EVT RetType[] = {MVT::i32, MVT::i32, MVT::Other};
4766 
4767       ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, RetType, Ops));
4768       return;
4769     }
4770     case Intrinsic::arm_ldaexd:
4771     case Intrinsic::arm_ldrexd: {
4772       SDLoc dl(N);
4773       SDValue Chain = N->getOperand(0);
4774       SDValue MemAddr = N->getOperand(2);
4775       bool isThumb = Subtarget->isThumb() && Subtarget->hasV8MBaselineOps();
4776 
4777       bool IsAcquire = IntNo == Intrinsic::arm_ldaexd;
4778       unsigned NewOpc = isThumb ? (IsAcquire ? ARM::t2LDAEXD : ARM::t2LDREXD)
4779                                 : (IsAcquire ? ARM::LDAEXD : ARM::LDREXD);
4780 
4781       // arm_ldrexd returns a i64 value in {i32, i32}
4782       std::vector<EVT> ResTys;
4783       if (isThumb) {
4784         ResTys.push_back(MVT::i32);
4785         ResTys.push_back(MVT::i32);
4786       } else
4787         ResTys.push_back(MVT::Untyped);
4788       ResTys.push_back(MVT::Other);
4789 
4790       // Place arguments in the right order.
4791       SDValue Ops[] = {MemAddr, getAL(CurDAG, dl),
4792                        CurDAG->getRegister(0, MVT::i32), Chain};
4793       SDNode *Ld = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
4794       // Transfer memoperands.
4795       MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
4796       CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
4797 
4798       // Remap uses.
4799       SDValue OutChain = isThumb ? SDValue(Ld, 2) : SDValue(Ld, 1);
4800       if (!SDValue(N, 0).use_empty()) {
4801         SDValue Result;
4802         if (isThumb)
4803           Result = SDValue(Ld, 0);
4804         else {
4805           SDValue SubRegIdx =
4806             CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
4807           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
4808               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
4809           Result = SDValue(ResNode,0);
4810         }
4811         ReplaceUses(SDValue(N, 0), Result);
4812       }
4813       if (!SDValue(N, 1).use_empty()) {
4814         SDValue Result;
4815         if (isThumb)
4816           Result = SDValue(Ld, 1);
4817         else {
4818           SDValue SubRegIdx =
4819             CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
4820           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
4821               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
4822           Result = SDValue(ResNode,0);
4823         }
4824         ReplaceUses(SDValue(N, 1), Result);
4825       }
4826       ReplaceUses(SDValue(N, 2), OutChain);
4827       CurDAG->RemoveDeadNode(N);
4828       return;
4829     }
4830     case Intrinsic::arm_stlexd:
4831     case Intrinsic::arm_strexd: {
4832       SDLoc dl(N);
4833       SDValue Chain = N->getOperand(0);
4834       SDValue Val0 = N->getOperand(2);
4835       SDValue Val1 = N->getOperand(3);
4836       SDValue MemAddr = N->getOperand(4);
4837 
4838       // Store exclusive double return a i32 value which is the return status
4839       // of the issued store.
4840       const EVT ResTys[] = {MVT::i32, MVT::Other};
4841 
4842       bool isThumb = Subtarget->isThumb() && Subtarget->hasThumb2();
4843       // Place arguments in the right order.
4844       SmallVector<SDValue, 7> Ops;
4845       if (isThumb) {
4846         Ops.push_back(Val0);
4847         Ops.push_back(Val1);
4848       } else
4849         // arm_strexd uses GPRPair.
4850         Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, Val0, Val1), 0));
4851       Ops.push_back(MemAddr);
4852       Ops.push_back(getAL(CurDAG, dl));
4853       Ops.push_back(CurDAG->getRegister(0, MVT::i32));
4854       Ops.push_back(Chain);
4855 
4856       bool IsRelease = IntNo == Intrinsic::arm_stlexd;
4857       unsigned NewOpc = isThumb ? (IsRelease ? ARM::t2STLEXD : ARM::t2STREXD)
4858                                 : (IsRelease ? ARM::STLEXD : ARM::STREXD);
4859 
4860       SDNode *St = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
4861       // Transfer memoperands.
4862       MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
4863       CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
4864 
4865       ReplaceNode(N, St);
4866       return;
4867     }
4868 
4869     case Intrinsic::arm_neon_vld1: {
4870       static const uint16_t DOpcodes[] = { ARM::VLD1d8, ARM::VLD1d16,
4871                                            ARM::VLD1d32, ARM::VLD1d64 };
4872       static const uint16_t QOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
4873                                            ARM::VLD1q32, ARM::VLD1q64};
4874       SelectVLD(N, false, 1, DOpcodes, QOpcodes, nullptr);
4875       return;
4876     }
4877 
4878     case Intrinsic::arm_neon_vld1x2: {
4879       static const uint16_t DOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
4880                                            ARM::VLD1q32, ARM::VLD1q64 };
4881       static const uint16_t QOpcodes[] = { ARM::VLD1d8QPseudo,
4882                                            ARM::VLD1d16QPseudo,
4883                                            ARM::VLD1d32QPseudo,
4884                                            ARM::VLD1d64QPseudo };
4885       SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
4886       return;
4887     }
4888 
4889     case Intrinsic::arm_neon_vld1x3: {
4890       static const uint16_t DOpcodes[] = { ARM::VLD1d8TPseudo,
4891                                            ARM::VLD1d16TPseudo,
4892                                            ARM::VLD1d32TPseudo,
4893                                            ARM::VLD1d64TPseudo };
4894       static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowTPseudo_UPD,
4895                                             ARM::VLD1q16LowTPseudo_UPD,
4896                                             ARM::VLD1q32LowTPseudo_UPD,
4897                                             ARM::VLD1q64LowTPseudo_UPD };
4898       static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighTPseudo,
4899                                             ARM::VLD1q16HighTPseudo,
4900                                             ARM::VLD1q32HighTPseudo,
4901                                             ARM::VLD1q64HighTPseudo };
4902       SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
4903       return;
4904     }
4905 
4906     case Intrinsic::arm_neon_vld1x4: {
4907       static const uint16_t DOpcodes[] = { ARM::VLD1d8QPseudo,
4908                                            ARM::VLD1d16QPseudo,
4909                                            ARM::VLD1d32QPseudo,
4910                                            ARM::VLD1d64QPseudo };
4911       static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowQPseudo_UPD,
4912                                             ARM::VLD1q16LowQPseudo_UPD,
4913                                             ARM::VLD1q32LowQPseudo_UPD,
4914                                             ARM::VLD1q64LowQPseudo_UPD };
4915       static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighQPseudo,
4916                                             ARM::VLD1q16HighQPseudo,
4917                                             ARM::VLD1q32HighQPseudo,
4918                                             ARM::VLD1q64HighQPseudo };
4919       SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
4920       return;
4921     }
4922 
4923     case Intrinsic::arm_neon_vld2: {
4924       static const uint16_t DOpcodes[] = { ARM::VLD2d8, ARM::VLD2d16,
4925                                            ARM::VLD2d32, ARM::VLD1q64 };
4926       static const uint16_t QOpcodes[] = { ARM::VLD2q8Pseudo, ARM::VLD2q16Pseudo,
4927                                            ARM::VLD2q32Pseudo };
4928       SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
4929       return;
4930     }
4931 
4932     case Intrinsic::arm_neon_vld3: {
4933       static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo,
4934                                            ARM::VLD3d16Pseudo,
4935                                            ARM::VLD3d32Pseudo,
4936                                            ARM::VLD1d64TPseudo };
4937       static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
4938                                             ARM::VLD3q16Pseudo_UPD,
4939                                             ARM::VLD3q32Pseudo_UPD };
4940       static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo,
4941                                             ARM::VLD3q16oddPseudo,
4942                                             ARM::VLD3q32oddPseudo };
4943       SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
4944       return;
4945     }
4946 
4947     case Intrinsic::arm_neon_vld4: {
4948       static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo,
4949                                            ARM::VLD4d16Pseudo,
4950                                            ARM::VLD4d32Pseudo,
4951                                            ARM::VLD1d64QPseudo };
4952       static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
4953                                             ARM::VLD4q16Pseudo_UPD,
4954                                             ARM::VLD4q32Pseudo_UPD };
4955       static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo,
4956                                             ARM::VLD4q16oddPseudo,
4957                                             ARM::VLD4q32oddPseudo };
4958       SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
4959       return;
4960     }
4961 
4962     case Intrinsic::arm_neon_vld2dup: {
4963       static const uint16_t DOpcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
4964                                            ARM::VLD2DUPd32, ARM::VLD1q64 };
4965       static const uint16_t QOpcodes0[] = { ARM::VLD2DUPq8EvenPseudo,
4966                                             ARM::VLD2DUPq16EvenPseudo,
4967                                             ARM::VLD2DUPq32EvenPseudo };
4968       static const uint16_t QOpcodes1[] = { ARM::VLD2DUPq8OddPseudo,
4969                                             ARM::VLD2DUPq16OddPseudo,
4970                                             ARM::VLD2DUPq32OddPseudo };
4971       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 2,
4972                    DOpcodes, QOpcodes0, QOpcodes1);
4973       return;
4974     }
4975 
4976     case Intrinsic::arm_neon_vld3dup: {
4977       static const uint16_t DOpcodes[] = { ARM::VLD3DUPd8Pseudo,
4978                                            ARM::VLD3DUPd16Pseudo,
4979                                            ARM::VLD3DUPd32Pseudo,
4980                                            ARM::VLD1d64TPseudo };
4981       static const uint16_t QOpcodes0[] = { ARM::VLD3DUPq8EvenPseudo,
4982                                             ARM::VLD3DUPq16EvenPseudo,
4983                                             ARM::VLD3DUPq32EvenPseudo };
4984       static const uint16_t QOpcodes1[] = { ARM::VLD3DUPq8OddPseudo,
4985                                             ARM::VLD3DUPq16OddPseudo,
4986                                             ARM::VLD3DUPq32OddPseudo };
4987       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 3,
4988                    DOpcodes, QOpcodes0, QOpcodes1);
4989       return;
4990     }
4991 
4992     case Intrinsic::arm_neon_vld4dup: {
4993       static const uint16_t DOpcodes[] = { ARM::VLD4DUPd8Pseudo,
4994                                            ARM::VLD4DUPd16Pseudo,
4995                                            ARM::VLD4DUPd32Pseudo,
4996                                            ARM::VLD1d64QPseudo };
4997       static const uint16_t QOpcodes0[] = { ARM::VLD4DUPq8EvenPseudo,
4998                                             ARM::VLD4DUPq16EvenPseudo,
4999                                             ARM::VLD4DUPq32EvenPseudo };
5000       static const uint16_t QOpcodes1[] = { ARM::VLD4DUPq8OddPseudo,
5001                                             ARM::VLD4DUPq16OddPseudo,
5002                                             ARM::VLD4DUPq32OddPseudo };
5003       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 4,
5004                    DOpcodes, QOpcodes0, QOpcodes1);
5005       return;
5006     }
5007 
5008     case Intrinsic::arm_neon_vld2lane: {
5009       static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo,
5010                                            ARM::VLD2LNd16Pseudo,
5011                                            ARM::VLD2LNd32Pseudo };
5012       static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo,
5013                                            ARM::VLD2LNq32Pseudo };
5014       SelectVLDSTLane(N, true, false, 2, DOpcodes, QOpcodes);
5015       return;
5016     }
5017 
5018     case Intrinsic::arm_neon_vld3lane: {
5019       static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo,
5020                                            ARM::VLD3LNd16Pseudo,
5021                                            ARM::VLD3LNd32Pseudo };
5022       static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo,
5023                                            ARM::VLD3LNq32Pseudo };
5024       SelectVLDSTLane(N, true, false, 3, DOpcodes, QOpcodes);
5025       return;
5026     }
5027 
5028     case Intrinsic::arm_neon_vld4lane: {
5029       static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo,
5030                                            ARM::VLD4LNd16Pseudo,
5031                                            ARM::VLD4LNd32Pseudo };
5032       static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo,
5033                                            ARM::VLD4LNq32Pseudo };
5034       SelectVLDSTLane(N, true, false, 4, DOpcodes, QOpcodes);
5035       return;
5036     }
5037 
5038     case Intrinsic::arm_neon_vst1: {
5039       static const uint16_t DOpcodes[] = { ARM::VST1d8, ARM::VST1d16,
5040                                            ARM::VST1d32, ARM::VST1d64 };
5041       static const uint16_t QOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
5042                                            ARM::VST1q32, ARM::VST1q64 };
5043       SelectVST(N, false, 1, DOpcodes, QOpcodes, nullptr);
5044       return;
5045     }
5046 
5047     case Intrinsic::arm_neon_vst1x2: {
5048       static const uint16_t DOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
5049                                            ARM::VST1q32, ARM::VST1q64 };
5050       static const uint16_t QOpcodes[] = { ARM::VST1d8QPseudo,
5051                                            ARM::VST1d16QPseudo,
5052                                            ARM::VST1d32QPseudo,
5053                                            ARM::VST1d64QPseudo };
5054       SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
5055       return;
5056     }
5057 
5058     case Intrinsic::arm_neon_vst1x3: {
5059       static const uint16_t DOpcodes[] = { ARM::VST1d8TPseudo,
5060                                            ARM::VST1d16TPseudo,
5061                                            ARM::VST1d32TPseudo,
5062                                            ARM::VST1d64TPseudo };
5063       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowTPseudo_UPD,
5064                                             ARM::VST1q16LowTPseudo_UPD,
5065                                             ARM::VST1q32LowTPseudo_UPD,
5066                                             ARM::VST1q64LowTPseudo_UPD };
5067       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighTPseudo,
5068                                             ARM::VST1q16HighTPseudo,
5069                                             ARM::VST1q32HighTPseudo,
5070                                             ARM::VST1q64HighTPseudo };
5071       SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
5072       return;
5073     }
5074 
5075     case Intrinsic::arm_neon_vst1x4: {
5076       static const uint16_t DOpcodes[] = { ARM::VST1d8QPseudo,
5077                                            ARM::VST1d16QPseudo,
5078                                            ARM::VST1d32QPseudo,
5079                                            ARM::VST1d64QPseudo };
5080       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowQPseudo_UPD,
5081                                             ARM::VST1q16LowQPseudo_UPD,
5082                                             ARM::VST1q32LowQPseudo_UPD,
5083                                             ARM::VST1q64LowQPseudo_UPD };
5084       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighQPseudo,
5085                                             ARM::VST1q16HighQPseudo,
5086                                             ARM::VST1q32HighQPseudo,
5087                                             ARM::VST1q64HighQPseudo };
5088       SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
5089       return;
5090     }
5091 
5092     case Intrinsic::arm_neon_vst2: {
5093       static const uint16_t DOpcodes[] = { ARM::VST2d8, ARM::VST2d16,
5094                                            ARM::VST2d32, ARM::VST1q64 };
5095       static const uint16_t QOpcodes[] = { ARM::VST2q8Pseudo, ARM::VST2q16Pseudo,
5096                                            ARM::VST2q32Pseudo };
5097       SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
5098       return;
5099     }
5100 
5101     case Intrinsic::arm_neon_vst3: {
5102       static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo,
5103                                            ARM::VST3d16Pseudo,
5104                                            ARM::VST3d32Pseudo,
5105                                            ARM::VST1d64TPseudo };
5106       static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
5107                                             ARM::VST3q16Pseudo_UPD,
5108                                             ARM::VST3q32Pseudo_UPD };
5109       static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo,
5110                                             ARM::VST3q16oddPseudo,
5111                                             ARM::VST3q32oddPseudo };
5112       SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
5113       return;
5114     }
5115 
5116     case Intrinsic::arm_neon_vst4: {
5117       static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo,
5118                                            ARM::VST4d16Pseudo,
5119                                            ARM::VST4d32Pseudo,
5120                                            ARM::VST1d64QPseudo };
5121       static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
5122                                             ARM::VST4q16Pseudo_UPD,
5123                                             ARM::VST4q32Pseudo_UPD };
5124       static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo,
5125                                             ARM::VST4q16oddPseudo,
5126                                             ARM::VST4q32oddPseudo };
5127       SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
5128       return;
5129     }
5130 
5131     case Intrinsic::arm_neon_vst2lane: {
5132       static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo,
5133                                            ARM::VST2LNd16Pseudo,
5134                                            ARM::VST2LNd32Pseudo };
5135       static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo,
5136                                            ARM::VST2LNq32Pseudo };
5137       SelectVLDSTLane(N, false, false, 2, DOpcodes, QOpcodes);
5138       return;
5139     }
5140 
5141     case Intrinsic::arm_neon_vst3lane: {
5142       static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo,
5143                                            ARM::VST3LNd16Pseudo,
5144                                            ARM::VST3LNd32Pseudo };
5145       static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo,
5146                                            ARM::VST3LNq32Pseudo };
5147       SelectVLDSTLane(N, false, false, 3, DOpcodes, QOpcodes);
5148       return;
5149     }
5150 
5151     case Intrinsic::arm_neon_vst4lane: {
5152       static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo,
5153                                            ARM::VST4LNd16Pseudo,
5154                                            ARM::VST4LNd32Pseudo };
5155       static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo,
5156                                            ARM::VST4LNq32Pseudo };
5157       SelectVLDSTLane(N, false, false, 4, DOpcodes, QOpcodes);
5158       return;
5159     }
5160 
5161     case Intrinsic::arm_mve_vldr_gather_base_wb:
5162     case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
5163       static const uint16_t Opcodes[] = {ARM::MVE_VLDRWU32_qi_pre,
5164                                          ARM::MVE_VLDRDU64_qi_pre};
5165       SelectMVE_WB(N, Opcodes,
5166                    IntNo == Intrinsic::arm_mve_vldr_gather_base_wb_predicated);
5167       return;
5168     }
5169 
5170     case Intrinsic::arm_mve_vld2q: {
5171       static const uint16_t Opcodes8[] = {ARM::MVE_VLD20_8, ARM::MVE_VLD21_8};
5172       static const uint16_t Opcodes16[] = {ARM::MVE_VLD20_16,
5173                                            ARM::MVE_VLD21_16};
5174       static const uint16_t Opcodes32[] = {ARM::MVE_VLD20_32,
5175                                            ARM::MVE_VLD21_32};
5176       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
5177       SelectMVE_VLD(N, 2, Opcodes, false);
5178       return;
5179     }
5180 
5181     case Intrinsic::arm_mve_vld4q: {
5182       static const uint16_t Opcodes8[] = {ARM::MVE_VLD40_8, ARM::MVE_VLD41_8,
5183                                           ARM::MVE_VLD42_8, ARM::MVE_VLD43_8};
5184       static const uint16_t Opcodes16[] = {ARM::MVE_VLD40_16, ARM::MVE_VLD41_16,
5185                                            ARM::MVE_VLD42_16,
5186                                            ARM::MVE_VLD43_16};
5187       static const uint16_t Opcodes32[] = {ARM::MVE_VLD40_32, ARM::MVE_VLD41_32,
5188                                            ARM::MVE_VLD42_32,
5189                                            ARM::MVE_VLD43_32};
5190       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
5191       SelectMVE_VLD(N, 4, Opcodes, false);
5192       return;
5193     }
5194     }
5195     break;
5196   }
5197 
5198   case ISD::INTRINSIC_WO_CHAIN: {
5199     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5200     switch (IntNo) {
5201     default:
5202       break;
5203 
5204     // Scalar f32 -> bf16
5205     case Intrinsic::arm_neon_vcvtbfp2bf: {
5206       SDLoc dl(N);
5207       const SDValue &Src = N->getOperand(1);
5208       llvm::EVT DestTy = N->getValueType(0);
5209       SDValue Pred = getAL(CurDAG, dl);
5210       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
5211       SDValue Ops[] = { Src, Src, Pred, Reg0 };
5212       CurDAG->SelectNodeTo(N, ARM::BF16_VCVTB, DestTy, Ops);
5213       return;
5214     }
5215 
5216     // Vector v4f32 -> v4bf16
5217     case Intrinsic::arm_neon_vcvtfp2bf: {
5218       SDLoc dl(N);
5219       const SDValue &Src = N->getOperand(1);
5220       SDValue Pred = getAL(CurDAG, dl);
5221       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
5222       SDValue Ops[] = { Src, Pred, Reg0 };
5223       CurDAG->SelectNodeTo(N, ARM::BF16_VCVT, MVT::v4bf16, Ops);
5224       return;
5225     }
5226 
5227     case Intrinsic::arm_mve_urshrl:
5228       SelectMVE_LongShift(N, ARM::MVE_URSHRL, true, false);
5229       return;
5230     case Intrinsic::arm_mve_uqshll:
5231       SelectMVE_LongShift(N, ARM::MVE_UQSHLL, true, false);
5232       return;
5233     case Intrinsic::arm_mve_srshrl:
5234       SelectMVE_LongShift(N, ARM::MVE_SRSHRL, true, false);
5235       return;
5236     case Intrinsic::arm_mve_sqshll:
5237       SelectMVE_LongShift(N, ARM::MVE_SQSHLL, true, false);
5238       return;
5239     case Intrinsic::arm_mve_uqrshll:
5240       SelectMVE_LongShift(N, ARM::MVE_UQRSHLL, false, true);
5241       return;
5242     case Intrinsic::arm_mve_sqrshrl:
5243       SelectMVE_LongShift(N, ARM::MVE_SQRSHRL, false, true);
5244       return;
5245 
5246     case Intrinsic::arm_mve_vadc:
5247     case Intrinsic::arm_mve_vadc_predicated:
5248       SelectMVE_VADCSBC(N, ARM::MVE_VADC, ARM::MVE_VADCI, true,
5249                         IntNo == Intrinsic::arm_mve_vadc_predicated);
5250       return;
5251     case Intrinsic::arm_mve_vsbc:
5252     case Intrinsic::arm_mve_vsbc_predicated:
5253       SelectMVE_VADCSBC(N, ARM::MVE_VSBC, ARM::MVE_VSBCI, true,
5254                         IntNo == Intrinsic::arm_mve_vsbc_predicated);
5255       return;
5256     case Intrinsic::arm_mve_vshlc:
5257     case Intrinsic::arm_mve_vshlc_predicated:
5258       SelectMVE_VSHLC(N, IntNo == Intrinsic::arm_mve_vshlc_predicated);
5259       return;
5260 
5261     case Intrinsic::arm_mve_vmlldava:
5262     case Intrinsic::arm_mve_vmlldava_predicated: {
5263       static const uint16_t OpcodesU[] = {
5264           ARM::MVE_VMLALDAVu16,   ARM::MVE_VMLALDAVu32,
5265           ARM::MVE_VMLALDAVau16,  ARM::MVE_VMLALDAVau32,
5266       };
5267       static const uint16_t OpcodesS[] = {
5268           ARM::MVE_VMLALDAVs16,   ARM::MVE_VMLALDAVs32,
5269           ARM::MVE_VMLALDAVas16,  ARM::MVE_VMLALDAVas32,
5270           ARM::MVE_VMLALDAVxs16,  ARM::MVE_VMLALDAVxs32,
5271           ARM::MVE_VMLALDAVaxs16, ARM::MVE_VMLALDAVaxs32,
5272           ARM::MVE_VMLSLDAVs16,   ARM::MVE_VMLSLDAVs32,
5273           ARM::MVE_VMLSLDAVas16,  ARM::MVE_VMLSLDAVas32,
5274           ARM::MVE_VMLSLDAVxs16,  ARM::MVE_VMLSLDAVxs32,
5275           ARM::MVE_VMLSLDAVaxs16, ARM::MVE_VMLSLDAVaxs32,
5276       };
5277       SelectMVE_VMLLDAV(N, IntNo == Intrinsic::arm_mve_vmlldava_predicated,
5278                         OpcodesS, OpcodesU);
5279       return;
5280     }
5281 
5282     case Intrinsic::arm_mve_vrmlldavha:
5283     case Intrinsic::arm_mve_vrmlldavha_predicated: {
5284       static const uint16_t OpcodesU[] = {
5285           ARM::MVE_VRMLALDAVHu32,  ARM::MVE_VRMLALDAVHau32,
5286       };
5287       static const uint16_t OpcodesS[] = {
5288           ARM::MVE_VRMLALDAVHs32,  ARM::MVE_VRMLALDAVHas32,
5289           ARM::MVE_VRMLALDAVHxs32, ARM::MVE_VRMLALDAVHaxs32,
5290           ARM::MVE_VRMLSLDAVHs32,  ARM::MVE_VRMLSLDAVHas32,
5291           ARM::MVE_VRMLSLDAVHxs32, ARM::MVE_VRMLSLDAVHaxs32,
5292       };
5293       SelectMVE_VRMLLDAVH(N, IntNo == Intrinsic::arm_mve_vrmlldavha_predicated,
5294                           OpcodesS, OpcodesU);
5295       return;
5296     }
5297 
5298     case Intrinsic::arm_mve_vidup:
5299     case Intrinsic::arm_mve_vidup_predicated: {
5300       static const uint16_t Opcodes[] = {
5301           ARM::MVE_VIDUPu8, ARM::MVE_VIDUPu16, ARM::MVE_VIDUPu32,
5302       };
5303       SelectMVE_VxDUP(N, Opcodes, false,
5304                       IntNo == Intrinsic::arm_mve_vidup_predicated);
5305       return;
5306     }
5307 
5308     case Intrinsic::arm_mve_vddup:
5309     case Intrinsic::arm_mve_vddup_predicated: {
5310       static const uint16_t Opcodes[] = {
5311           ARM::MVE_VDDUPu8, ARM::MVE_VDDUPu16, ARM::MVE_VDDUPu32,
5312       };
5313       SelectMVE_VxDUP(N, Opcodes, false,
5314                       IntNo == Intrinsic::arm_mve_vddup_predicated);
5315       return;
5316     }
5317 
5318     case Intrinsic::arm_mve_viwdup:
5319     case Intrinsic::arm_mve_viwdup_predicated: {
5320       static const uint16_t Opcodes[] = {
5321           ARM::MVE_VIWDUPu8, ARM::MVE_VIWDUPu16, ARM::MVE_VIWDUPu32,
5322       };
5323       SelectMVE_VxDUP(N, Opcodes, true,
5324                       IntNo == Intrinsic::arm_mve_viwdup_predicated);
5325       return;
5326     }
5327 
5328     case Intrinsic::arm_mve_vdwdup:
5329     case Intrinsic::arm_mve_vdwdup_predicated: {
5330       static const uint16_t Opcodes[] = {
5331           ARM::MVE_VDWDUPu8, ARM::MVE_VDWDUPu16, ARM::MVE_VDWDUPu32,
5332       };
5333       SelectMVE_VxDUP(N, Opcodes, true,
5334                       IntNo == Intrinsic::arm_mve_vdwdup_predicated);
5335       return;
5336     }
5337 
5338     case Intrinsic::arm_cde_cx1d:
5339     case Intrinsic::arm_cde_cx1da:
5340     case Intrinsic::arm_cde_cx2d:
5341     case Intrinsic::arm_cde_cx2da:
5342     case Intrinsic::arm_cde_cx3d:
5343     case Intrinsic::arm_cde_cx3da: {
5344       bool HasAccum = IntNo == Intrinsic::arm_cde_cx1da ||
5345                       IntNo == Intrinsic::arm_cde_cx2da ||
5346                       IntNo == Intrinsic::arm_cde_cx3da;
5347       size_t NumExtraOps;
5348       uint16_t Opcode;
5349       switch (IntNo) {
5350       case Intrinsic::arm_cde_cx1d:
5351       case Intrinsic::arm_cde_cx1da:
5352         NumExtraOps = 0;
5353         Opcode = HasAccum ? ARM::CDE_CX1DA : ARM::CDE_CX1D;
5354         break;
5355       case Intrinsic::arm_cde_cx2d:
5356       case Intrinsic::arm_cde_cx2da:
5357         NumExtraOps = 1;
5358         Opcode = HasAccum ? ARM::CDE_CX2DA : ARM::CDE_CX2D;
5359         break;
5360       case Intrinsic::arm_cde_cx3d:
5361       case Intrinsic::arm_cde_cx3da:
5362         NumExtraOps = 2;
5363         Opcode = HasAccum ? ARM::CDE_CX3DA : ARM::CDE_CX3D;
5364         break;
5365       default:
5366         llvm_unreachable("Unexpected opcode");
5367       }
5368       SelectCDE_CXxD(N, Opcode, NumExtraOps, HasAccum);
5369       return;
5370     }
5371     }
5372     break;
5373   }
5374 
5375   case ISD::ATOMIC_CMP_SWAP:
5376     SelectCMP_SWAP(N);
5377     return;
5378   }
5379 
5380   SelectCode(N);
5381 }
5382 
5383 // Inspect a register string of the form
5384 // cp<coprocessor>:<opc1>:c<CRn>:c<CRm>:<opc2> (32bit) or
5385 // cp<coprocessor>:<opc1>:c<CRm> (64bit) inspect the fields of the string
5386 // and obtain the integer operands from them, adding these operands to the
5387 // provided vector.
5388 static void getIntOperandsFromRegisterString(StringRef RegString,
5389                                              SelectionDAG *CurDAG,
5390                                              const SDLoc &DL,
5391                                              std::vector<SDValue> &Ops) {
5392   SmallVector<StringRef, 5> Fields;
5393   RegString.split(Fields, ':');
5394 
5395   if (Fields.size() > 1) {
5396     bool AllIntFields = true;
5397 
5398     for (StringRef Field : Fields) {
5399       // Need to trim out leading 'cp' characters and get the integer field.
5400       unsigned IntField;
5401       AllIntFields &= !Field.trim("CPcp").getAsInteger(10, IntField);
5402       Ops.push_back(CurDAG->getTargetConstant(IntField, DL, MVT::i32));
5403     }
5404 
5405     assert(AllIntFields &&
5406             "Unexpected non-integer value in special register string.");
5407     (void)AllIntFields;
5408   }
5409 }
5410 
5411 // Maps a Banked Register string to its mask value. The mask value returned is
5412 // for use in the MRSbanked / MSRbanked instruction nodes as the Banked Register
5413 // mask operand, which expresses which register is to be used, e.g. r8, and in
5414 // which mode it is to be used, e.g. usr. Returns -1 to signify that the string
5415 // was invalid.
5416 static inline int getBankedRegisterMask(StringRef RegString) {
5417   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegString.lower());
5418   if (!TheReg)
5419      return -1;
5420   return TheReg->Encoding;
5421 }
5422 
5423 // The flags here are common to those allowed for apsr in the A class cores and
5424 // those allowed for the special registers in the M class cores. Returns a
5425 // value representing which flags were present, -1 if invalid.
5426 static inline int getMClassFlagsMask(StringRef Flags) {
5427   return StringSwitch<int>(Flags)
5428           .Case("", 0x2) // no flags means nzcvq for psr registers, and 0x2 is
5429                          // correct when flags are not permitted
5430           .Case("g", 0x1)
5431           .Case("nzcvq", 0x2)
5432           .Case("nzcvqg", 0x3)
5433           .Default(-1);
5434 }
5435 
5436 // Maps MClass special registers string to its value for use in the
5437 // t2MRS_M/t2MSR_M instruction nodes as the SYSm value operand.
5438 // Returns -1 to signify that the string was invalid.
5439 static int getMClassRegisterMask(StringRef Reg, const ARMSubtarget *Subtarget) {
5440   auto TheReg = ARMSysReg::lookupMClassSysRegByName(Reg);
5441   const FeatureBitset &FeatureBits = Subtarget->getFeatureBits();
5442   if (!TheReg || !TheReg->hasRequiredFeatures(FeatureBits))
5443     return -1;
5444   return (int)(TheReg->Encoding & 0xFFF); // SYSm value
5445 }
5446 
5447 static int getARClassRegisterMask(StringRef Reg, StringRef Flags) {
5448   // The mask operand contains the special register (R Bit) in bit 4, whether
5449   // the register is spsr (R bit is 1) or one of cpsr/apsr (R bit is 0), and
5450   // bits 3-0 contains the fields to be accessed in the special register, set by
5451   // the flags provided with the register.
5452   int Mask = 0;
5453   if (Reg == "apsr") {
5454     // The flags permitted for apsr are the same flags that are allowed in
5455     // M class registers. We get the flag value and then shift the flags into
5456     // the correct place to combine with the mask.
5457     Mask = getMClassFlagsMask(Flags);
5458     if (Mask == -1)
5459       return -1;
5460     return Mask << 2;
5461   }
5462 
5463   if (Reg != "cpsr" && Reg != "spsr") {
5464     return -1;
5465   }
5466 
5467   // This is the same as if the flags were "fc"
5468   if (Flags.empty() || Flags == "all")
5469     return Mask | 0x9;
5470 
5471   // Inspect the supplied flags string and set the bits in the mask for
5472   // the relevant and valid flags allowed for cpsr and spsr.
5473   for (char Flag : Flags) {
5474     int FlagVal;
5475     switch (Flag) {
5476       case 'c':
5477         FlagVal = 0x1;
5478         break;
5479       case 'x':
5480         FlagVal = 0x2;
5481         break;
5482       case 's':
5483         FlagVal = 0x4;
5484         break;
5485       case 'f':
5486         FlagVal = 0x8;
5487         break;
5488       default:
5489         FlagVal = 0;
5490     }
5491 
5492     // This avoids allowing strings where the same flag bit appears twice.
5493     if (!FlagVal || (Mask & FlagVal))
5494       return -1;
5495     Mask |= FlagVal;
5496   }
5497 
5498   // If the register is spsr then we need to set the R bit.
5499   if (Reg == "spsr")
5500     Mask |= 0x10;
5501 
5502   return Mask;
5503 }
5504 
5505 // Lower the read_register intrinsic to ARM specific DAG nodes
5506 // using the supplied metadata string to select the instruction node to use
5507 // and the registers/masks to construct as operands for the node.
5508 bool ARMDAGToDAGISel::tryReadRegister(SDNode *N){
5509   const auto *MD = cast<MDNodeSDNode>(N->getOperand(1));
5510   const auto *RegString = cast<MDString>(MD->getMD()->getOperand(0));
5511   bool IsThumb2 = Subtarget->isThumb2();
5512   SDLoc DL(N);
5513 
5514   std::vector<SDValue> Ops;
5515   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
5516 
5517   if (!Ops.empty()) {
5518     // If the special register string was constructed of fields (as defined
5519     // in the ACLE) then need to lower to MRC node (32 bit) or
5520     // MRRC node(64 bit), we can make the distinction based on the number of
5521     // operands we have.
5522     unsigned Opcode;
5523     SmallVector<EVT, 3> ResTypes;
5524     if (Ops.size() == 5){
5525       Opcode = IsThumb2 ? ARM::t2MRC : ARM::MRC;
5526       ResTypes.append({ MVT::i32, MVT::Other });
5527     } else {
5528       assert(Ops.size() == 3 &&
5529               "Invalid number of fields in special register string.");
5530       Opcode = IsThumb2 ? ARM::t2MRRC : ARM::MRRC;
5531       ResTypes.append({ MVT::i32, MVT::i32, MVT::Other });
5532     }
5533 
5534     Ops.push_back(getAL(CurDAG, DL));
5535     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
5536     Ops.push_back(N->getOperand(0));
5537     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, ResTypes, Ops));
5538     return true;
5539   }
5540 
5541   std::string SpecialReg = RegString->getString().lower();
5542 
5543   int BankedReg = getBankedRegisterMask(SpecialReg);
5544   if (BankedReg != -1) {
5545     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32),
5546             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5547             N->getOperand(0) };
5548     ReplaceNode(
5549         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSbanked : ARM::MRSbanked,
5550                                   DL, MVT::i32, MVT::Other, Ops));
5551     return true;
5552   }
5553 
5554   // The VFP registers are read by creating SelectionDAG nodes with opcodes
5555   // corresponding to the register that is being read from. So we switch on the
5556   // string to find which opcode we need to use.
5557   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
5558                     .Case("fpscr", ARM::VMRS)
5559                     .Case("fpexc", ARM::VMRS_FPEXC)
5560                     .Case("fpsid", ARM::VMRS_FPSID)
5561                     .Case("mvfr0", ARM::VMRS_MVFR0)
5562                     .Case("mvfr1", ARM::VMRS_MVFR1)
5563                     .Case("mvfr2", ARM::VMRS_MVFR2)
5564                     .Case("fpinst", ARM::VMRS_FPINST)
5565                     .Case("fpinst2", ARM::VMRS_FPINST2)
5566                     .Default(0);
5567 
5568   // If an opcode was found then we can lower the read to a VFP instruction.
5569   if (Opcode) {
5570     if (!Subtarget->hasVFP2Base())
5571       return false;
5572     if (Opcode == ARM::VMRS_MVFR2 && !Subtarget->hasFPARMv8Base())
5573       return false;
5574 
5575     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5576             N->getOperand(0) };
5577     ReplaceNode(N,
5578                 CurDAG->getMachineNode(Opcode, DL, MVT::i32, MVT::Other, Ops));
5579     return true;
5580   }
5581 
5582   // If the target is M Class then need to validate that the register string
5583   // is an acceptable value, so check that a mask can be constructed from the
5584   // string.
5585   if (Subtarget->isMClass()) {
5586     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
5587     if (SYSmValue == -1)
5588       return false;
5589 
5590     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
5591                       getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5592                       N->getOperand(0) };
5593     ReplaceNode(
5594         N, CurDAG->getMachineNode(ARM::t2MRS_M, DL, MVT::i32, MVT::Other, Ops));
5595     return true;
5596   }
5597 
5598   // Here we know the target is not M Class so we need to check if it is one
5599   // of the remaining possible values which are apsr, cpsr or spsr.
5600   if (SpecialReg == "apsr" || SpecialReg == "cpsr") {
5601     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5602             N->getOperand(0) };
5603     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRS_AR : ARM::MRS,
5604                                           DL, MVT::i32, MVT::Other, Ops));
5605     return true;
5606   }
5607 
5608   if (SpecialReg == "spsr") {
5609     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5610             N->getOperand(0) };
5611     ReplaceNode(
5612         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSsys_AR : ARM::MRSsys, DL,
5613                                   MVT::i32, MVT::Other, Ops));
5614     return true;
5615   }
5616 
5617   return false;
5618 }
5619 
5620 // Lower the write_register intrinsic to ARM specific DAG nodes
5621 // using the supplied metadata string to select the instruction node to use
5622 // and the registers/masks to use in the nodes
5623 bool ARMDAGToDAGISel::tryWriteRegister(SDNode *N){
5624   const auto *MD = cast<MDNodeSDNode>(N->getOperand(1));
5625   const auto *RegString = cast<MDString>(MD->getMD()->getOperand(0));
5626   bool IsThumb2 = Subtarget->isThumb2();
5627   SDLoc DL(N);
5628 
5629   std::vector<SDValue> Ops;
5630   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
5631 
5632   if (!Ops.empty()) {
5633     // If the special register string was constructed of fields (as defined
5634     // in the ACLE) then need to lower to MCR node (32 bit) or
5635     // MCRR node(64 bit), we can make the distinction based on the number of
5636     // operands we have.
5637     unsigned Opcode;
5638     if (Ops.size() == 5) {
5639       Opcode = IsThumb2 ? ARM::t2MCR : ARM::MCR;
5640       Ops.insert(Ops.begin()+2, N->getOperand(2));
5641     } else {
5642       assert(Ops.size() == 3 &&
5643               "Invalid number of fields in special register string.");
5644       Opcode = IsThumb2 ? ARM::t2MCRR : ARM::MCRR;
5645       SDValue WriteValue[] = { N->getOperand(2), N->getOperand(3) };
5646       Ops.insert(Ops.begin()+2, WriteValue, WriteValue+2);
5647     }
5648 
5649     Ops.push_back(getAL(CurDAG, DL));
5650     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
5651     Ops.push_back(N->getOperand(0));
5652 
5653     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
5654     return true;
5655   }
5656 
5657   std::string SpecialReg = RegString->getString().lower();
5658   int BankedReg = getBankedRegisterMask(SpecialReg);
5659   if (BankedReg != -1) {
5660     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32), N->getOperand(2),
5661             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5662             N->getOperand(0) };
5663     ReplaceNode(
5664         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSRbanked : ARM::MSRbanked,
5665                                   DL, MVT::Other, Ops));
5666     return true;
5667   }
5668 
5669   // The VFP registers are written to by creating SelectionDAG nodes with
5670   // opcodes corresponding to the register that is being written. So we switch
5671   // on the string to find which opcode we need to use.
5672   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
5673                     .Case("fpscr", ARM::VMSR)
5674                     .Case("fpexc", ARM::VMSR_FPEXC)
5675                     .Case("fpsid", ARM::VMSR_FPSID)
5676                     .Case("fpinst", ARM::VMSR_FPINST)
5677                     .Case("fpinst2", ARM::VMSR_FPINST2)
5678                     .Default(0);
5679 
5680   if (Opcode) {
5681     if (!Subtarget->hasVFP2Base())
5682       return false;
5683     Ops = { N->getOperand(2), getAL(CurDAG, DL),
5684             CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
5685     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
5686     return true;
5687   }
5688 
5689   std::pair<StringRef, StringRef> Fields;
5690   Fields = StringRef(SpecialReg).rsplit('_');
5691   std::string Reg = Fields.first.str();
5692   StringRef Flags = Fields.second;
5693 
5694   // If the target was M Class then need to validate the special register value
5695   // and retrieve the mask for use in the instruction node.
5696   if (Subtarget->isMClass()) {
5697     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
5698     if (SYSmValue == -1)
5699       return false;
5700 
5701     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
5702                       N->getOperand(2), getAL(CurDAG, DL),
5703                       CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
5704     ReplaceNode(N, CurDAG->getMachineNode(ARM::t2MSR_M, DL, MVT::Other, Ops));
5705     return true;
5706   }
5707 
5708   // We then check to see if a valid mask can be constructed for one of the
5709   // register string values permitted for the A and R class cores. These values
5710   // are apsr, spsr and cpsr; these are also valid on older cores.
5711   int Mask = getARClassRegisterMask(Reg, Flags);
5712   if (Mask != -1) {
5713     Ops = { CurDAG->getTargetConstant(Mask, DL, MVT::i32), N->getOperand(2),
5714             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5715             N->getOperand(0) };
5716     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSR_AR : ARM::MSR,
5717                                           DL, MVT::Other, Ops));
5718     return true;
5719   }
5720 
5721   return false;
5722 }
5723 
5724 bool ARMDAGToDAGISel::tryInlineAsm(SDNode *N){
5725   std::vector<SDValue> AsmNodeOperands;
5726   unsigned Flag, Kind;
5727   bool Changed = false;
5728   unsigned NumOps = N->getNumOperands();
5729 
5730   // Normally, i64 data is bounded to two arbitrary GRPs for "%r" constraint.
5731   // However, some instrstions (e.g. ldrexd/strexd in ARM mode) require
5732   // (even/even+1) GPRs and use %n and %Hn to refer to the individual regs
5733   // respectively. Since there is no constraint to explicitly specify a
5734   // reg pair, we use GPRPair reg class for "%r" for 64-bit data. For Thumb,
5735   // the 64-bit data may be referred by H, Q, R modifiers, so we still pack
5736   // them into a GPRPair.
5737 
5738   SDLoc dl(N);
5739   SDValue Glue = N->getGluedNode() ? N->getOperand(NumOps-1)
5740                                    : SDValue(nullptr,0);
5741 
5742   SmallVector<bool, 8> OpChanged;
5743   // Glue node will be appended late.
5744   for(unsigned i = 0, e = N->getGluedNode() ? NumOps - 1 : NumOps; i < e; ++i) {
5745     SDValue op = N->getOperand(i);
5746     AsmNodeOperands.push_back(op);
5747 
5748     if (i < InlineAsm::Op_FirstOperand)
5749       continue;
5750 
5751     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(i))) {
5752       Flag = C->getZExtValue();
5753       Kind = InlineAsm::getKind(Flag);
5754     }
5755     else
5756       continue;
5757 
5758     // Immediate operands to inline asm in the SelectionDAG are modeled with
5759     // two operands. The first is a constant of value InlineAsm::Kind_Imm, and
5760     // the second is a constant with the value of the immediate. If we get here
5761     // and we have a Kind_Imm, skip the next operand, and continue.
5762     if (Kind == InlineAsm::Kind_Imm) {
5763       SDValue op = N->getOperand(++i);
5764       AsmNodeOperands.push_back(op);
5765       continue;
5766     }
5767 
5768     unsigned NumRegs = InlineAsm::getNumOperandRegisters(Flag);
5769     if (NumRegs)
5770       OpChanged.push_back(false);
5771 
5772     unsigned DefIdx = 0;
5773     bool IsTiedToChangedOp = false;
5774     // If it's a use that is tied with a previous def, it has no
5775     // reg class constraint.
5776     if (Changed && InlineAsm::isUseOperandTiedToDef(Flag, DefIdx))
5777       IsTiedToChangedOp = OpChanged[DefIdx];
5778 
5779     // Memory operands to inline asm in the SelectionDAG are modeled with two
5780     // operands: a constant of value InlineAsm::Kind_Mem followed by the input
5781     // operand. If we get here and we have a Kind_Mem, skip the next operand (so
5782     // it doesn't get misinterpreted), and continue. We do this here because
5783     // it's important to update the OpChanged array correctly before moving on.
5784     if (Kind == InlineAsm::Kind_Mem) {
5785       SDValue op = N->getOperand(++i);
5786       AsmNodeOperands.push_back(op);
5787       continue;
5788     }
5789 
5790     if (Kind != InlineAsm::Kind_RegUse && Kind != InlineAsm::Kind_RegDef
5791         && Kind != InlineAsm::Kind_RegDefEarlyClobber)
5792       continue;
5793 
5794     unsigned RC;
5795     bool HasRC = InlineAsm::hasRegClassConstraint(Flag, RC);
5796     if ((!IsTiedToChangedOp && (!HasRC || RC != ARM::GPRRegClassID))
5797         || NumRegs != 2)
5798       continue;
5799 
5800     assert((i+2 < NumOps) && "Invalid number of operands in inline asm");
5801     SDValue V0 = N->getOperand(i+1);
5802     SDValue V1 = N->getOperand(i+2);
5803     unsigned Reg0 = cast<RegisterSDNode>(V0)->getReg();
5804     unsigned Reg1 = cast<RegisterSDNode>(V1)->getReg();
5805     SDValue PairedReg;
5806     MachineRegisterInfo &MRI = MF->getRegInfo();
5807 
5808     if (Kind == InlineAsm::Kind_RegDef ||
5809         Kind == InlineAsm::Kind_RegDefEarlyClobber) {
5810       // Replace the two GPRs with 1 GPRPair and copy values from GPRPair to
5811       // the original GPRs.
5812 
5813       Register GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5814       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
5815       SDValue Chain = SDValue(N,0);
5816 
5817       SDNode *GU = N->getGluedUser();
5818       SDValue RegCopy = CurDAG->getCopyFromReg(Chain, dl, GPVR, MVT::Untyped,
5819                                                Chain.getValue(1));
5820 
5821       // Extract values from a GPRPair reg and copy to the original GPR reg.
5822       SDValue Sub0 = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
5823                                                     RegCopy);
5824       SDValue Sub1 = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
5825                                                     RegCopy);
5826       SDValue T0 = CurDAG->getCopyToReg(Sub0, dl, Reg0, Sub0,
5827                                         RegCopy.getValue(1));
5828       SDValue T1 = CurDAG->getCopyToReg(Sub1, dl, Reg1, Sub1, T0.getValue(1));
5829 
5830       // Update the original glue user.
5831       std::vector<SDValue> Ops(GU->op_begin(), GU->op_end()-1);
5832       Ops.push_back(T1.getValue(1));
5833       CurDAG->UpdateNodeOperands(GU, Ops);
5834     }
5835     else {
5836       // For Kind  == InlineAsm::Kind_RegUse, we first copy two GPRs into a
5837       // GPRPair and then pass the GPRPair to the inline asm.
5838       SDValue Chain = AsmNodeOperands[InlineAsm::Op_InputChain];
5839 
5840       // As REG_SEQ doesn't take RegisterSDNode, we copy them first.
5841       SDValue T0 = CurDAG->getCopyFromReg(Chain, dl, Reg0, MVT::i32,
5842                                           Chain.getValue(1));
5843       SDValue T1 = CurDAG->getCopyFromReg(Chain, dl, Reg1, MVT::i32,
5844                                           T0.getValue(1));
5845       SDValue Pair = SDValue(createGPRPairNode(MVT::Untyped, T0, T1), 0);
5846 
5847       // Copy REG_SEQ into a GPRPair-typed VR and replace the original two
5848       // i32 VRs of inline asm with it.
5849       Register GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5850       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
5851       Chain = CurDAG->getCopyToReg(T1, dl, GPVR, Pair, T1.getValue(1));
5852 
5853       AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
5854       Glue = Chain.getValue(1);
5855     }
5856 
5857     Changed = true;
5858 
5859     if(PairedReg.getNode()) {
5860       OpChanged[OpChanged.size() -1 ] = true;
5861       Flag = InlineAsm::getFlagWord(Kind, 1 /* RegNum*/);
5862       if (IsTiedToChangedOp)
5863         Flag = InlineAsm::getFlagWordForMatchingOp(Flag, DefIdx);
5864       else
5865         Flag = InlineAsm::getFlagWordForRegClass(Flag, ARM::GPRPairRegClassID);
5866       // Replace the current flag.
5867       AsmNodeOperands[AsmNodeOperands.size() -1] = CurDAG->getTargetConstant(
5868           Flag, dl, MVT::i32);
5869       // Add the new register node and skip the original two GPRs.
5870       AsmNodeOperands.push_back(PairedReg);
5871       // Skip the next two GPRs.
5872       i += 2;
5873     }
5874   }
5875 
5876   if (Glue.getNode())
5877     AsmNodeOperands.push_back(Glue);
5878   if (!Changed)
5879     return false;
5880 
5881   SDValue New = CurDAG->getNode(N->getOpcode(), SDLoc(N),
5882       CurDAG->getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
5883   New->setNodeId(-1);
5884   ReplaceNode(N, New.getNode());
5885   return true;
5886 }
5887 
5888 
5889 bool ARMDAGToDAGISel::
5890 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
5891                              std::vector<SDValue> &OutOps) {
5892   switch(ConstraintID) {
5893   default:
5894     llvm_unreachable("Unexpected asm memory constraint");
5895   case InlineAsm::Constraint_m:
5896   case InlineAsm::Constraint_o:
5897   case InlineAsm::Constraint_Q:
5898   case InlineAsm::Constraint_Um:
5899   case InlineAsm::Constraint_Un:
5900   case InlineAsm::Constraint_Uq:
5901   case InlineAsm::Constraint_Us:
5902   case InlineAsm::Constraint_Ut:
5903   case InlineAsm::Constraint_Uv:
5904   case InlineAsm::Constraint_Uy:
5905     // Require the address to be in a register.  That is safe for all ARM
5906     // variants and it is hard to do anything much smarter without knowing
5907     // how the operand is used.
5908     OutOps.push_back(Op);
5909     return false;
5910   }
5911   return true;
5912 }
5913 
5914 /// createARMISelDag - This pass converts a legalized DAG into a
5915 /// ARM-specific DAG, ready for instruction scheduling.
5916 ///
5917 FunctionPass *llvm::createARMISelDag(ARMBaseTargetMachine &TM,
5918                                      CodeGenOpt::Level OptLevel) {
5919   return new ARMDAGToDAGISel(TM, OptLevel);
5920 }
5921