1 //===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the ARM target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARM.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMTargetMachine.h"
17 #include "MCTargetDesc/ARMAddressingModes.h"
18 #include "Utils/ARMBaseInfo.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/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Target/TargetOptions.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "arm-isel"
41 
42 static cl::opt<bool>
43 DisableShifterOp("disable-shifter-op", cl::Hidden,
44   cl::desc("Disable isel of shifter-op"),
45   cl::init(false));
46 
47 //===--------------------------------------------------------------------===//
48 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
49 /// instructions for SelectionDAG operations.
50 ///
51 namespace {
52 
53 class ARMDAGToDAGISel : public SelectionDAGISel {
54   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
55   /// make the right decision when generating code for different targets.
56   const ARMSubtarget *Subtarget;
57 
58 public:
59   explicit ARMDAGToDAGISel(ARMBaseTargetMachine &tm, CodeGenOpt::Level OptLevel)
60       : SelectionDAGISel(tm, OptLevel) {}
61 
62   bool runOnMachineFunction(MachineFunction &MF) override {
63     // Reset the subtarget each time through.
64     Subtarget = &MF.getSubtarget<ARMSubtarget>();
65     SelectionDAGISel::runOnMachineFunction(MF);
66     return true;
67   }
68 
69   StringRef getPassName() const override { return "ARM Instruction Selection"; }
70 
71   void PreprocessISelDAG() override;
72 
73   /// getI32Imm - Return a target constant of type i32 with the specified
74   /// value.
75   inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
76     return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
77   }
78 
79   void Select(SDNode *N) override;
80 
81   bool hasNoVMLxHazardUse(SDNode *N) const;
82   bool isShifterOpProfitable(const SDValue &Shift,
83                              ARM_AM::ShiftOpc ShOpcVal, unsigned ShAmt);
84   bool SelectRegShifterOperand(SDValue N, SDValue &A,
85                                SDValue &B, SDValue &C,
86                                bool CheckProfitability = true);
87   bool SelectImmShifterOperand(SDValue N, SDValue &A,
88                                SDValue &B, bool CheckProfitability = true);
89   bool SelectShiftRegShifterOperand(SDValue N, SDValue &A,
90                                     SDValue &B, SDValue &C) {
91     // Don't apply the profitability check
92     return SelectRegShifterOperand(N, A, B, C, false);
93   }
94   bool SelectShiftImmShifterOperand(SDValue N, SDValue &A,
95                                     SDValue &B) {
96     // Don't apply the profitability check
97     return SelectImmShifterOperand(N, A, B, false);
98   }
99 
100   bool SelectAddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
101   bool SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset, SDValue &Opc);
102 
103   bool SelectCMOVPred(SDValue N, SDValue &Pred, SDValue &Reg) {
104     const ConstantSDNode *CN = cast<ConstantSDNode>(N);
105     Pred = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);
106     Reg = CurDAG->getRegister(ARM::CPSR, MVT::i32);
107     return true;
108   }
109 
110   bool SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
111                              SDValue &Offset, SDValue &Opc);
112   bool SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
113                              SDValue &Offset, SDValue &Opc);
114   bool SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
115                              SDValue &Offset, SDValue &Opc);
116   bool SelectAddrOffsetNone(SDValue N, SDValue &Base);
117   bool SelectAddrMode3(SDValue N, SDValue &Base,
118                        SDValue &Offset, SDValue &Opc);
119   bool SelectAddrMode3Offset(SDNode *Op, SDValue N,
120                              SDValue &Offset, SDValue &Opc);
121   bool IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset,
122                          int Lwb, int Upb, bool FP16);
123   bool SelectAddrMode5(SDValue N, SDValue &Base, SDValue &Offset);
124   bool SelectAddrMode5FP16(SDValue N, SDValue &Base, SDValue &Offset);
125   bool SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,SDValue &Align);
126   bool SelectAddrMode6Offset(SDNode *Op, SDValue N, SDValue &Offset);
127 
128   bool SelectAddrModePC(SDValue N, SDValue &Offset, SDValue &Label);
129 
130   // Thumb Addressing Modes:
131   bool SelectThumbAddrModeRR(SDValue N, SDValue &Base, SDValue &Offset);
132   bool SelectThumbAddrModeImm5S(SDValue N, unsigned Scale, SDValue &Base,
133                                 SDValue &OffImm);
134   bool SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
135                                  SDValue &OffImm);
136   bool SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
137                                  SDValue &OffImm);
138   bool SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
139                                  SDValue &OffImm);
140   bool SelectThumbAddrModeSP(SDValue N, SDValue &Base, SDValue &OffImm);
141 
142   // Thumb 2 Addressing Modes:
143   bool SelectT2AddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
144   bool SelectT2AddrModeImm8(SDValue N, SDValue &Base,
145                             SDValue &OffImm);
146   bool SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
147                                  SDValue &OffImm);
148   bool SelectT2AddrModeSoReg(SDValue N, SDValue &Base,
149                              SDValue &OffReg, SDValue &ShImm);
150   bool SelectT2AddrModeExclusive(SDValue N, SDValue &Base, SDValue &OffImm);
151 
152   inline bool is_so_imm(unsigned Imm) const {
153     return ARM_AM::getSOImmVal(Imm) != -1;
154   }
155 
156   inline bool is_so_imm_not(unsigned Imm) const {
157     return ARM_AM::getSOImmVal(~Imm) != -1;
158   }
159 
160   inline bool is_t2_so_imm(unsigned Imm) const {
161     return ARM_AM::getT2SOImmVal(Imm) != -1;
162   }
163 
164   inline bool is_t2_so_imm_not(unsigned Imm) const {
165     return ARM_AM::getT2SOImmVal(~Imm) != -1;
166   }
167 
168   // Include the pieces autogenerated from the target description.
169 #include "ARMGenDAGISel.inc"
170 
171 private:
172   void transferMemOperands(SDNode *Src, SDNode *Dst);
173 
174   /// Indexed (pre/post inc/dec) load matching code for ARM.
175   bool tryARMIndexedLoad(SDNode *N);
176   bool tryT1IndexedLoad(SDNode *N);
177   bool tryT2IndexedLoad(SDNode *N);
178 
179   /// SelectVLD - Select NEON load intrinsics.  NumVecs should be
180   /// 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
181   /// loads of D registers and even subregs and odd subregs of Q registers.
182   /// For NumVecs <= 2, QOpcodes1 is not used.
183   void SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
184                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
185                  const uint16_t *QOpcodes1);
186 
187   /// SelectVST - Select NEON store intrinsics.  NumVecs should
188   /// be 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
189   /// stores of D registers and even subregs and odd subregs of Q registers.
190   /// For NumVecs <= 2, QOpcodes1 is not used.
191   void SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
192                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
193                  const uint16_t *QOpcodes1);
194 
195   /// SelectVLDSTLane - Select NEON load/store lane intrinsics.  NumVecs should
196   /// be 2, 3 or 4.  The opcode arrays specify the instructions used for
197   /// load/store of D registers and Q registers.
198   void SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
199                        unsigned NumVecs, const uint16_t *DOpcodes,
200                        const uint16_t *QOpcodes);
201 
202   /// SelectVLDDup - Select NEON load-duplicate intrinsics.  NumVecs
203   /// should be 1, 2, 3 or 4.  The opcode array specifies the instructions used
204   /// for loading D registers.  (Q registers are not supported.)
205   void SelectVLDDup(SDNode *N, bool isUpdating, unsigned NumVecs,
206                     const uint16_t *DOpcodes,
207                     const uint16_t *QOpcodes = nullptr);
208 
209   /// Try to select SBFX/UBFX instructions for ARM.
210   bool tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned);
211 
212   // Select special operations if node forms integer ABS pattern
213   bool tryABSOp(SDNode *N);
214 
215   bool tryReadRegister(SDNode *N);
216   bool tryWriteRegister(SDNode *N);
217 
218   bool tryInlineAsm(SDNode *N);
219 
220   void SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI);
221 
222   void SelectCMP_SWAP(SDNode *N);
223 
224   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
225   /// inline asm expressions.
226   bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
227                                     std::vector<SDValue> &OutOps) override;
228 
229   // Form pairs of consecutive R, S, D, or Q registers.
230   SDNode *createGPRPairNode(EVT VT, SDValue V0, SDValue V1);
231   SDNode *createSRegPairNode(EVT VT, SDValue V0, SDValue V1);
232   SDNode *createDRegPairNode(EVT VT, SDValue V0, SDValue V1);
233   SDNode *createQRegPairNode(EVT VT, SDValue V0, SDValue V1);
234 
235   // Form sequences of 4 consecutive S, D, or Q registers.
236   SDNode *createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
237   SDNode *createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
238   SDNode *createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
239 
240   // Get the alignment operand for a NEON VLD or VST instruction.
241   SDValue GetVLDSTAlign(SDValue Align, const SDLoc &dl, unsigned NumVecs,
242                         bool is64BitVector);
243 
244   /// Returns the number of instructions required to materialize the given
245   /// constant in a register, or 3 if a literal pool load is needed.
246   unsigned ConstantMaterializationCost(unsigned Val) const;
247 
248   /// Checks if N is a multiplication by a constant where we can extract out a
249   /// power of two from the constant so that it can be used in a shift, but only
250   /// if it simplifies the materialization of the constant. Returns true if it
251   /// is, and assigns to PowerOfTwo the power of two that should be extracted
252   /// out and to NewMulConst the new constant to be multiplied by.
253   bool canExtractShiftFromMul(const SDValue &N, unsigned MaxShift,
254                               unsigned &PowerOfTwo, SDValue &NewMulConst) const;
255 
256   /// Replace N with M in CurDAG, in a way that also ensures that M gets
257   /// selected when N would have been selected.
258   void replaceDAGValue(const SDValue &N, SDValue M);
259 };
260 }
261 
262 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
263 /// operand. If so Imm will receive the 32-bit value.
264 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
265   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
266     Imm = cast<ConstantSDNode>(N)->getZExtValue();
267     return true;
268   }
269   return false;
270 }
271 
272 // isInt32Immediate - This method tests to see if a constant operand.
273 // If so Imm will receive the 32 bit value.
274 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
275   return isInt32Immediate(N.getNode(), Imm);
276 }
277 
278 // isOpcWithIntImmediate - This method tests to see if the node is a specific
279 // opcode and that it has a immediate integer right operand.
280 // If so Imm will receive the 32 bit value.
281 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
282   return N->getOpcode() == Opc &&
283          isInt32Immediate(N->getOperand(1).getNode(), Imm);
284 }
285 
286 /// \brief Check whether a particular node is a constant value representable as
287 /// (N * Scale) where (N in [\p RangeMin, \p RangeMax).
288 ///
289 /// \param ScaledConstant [out] - On success, the pre-scaled constant value.
290 static bool isScaledConstantInRange(SDValue Node, int Scale,
291                                     int RangeMin, int RangeMax,
292                                     int &ScaledConstant) {
293   assert(Scale > 0 && "Invalid scale!");
294 
295   // Check that this is a constant.
296   const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Node);
297   if (!C)
298     return false;
299 
300   ScaledConstant = (int) C->getZExtValue();
301   if ((ScaledConstant % Scale) != 0)
302     return false;
303 
304   ScaledConstant /= Scale;
305   return ScaledConstant >= RangeMin && ScaledConstant < RangeMax;
306 }
307 
308 void ARMDAGToDAGISel::PreprocessISelDAG() {
309   if (!Subtarget->hasV6T2Ops())
310     return;
311 
312   bool isThumb2 = Subtarget->isThumb();
313   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
314        E = CurDAG->allnodes_end(); I != E; ) {
315     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
316 
317     if (N->getOpcode() != ISD::ADD)
318       continue;
319 
320     // Look for (add X1, (and (srl X2, c1), c2)) where c2 is constant with
321     // leading zeros, followed by consecutive set bits, followed by 1 or 2
322     // trailing zeros, e.g. 1020.
323     // Transform the expression to
324     // (add X1, (shl (and (srl X2, c1), (c2>>tz)), tz)) where tz is the number
325     // of trailing zeros of c2. The left shift would be folded as an shifter
326     // operand of 'add' and the 'and' and 'srl' would become a bits extraction
327     // node (UBFX).
328 
329     SDValue N0 = N->getOperand(0);
330     SDValue N1 = N->getOperand(1);
331     unsigned And_imm = 0;
332     if (!isOpcWithIntImmediate(N1.getNode(), ISD::AND, And_imm)) {
333       if (isOpcWithIntImmediate(N0.getNode(), ISD::AND, And_imm))
334         std::swap(N0, N1);
335     }
336     if (!And_imm)
337       continue;
338 
339     // Check if the AND mask is an immediate of the form: 000.....1111111100
340     unsigned TZ = countTrailingZeros(And_imm);
341     if (TZ != 1 && TZ != 2)
342       // Be conservative here. Shifter operands aren't always free. e.g. On
343       // Swift, left shifter operand of 1 / 2 for free but others are not.
344       // e.g.
345       //  ubfx   r3, r1, #16, #8
346       //  ldr.w  r3, [r0, r3, lsl #2]
347       // vs.
348       //  mov.w  r9, #1020
349       //  and.w  r2, r9, r1, lsr #14
350       //  ldr    r2, [r0, r2]
351       continue;
352     And_imm >>= TZ;
353     if (And_imm & (And_imm + 1))
354       continue;
355 
356     // Look for (and (srl X, c1), c2).
357     SDValue Srl = N1.getOperand(0);
358     unsigned Srl_imm = 0;
359     if (!isOpcWithIntImmediate(Srl.getNode(), ISD::SRL, Srl_imm) ||
360         (Srl_imm <= 2))
361       continue;
362 
363     // Make sure first operand is not a shifter operand which would prevent
364     // folding of the left shift.
365     SDValue CPTmp0;
366     SDValue CPTmp1;
367     SDValue CPTmp2;
368     if (isThumb2) {
369       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1))
370         continue;
371     } else {
372       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1) ||
373           SelectRegShifterOperand(N0, CPTmp0, CPTmp1, CPTmp2))
374         continue;
375     }
376 
377     // Now make the transformation.
378     Srl = CurDAG->getNode(ISD::SRL, SDLoc(Srl), MVT::i32,
379                           Srl.getOperand(0),
380                           CurDAG->getConstant(Srl_imm + TZ, SDLoc(Srl),
381                                               MVT::i32));
382     N1 = CurDAG->getNode(ISD::AND, SDLoc(N1), MVT::i32,
383                          Srl,
384                          CurDAG->getConstant(And_imm, SDLoc(Srl), MVT::i32));
385     N1 = CurDAG->getNode(ISD::SHL, SDLoc(N1), MVT::i32,
386                          N1, CurDAG->getConstant(TZ, SDLoc(Srl), MVT::i32));
387     CurDAG->UpdateNodeOperands(N, N0, N1);
388   }
389 }
390 
391 /// hasNoVMLxHazardUse - Return true if it's desirable to select a FP MLA / MLS
392 /// node. VFP / NEON fp VMLA / VMLS instructions have special RAW hazards (at
393 /// least on current ARM implementations) which should be avoidded.
394 bool ARMDAGToDAGISel::hasNoVMLxHazardUse(SDNode *N) const {
395   if (OptLevel == CodeGenOpt::None)
396     return true;
397 
398   if (!Subtarget->hasVMLxHazards())
399     return true;
400 
401   if (!N->hasOneUse())
402     return false;
403 
404   SDNode *Use = *N->use_begin();
405   if (Use->getOpcode() == ISD::CopyToReg)
406     return true;
407   if (Use->isMachineOpcode()) {
408     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
409         CurDAG->getSubtarget().getInstrInfo());
410 
411     const MCInstrDesc &MCID = TII->get(Use->getMachineOpcode());
412     if (MCID.mayStore())
413       return true;
414     unsigned Opcode = MCID.getOpcode();
415     if (Opcode == ARM::VMOVRS || Opcode == ARM::VMOVRRD)
416       return true;
417     // vmlx feeding into another vmlx. We actually want to unfold
418     // the use later in the MLxExpansion pass. e.g.
419     // vmla
420     // vmla (stall 8 cycles)
421     //
422     // vmul (5 cycles)
423     // vadd (5 cycles)
424     // vmla
425     // This adds up to about 18 - 19 cycles.
426     //
427     // vmla
428     // vmul (stall 4 cycles)
429     // vadd adds up to about 14 cycles.
430     return TII->isFpMLxInstruction(Opcode);
431   }
432 
433   return false;
434 }
435 
436 bool ARMDAGToDAGISel::isShifterOpProfitable(const SDValue &Shift,
437                                             ARM_AM::ShiftOpc ShOpcVal,
438                                             unsigned ShAmt) {
439   if (!Subtarget->isLikeA9() && !Subtarget->isSwift())
440     return true;
441   if (Shift.hasOneUse())
442     return true;
443   // R << 2 is free.
444   return ShOpcVal == ARM_AM::lsl &&
445          (ShAmt == 2 || (Subtarget->isSwift() && ShAmt == 1));
446 }
447 
448 unsigned ARMDAGToDAGISel::ConstantMaterializationCost(unsigned Val) const {
449   if (Subtarget->isThumb()) {
450     if (Val <= 255) return 1;                               // MOV
451     if (Subtarget->hasV6T2Ops() &&
452         (Val <= 0xffff || ARM_AM::getT2SOImmValSplatVal(Val) != -1))
453       return 1; // MOVW
454     if (Val <= 510) return 2;                               // MOV + ADDi8
455     if (~Val <= 255) return 2;                              // MOV + MVN
456     if (ARM_AM::isThumbImmShiftedVal(Val)) return 2;        // MOV + LSL
457   } else {
458     if (ARM_AM::getSOImmVal(Val) != -1) return 1;           // MOV
459     if (ARM_AM::getSOImmVal(~Val) != -1) return 1;          // MVN
460     if (Subtarget->hasV6T2Ops() && Val <= 0xffff) return 1; // MOVW
461     if (ARM_AM::isSOImmTwoPartVal(Val)) return 2;           // two instrs
462   }
463   if (Subtarget->useMovt(*MF)) return 2; // MOVW + MOVT
464   return 3; // Literal pool load
465 }
466 
467 bool ARMDAGToDAGISel::canExtractShiftFromMul(const SDValue &N,
468                                              unsigned MaxShift,
469                                              unsigned &PowerOfTwo,
470                                              SDValue &NewMulConst) const {
471   assert(N.getOpcode() == ISD::MUL);
472   assert(MaxShift > 0);
473 
474   // If the multiply is used in more than one place then changing the constant
475   // will make other uses incorrect, so don't.
476   if (!N.hasOneUse()) return false;
477   // Check if the multiply is by a constant
478   ConstantSDNode *MulConst = dyn_cast<ConstantSDNode>(N.getOperand(1));
479   if (!MulConst) return false;
480   // If the constant is used in more than one place then modifying it will mean
481   // we need to materialize two constants instead of one, which is a bad idea.
482   if (!MulConst->hasOneUse()) return false;
483   unsigned MulConstVal = MulConst->getZExtValue();
484   if (MulConstVal == 0) return false;
485 
486   // Find the largest power of 2 that MulConstVal is a multiple of
487   PowerOfTwo = MaxShift;
488   while ((MulConstVal % (1 << PowerOfTwo)) != 0) {
489     --PowerOfTwo;
490     if (PowerOfTwo == 0) return false;
491   }
492 
493   // Only optimise if the new cost is better
494   unsigned NewMulConstVal = MulConstVal / (1 << PowerOfTwo);
495   NewMulConst = CurDAG->getConstant(NewMulConstVal, SDLoc(N), MVT::i32);
496   unsigned OldCost = ConstantMaterializationCost(MulConstVal);
497   unsigned NewCost = ConstantMaterializationCost(NewMulConstVal);
498   return NewCost < OldCost;
499 }
500 
501 void ARMDAGToDAGISel::replaceDAGValue(const SDValue &N, SDValue M) {
502   CurDAG->RepositionNode(N.getNode()->getIterator(), M.getNode());
503   CurDAG->ReplaceAllUsesWith(N, M);
504 }
505 
506 bool ARMDAGToDAGISel::SelectImmShifterOperand(SDValue N,
507                                               SDValue &BaseReg,
508                                               SDValue &Opc,
509                                               bool CheckProfitability) {
510   if (DisableShifterOp)
511     return false;
512 
513   // If N is a multiply-by-constant and it's profitable to extract a shift and
514   // use it in a shifted operand do so.
515   if (N.getOpcode() == ISD::MUL) {
516     unsigned PowerOfTwo = 0;
517     SDValue NewMulConst;
518     if (canExtractShiftFromMul(N, 31, PowerOfTwo, NewMulConst)) {
519       HandleSDNode Handle(N);
520       SDLoc Loc(N);
521       replaceDAGValue(N.getOperand(1), NewMulConst);
522       BaseReg = Handle.getValue();
523       Opc = CurDAG->getTargetConstant(
524           ARM_AM::getSORegOpc(ARM_AM::lsl, PowerOfTwo), Loc, MVT::i32);
525       return true;
526     }
527   }
528 
529   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
530 
531   // Don't match base register only case. That is matched to a separate
532   // lower complexity pattern with explicit register operand.
533   if (ShOpcVal == ARM_AM::no_shift) return false;
534 
535   BaseReg = N.getOperand(0);
536   unsigned ShImmVal = 0;
537   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
538   if (!RHS) return false;
539   ShImmVal = RHS->getZExtValue() & 31;
540   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
541                                   SDLoc(N), MVT::i32);
542   return true;
543 }
544 
545 bool ARMDAGToDAGISel::SelectRegShifterOperand(SDValue N,
546                                               SDValue &BaseReg,
547                                               SDValue &ShReg,
548                                               SDValue &Opc,
549                                               bool CheckProfitability) {
550   if (DisableShifterOp)
551     return false;
552 
553   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
554 
555   // Don't match base register only case. That is matched to a separate
556   // lower complexity pattern with explicit register operand.
557   if (ShOpcVal == ARM_AM::no_shift) return false;
558 
559   BaseReg = N.getOperand(0);
560   unsigned ShImmVal = 0;
561   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
562   if (RHS) return false;
563 
564   ShReg = N.getOperand(1);
565   if (CheckProfitability && !isShifterOpProfitable(N, ShOpcVal, ShImmVal))
566     return false;
567   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
568                                   SDLoc(N), MVT::i32);
569   return true;
570 }
571 
572 
573 bool ARMDAGToDAGISel::SelectAddrModeImm12(SDValue N,
574                                           SDValue &Base,
575                                           SDValue &OffImm) {
576   // Match simple R + imm12 operands.
577 
578   // Base only.
579   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
580       !CurDAG->isBaseWithConstantOffset(N)) {
581     if (N.getOpcode() == ISD::FrameIndex) {
582       // Match frame index.
583       int FI = cast<FrameIndexSDNode>(N)->getIndex();
584       Base = CurDAG->getTargetFrameIndex(
585           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
586       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
587       return true;
588     }
589 
590     if (N.getOpcode() == ARMISD::Wrapper &&
591         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
592         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
593         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
594       Base = N.getOperand(0);
595     } else
596       Base = N;
597     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
598     return true;
599   }
600 
601   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
602     int RHSC = (int)RHS->getSExtValue();
603     if (N.getOpcode() == ISD::SUB)
604       RHSC = -RHSC;
605 
606     if (RHSC > -0x1000 && RHSC < 0x1000) { // 12 bits
607       Base   = N.getOperand(0);
608       if (Base.getOpcode() == ISD::FrameIndex) {
609         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
610         Base = CurDAG->getTargetFrameIndex(
611             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
612       }
613       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
614       return true;
615     }
616   }
617 
618   // Base only.
619   Base = N;
620   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
621   return true;
622 }
623 
624 
625 
626 bool ARMDAGToDAGISel::SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset,
627                                       SDValue &Opc) {
628   if (N.getOpcode() == ISD::MUL &&
629       ((!Subtarget->isLikeA9() && !Subtarget->isSwift()) || N.hasOneUse())) {
630     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
631       // X * [3,5,9] -> X + X * [2,4,8] etc.
632       int RHSC = (int)RHS->getZExtValue();
633       if (RHSC & 1) {
634         RHSC = RHSC & ~1;
635         ARM_AM::AddrOpc AddSub = ARM_AM::add;
636         if (RHSC < 0) {
637           AddSub = ARM_AM::sub;
638           RHSC = - RHSC;
639         }
640         if (isPowerOf2_32(RHSC)) {
641           unsigned ShAmt = Log2_32(RHSC);
642           Base = Offset = N.getOperand(0);
643           Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt,
644                                                             ARM_AM::lsl),
645                                           SDLoc(N), MVT::i32);
646           return true;
647         }
648       }
649     }
650   }
651 
652   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
653       // ISD::OR that is equivalent to an ISD::ADD.
654       !CurDAG->isBaseWithConstantOffset(N))
655     return false;
656 
657   // Leave simple R +/- imm12 operands for LDRi12
658   if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
659     int RHSC;
660     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
661                                 -0x1000+1, 0x1000, RHSC)) // 12 bits.
662       return false;
663   }
664 
665   // Otherwise this is R +/- [possibly shifted] R.
666   ARM_AM::AddrOpc AddSub = N.getOpcode() == ISD::SUB ? ARM_AM::sub:ARM_AM::add;
667   ARM_AM::ShiftOpc ShOpcVal =
668     ARM_AM::getShiftOpcForNode(N.getOperand(1).getOpcode());
669   unsigned ShAmt = 0;
670 
671   Base   = N.getOperand(0);
672   Offset = N.getOperand(1);
673 
674   if (ShOpcVal != ARM_AM::no_shift) {
675     // Check to see if the RHS of the shift is a constant, if not, we can't fold
676     // it.
677     if (ConstantSDNode *Sh =
678            dyn_cast<ConstantSDNode>(N.getOperand(1).getOperand(1))) {
679       ShAmt = Sh->getZExtValue();
680       if (isShifterOpProfitable(Offset, ShOpcVal, ShAmt))
681         Offset = N.getOperand(1).getOperand(0);
682       else {
683         ShAmt = 0;
684         ShOpcVal = ARM_AM::no_shift;
685       }
686     } else {
687       ShOpcVal = ARM_AM::no_shift;
688     }
689   }
690 
691   // Try matching (R shl C) + (R).
692   if (N.getOpcode() != ISD::SUB && ShOpcVal == ARM_AM::no_shift &&
693       !(Subtarget->isLikeA9() || Subtarget->isSwift() ||
694         N.getOperand(0).hasOneUse())) {
695     ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOperand(0).getOpcode());
696     if (ShOpcVal != ARM_AM::no_shift) {
697       // Check to see if the RHS of the shift is a constant, if not, we can't
698       // fold it.
699       if (ConstantSDNode *Sh =
700           dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
701         ShAmt = Sh->getZExtValue();
702         if (isShifterOpProfitable(N.getOperand(0), ShOpcVal, ShAmt)) {
703           Offset = N.getOperand(0).getOperand(0);
704           Base = N.getOperand(1);
705         } else {
706           ShAmt = 0;
707           ShOpcVal = ARM_AM::no_shift;
708         }
709       } else {
710         ShOpcVal = ARM_AM::no_shift;
711       }
712     }
713   }
714 
715   // If Offset is a multiply-by-constant and it's profitable to extract a shift
716   // and use it in a shifted operand do so.
717   if (Offset.getOpcode() == ISD::MUL && N.hasOneUse()) {
718     unsigned PowerOfTwo = 0;
719     SDValue NewMulConst;
720     if (canExtractShiftFromMul(Offset, 31, PowerOfTwo, NewMulConst)) {
721       HandleSDNode Handle(Offset);
722       replaceDAGValue(Offset.getOperand(1), NewMulConst);
723       Offset = Handle.getValue();
724       ShAmt = PowerOfTwo;
725       ShOpcVal = ARM_AM::lsl;
726     }
727   }
728 
729   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
730                                   SDLoc(N), MVT::i32);
731   return true;
732 }
733 
734 bool ARMDAGToDAGISel::SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
735                                             SDValue &Offset, SDValue &Opc) {
736   unsigned Opcode = Op->getOpcode();
737   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
738     ? cast<LoadSDNode>(Op)->getAddressingMode()
739     : cast<StoreSDNode>(Op)->getAddressingMode();
740   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
741     ? ARM_AM::add : ARM_AM::sub;
742   int Val;
743   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val))
744     return false;
745 
746   Offset = N;
747   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
748   unsigned ShAmt = 0;
749   if (ShOpcVal != ARM_AM::no_shift) {
750     // Check to see if the RHS of the shift is a constant, if not, we can't fold
751     // it.
752     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
753       ShAmt = Sh->getZExtValue();
754       if (isShifterOpProfitable(N, ShOpcVal, ShAmt))
755         Offset = N.getOperand(0);
756       else {
757         ShAmt = 0;
758         ShOpcVal = ARM_AM::no_shift;
759       }
760     } else {
761       ShOpcVal = ARM_AM::no_shift;
762     }
763   }
764 
765   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
766                                   SDLoc(N), MVT::i32);
767   return true;
768 }
769 
770 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
771                                             SDValue &Offset, SDValue &Opc) {
772   unsigned Opcode = Op->getOpcode();
773   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
774     ? cast<LoadSDNode>(Op)->getAddressingMode()
775     : cast<StoreSDNode>(Op)->getAddressingMode();
776   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
777     ? ARM_AM::add : ARM_AM::sub;
778   int Val;
779   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
780     if (AddSub == ARM_AM::sub) Val *= -1;
781     Offset = CurDAG->getRegister(0, MVT::i32);
782     Opc = CurDAG->getTargetConstant(Val, SDLoc(Op), MVT::i32);
783     return true;
784   }
785 
786   return false;
787 }
788 
789 
790 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
791                                             SDValue &Offset, SDValue &Opc) {
792   unsigned Opcode = Op->getOpcode();
793   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
794     ? cast<LoadSDNode>(Op)->getAddressingMode()
795     : cast<StoreSDNode>(Op)->getAddressingMode();
796   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
797     ? ARM_AM::add : ARM_AM::sub;
798   int Val;
799   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
800     Offset = CurDAG->getRegister(0, MVT::i32);
801     Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, Val,
802                                                       ARM_AM::no_shift),
803                                     SDLoc(Op), MVT::i32);
804     return true;
805   }
806 
807   return false;
808 }
809 
810 bool ARMDAGToDAGISel::SelectAddrOffsetNone(SDValue N, SDValue &Base) {
811   Base = N;
812   return true;
813 }
814 
815 bool ARMDAGToDAGISel::SelectAddrMode3(SDValue N,
816                                       SDValue &Base, SDValue &Offset,
817                                       SDValue &Opc) {
818   if (N.getOpcode() == ISD::SUB) {
819     // X - C  is canonicalize to X + -C, no need to handle it here.
820     Base = N.getOperand(0);
821     Offset = N.getOperand(1);
822     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::sub, 0), SDLoc(N),
823                                     MVT::i32);
824     return true;
825   }
826 
827   if (!CurDAG->isBaseWithConstantOffset(N)) {
828     Base = N;
829     if (N.getOpcode() == ISD::FrameIndex) {
830       int FI = cast<FrameIndexSDNode>(N)->getIndex();
831       Base = CurDAG->getTargetFrameIndex(
832           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
833     }
834     Offset = CurDAG->getRegister(0, MVT::i32);
835     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
836                                     MVT::i32);
837     return true;
838   }
839 
840   // If the RHS is +/- imm8, fold into addr mode.
841   int RHSC;
842   if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
843                               -256 + 1, 256, RHSC)) { // 8 bits.
844     Base = N.getOperand(0);
845     if (Base.getOpcode() == ISD::FrameIndex) {
846       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
847       Base = CurDAG->getTargetFrameIndex(
848           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
849     }
850     Offset = CurDAG->getRegister(0, MVT::i32);
851 
852     ARM_AM::AddrOpc AddSub = ARM_AM::add;
853     if (RHSC < 0) {
854       AddSub = ARM_AM::sub;
855       RHSC = -RHSC;
856     }
857     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, RHSC), SDLoc(N),
858                                     MVT::i32);
859     return true;
860   }
861 
862   Base = N.getOperand(0);
863   Offset = N.getOperand(1);
864   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
865                                   MVT::i32);
866   return true;
867 }
868 
869 bool ARMDAGToDAGISel::SelectAddrMode3Offset(SDNode *Op, SDValue N,
870                                             SDValue &Offset, SDValue &Opc) {
871   unsigned Opcode = Op->getOpcode();
872   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
873     ? cast<LoadSDNode>(Op)->getAddressingMode()
874     : cast<StoreSDNode>(Op)->getAddressingMode();
875   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
876     ? ARM_AM::add : ARM_AM::sub;
877   int Val;
878   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 256, Val)) { // 12 bits.
879     Offset = CurDAG->getRegister(0, MVT::i32);
880     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, Val), SDLoc(Op),
881                                     MVT::i32);
882     return true;
883   }
884 
885   Offset = N;
886   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, 0), SDLoc(Op),
887                                   MVT::i32);
888   return true;
889 }
890 
891 bool ARMDAGToDAGISel::IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset,
892                                         int Lwb, int Upb, bool FP16) {
893   if (!CurDAG->isBaseWithConstantOffset(N)) {
894     Base = N;
895     if (N.getOpcode() == ISD::FrameIndex) {
896       int FI = cast<FrameIndexSDNode>(N)->getIndex();
897       Base = CurDAG->getTargetFrameIndex(
898           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
899     } else if (N.getOpcode() == ARMISD::Wrapper &&
900                N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
901                N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
902                N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
903       Base = N.getOperand(0);
904     }
905     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
906                                        SDLoc(N), MVT::i32);
907     return true;
908   }
909 
910   // If the RHS is +/- imm8, fold into addr mode.
911   int RHSC;
912   const int Scale = FP16 ? 2 : 4;
913 
914   if (isScaledConstantInRange(N.getOperand(1), Scale, Lwb, Upb, RHSC)) {
915     Base = N.getOperand(0);
916     if (Base.getOpcode() == ISD::FrameIndex) {
917       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
918       Base = CurDAG->getTargetFrameIndex(
919           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
920     }
921 
922     ARM_AM::AddrOpc AddSub = ARM_AM::add;
923     if (RHSC < 0) {
924       AddSub = ARM_AM::sub;
925       RHSC = -RHSC;
926     }
927 
928     if (FP16)
929       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(AddSub, RHSC),
930                                          SDLoc(N), MVT::i32);
931     else
932       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(AddSub, RHSC),
933                                          SDLoc(N), MVT::i32);
934 
935     return true;
936   }
937 
938   Base = N;
939 
940   if (FP16)
941     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(ARM_AM::add, 0),
942                                        SDLoc(N), MVT::i32);
943   else
944     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
945                                        SDLoc(N), MVT::i32);
946 
947   return true;
948 }
949 
950 bool ARMDAGToDAGISel::SelectAddrMode5(SDValue N,
951                                       SDValue &Base, SDValue &Offset) {
952   int Lwb = -256 + 1;
953   int Upb = 256;
954   return IsAddressingMode5(N, Base, Offset, Lwb, Upb, /*FP16=*/ false);
955 }
956 
957 bool ARMDAGToDAGISel::SelectAddrMode5FP16(SDValue N,
958                                           SDValue &Base, SDValue &Offset) {
959   int Lwb = -512 + 1;
960   int Upb = 512;
961   return IsAddressingMode5(N, Base, Offset, Lwb, Upb, /*FP16=*/ true);
962 }
963 
964 bool ARMDAGToDAGISel::SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,
965                                       SDValue &Align) {
966   Addr = N;
967 
968   unsigned Alignment = 0;
969 
970   MemSDNode *MemN = cast<MemSDNode>(Parent);
971 
972   if (isa<LSBaseSDNode>(MemN) ||
973       ((MemN->getOpcode() == ARMISD::VST1_UPD ||
974         MemN->getOpcode() == ARMISD::VLD1_UPD) &&
975        MemN->getConstantOperandVal(MemN->getNumOperands() - 1) == 1)) {
976     // This case occurs only for VLD1-lane/dup and VST1-lane instructions.
977     // The maximum alignment is equal to the memory size being referenced.
978     unsigned MMOAlign = MemN->getAlignment();
979     unsigned MemSize = MemN->getMemoryVT().getSizeInBits() / 8;
980     if (MMOAlign >= MemSize && MemSize > 1)
981       Alignment = MemSize;
982   } else {
983     // All other uses of addrmode6 are for intrinsics.  For now just record
984     // the raw alignment value; it will be refined later based on the legal
985     // alignment operands for the intrinsic.
986     Alignment = MemN->getAlignment();
987   }
988 
989   Align = CurDAG->getTargetConstant(Alignment, SDLoc(N), MVT::i32);
990   return true;
991 }
992 
993 bool ARMDAGToDAGISel::SelectAddrMode6Offset(SDNode *Op, SDValue N,
994                                             SDValue &Offset) {
995   LSBaseSDNode *LdSt = cast<LSBaseSDNode>(Op);
996   ISD::MemIndexedMode AM = LdSt->getAddressingMode();
997   if (AM != ISD::POST_INC)
998     return false;
999   Offset = N;
1000   if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N)) {
1001     if (NC->getZExtValue() * 8 == LdSt->getMemoryVT().getSizeInBits())
1002       Offset = CurDAG->getRegister(0, MVT::i32);
1003   }
1004   return true;
1005 }
1006 
1007 bool ARMDAGToDAGISel::SelectAddrModePC(SDValue N,
1008                                        SDValue &Offset, SDValue &Label) {
1009   if (N.getOpcode() == ARMISD::PIC_ADD && N.hasOneUse()) {
1010     Offset = N.getOperand(0);
1011     SDValue N1 = N.getOperand(1);
1012     Label = CurDAG->getTargetConstant(cast<ConstantSDNode>(N1)->getZExtValue(),
1013                                       SDLoc(N), MVT::i32);
1014     return true;
1015   }
1016 
1017   return false;
1018 }
1019 
1020 
1021 //===----------------------------------------------------------------------===//
1022 //                         Thumb Addressing Modes
1023 //===----------------------------------------------------------------------===//
1024 
1025 bool ARMDAGToDAGISel::SelectThumbAddrModeRR(SDValue N,
1026                                             SDValue &Base, SDValue &Offset){
1027   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N)) {
1028     ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N);
1029     if (!NC || !NC->isNullValue())
1030       return false;
1031 
1032     Base = Offset = N;
1033     return true;
1034   }
1035 
1036   Base = N.getOperand(0);
1037   Offset = N.getOperand(1);
1038   return true;
1039 }
1040 
1041 bool
1042 ARMDAGToDAGISel::SelectThumbAddrModeImm5S(SDValue N, unsigned Scale,
1043                                           SDValue &Base, SDValue &OffImm) {
1044   if (!CurDAG->isBaseWithConstantOffset(N)) {
1045     if (N.getOpcode() == ISD::ADD) {
1046       return false; // We want to select register offset instead
1047     } else if (N.getOpcode() == ARMISD::Wrapper &&
1048         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1049         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1050         N.getOperand(0).getOpcode() != ISD::TargetConstantPool &&
1051         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1052       Base = N.getOperand(0);
1053     } else {
1054       Base = N;
1055     }
1056 
1057     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1058     return true;
1059   }
1060 
1061   // If the RHS is + imm5 * scale, fold into addr mode.
1062   int RHSC;
1063   if (isScaledConstantInRange(N.getOperand(1), Scale, 0, 32, RHSC)) {
1064     Base = N.getOperand(0);
1065     OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1066     return true;
1067   }
1068 
1069   // Offset is too large, so use register offset instead.
1070   return false;
1071 }
1072 
1073 bool
1074 ARMDAGToDAGISel::SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
1075                                            SDValue &OffImm) {
1076   return SelectThumbAddrModeImm5S(N, 4, Base, OffImm);
1077 }
1078 
1079 bool
1080 ARMDAGToDAGISel::SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
1081                                            SDValue &OffImm) {
1082   return SelectThumbAddrModeImm5S(N, 2, Base, OffImm);
1083 }
1084 
1085 bool
1086 ARMDAGToDAGISel::SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
1087                                            SDValue &OffImm) {
1088   return SelectThumbAddrModeImm5S(N, 1, Base, OffImm);
1089 }
1090 
1091 bool ARMDAGToDAGISel::SelectThumbAddrModeSP(SDValue N,
1092                                             SDValue &Base, SDValue &OffImm) {
1093   if (N.getOpcode() == ISD::FrameIndex) {
1094     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1095     // Only multiples of 4 are allowed for the offset, so the frame object
1096     // alignment must be at least 4.
1097     MachineFrameInfo &MFI = MF->getFrameInfo();
1098     if (MFI.getObjectAlignment(FI) < 4)
1099       MFI.setObjectAlignment(FI, 4);
1100     Base = CurDAG->getTargetFrameIndex(
1101         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1102     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1103     return true;
1104   }
1105 
1106   if (!CurDAG->isBaseWithConstantOffset(N))
1107     return false;
1108 
1109   RegisterSDNode *LHSR = dyn_cast<RegisterSDNode>(N.getOperand(0));
1110   if (N.getOperand(0).getOpcode() == ISD::FrameIndex ||
1111       (LHSR && LHSR->getReg() == ARM::SP)) {
1112     // If the RHS is + imm8 * scale, fold into addr mode.
1113     int RHSC;
1114     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/4, 0, 256, RHSC)) {
1115       Base = N.getOperand(0);
1116       if (Base.getOpcode() == ISD::FrameIndex) {
1117         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1118         // For LHS+RHS to result in an offset that's a multiple of 4 the object
1119         // indexed by the LHS must be 4-byte aligned.
1120         MachineFrameInfo &MFI = MF->getFrameInfo();
1121         if (MFI.getObjectAlignment(FI) < 4)
1122           MFI.setObjectAlignment(FI, 4);
1123         Base = CurDAG->getTargetFrameIndex(
1124             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1125       }
1126       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1127       return true;
1128     }
1129   }
1130 
1131   return false;
1132 }
1133 
1134 
1135 //===----------------------------------------------------------------------===//
1136 //                        Thumb 2 Addressing Modes
1137 //===----------------------------------------------------------------------===//
1138 
1139 
1140 bool ARMDAGToDAGISel::SelectT2AddrModeImm12(SDValue N,
1141                                             SDValue &Base, SDValue &OffImm) {
1142   // Match simple R + imm12 operands.
1143 
1144   // Base only.
1145   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1146       !CurDAG->isBaseWithConstantOffset(N)) {
1147     if (N.getOpcode() == ISD::FrameIndex) {
1148       // Match frame index.
1149       int FI = cast<FrameIndexSDNode>(N)->getIndex();
1150       Base = CurDAG->getTargetFrameIndex(
1151           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1152       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1153       return true;
1154     }
1155 
1156     if (N.getOpcode() == ARMISD::Wrapper &&
1157         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1158         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1159         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1160       Base = N.getOperand(0);
1161       if (Base.getOpcode() == ISD::TargetConstantPool)
1162         return false;  // We want to select t2LDRpci instead.
1163     } else
1164       Base = N;
1165     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1166     return true;
1167   }
1168 
1169   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1170     if (SelectT2AddrModeImm8(N, Base, OffImm))
1171       // Let t2LDRi8 handle (R - imm8).
1172       return false;
1173 
1174     int RHSC = (int)RHS->getZExtValue();
1175     if (N.getOpcode() == ISD::SUB)
1176       RHSC = -RHSC;
1177 
1178     if (RHSC >= 0 && RHSC < 0x1000) { // 12 bits (unsigned)
1179       Base   = N.getOperand(0);
1180       if (Base.getOpcode() == ISD::FrameIndex) {
1181         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1182         Base = CurDAG->getTargetFrameIndex(
1183             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1184       }
1185       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1186       return true;
1187     }
1188   }
1189 
1190   // Base only.
1191   Base = N;
1192   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1193   return true;
1194 }
1195 
1196 bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N,
1197                                            SDValue &Base, SDValue &OffImm) {
1198   // Match simple R - imm8 operands.
1199   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1200       !CurDAG->isBaseWithConstantOffset(N))
1201     return false;
1202 
1203   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1204     int RHSC = (int)RHS->getSExtValue();
1205     if (N.getOpcode() == ISD::SUB)
1206       RHSC = -RHSC;
1207 
1208     if ((RHSC >= -255) && (RHSC < 0)) { // 8 bits (always negative)
1209       Base = N.getOperand(0);
1210       if (Base.getOpcode() == ISD::FrameIndex) {
1211         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1212         Base = CurDAG->getTargetFrameIndex(
1213             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1214       }
1215       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1216       return true;
1217     }
1218   }
1219 
1220   return false;
1221 }
1222 
1223 bool ARMDAGToDAGISel::SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
1224                                                  SDValue &OffImm){
1225   unsigned Opcode = Op->getOpcode();
1226   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
1227     ? cast<LoadSDNode>(Op)->getAddressingMode()
1228     : cast<StoreSDNode>(Op)->getAddressingMode();
1229   int RHSC;
1230   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x100, RHSC)) { // 8 bits.
1231     OffImm = ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
1232       ? CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32)
1233       : CurDAG->getTargetConstant(-RHSC, SDLoc(N), MVT::i32);
1234     return true;
1235   }
1236 
1237   return false;
1238 }
1239 
1240 bool ARMDAGToDAGISel::SelectT2AddrModeSoReg(SDValue N,
1241                                             SDValue &Base,
1242                                             SDValue &OffReg, SDValue &ShImm) {
1243   // (R - imm8) should be handled by t2LDRi8. The rest are handled by t2LDRi12.
1244   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N))
1245     return false;
1246 
1247   // Leave (R + imm12) for t2LDRi12, (R - imm8) for t2LDRi8.
1248   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1249     int RHSC = (int)RHS->getZExtValue();
1250     if (RHSC >= 0 && RHSC < 0x1000) // 12 bits (unsigned)
1251       return false;
1252     else if (RHSC < 0 && RHSC >= -255) // 8 bits
1253       return false;
1254   }
1255 
1256   // Look for (R + R) or (R + (R << [1,2,3])).
1257   unsigned ShAmt = 0;
1258   Base   = N.getOperand(0);
1259   OffReg = N.getOperand(1);
1260 
1261   // Swap if it is ((R << c) + R).
1262   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(OffReg.getOpcode());
1263   if (ShOpcVal != ARM_AM::lsl) {
1264     ShOpcVal = ARM_AM::getShiftOpcForNode(Base.getOpcode());
1265     if (ShOpcVal == ARM_AM::lsl)
1266       std::swap(Base, OffReg);
1267   }
1268 
1269   if (ShOpcVal == ARM_AM::lsl) {
1270     // Check to see if the RHS of the shift is a constant, if not, we can't fold
1271     // it.
1272     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(OffReg.getOperand(1))) {
1273       ShAmt = Sh->getZExtValue();
1274       if (ShAmt < 4 && isShifterOpProfitable(OffReg, ShOpcVal, ShAmt))
1275         OffReg = OffReg.getOperand(0);
1276       else {
1277         ShAmt = 0;
1278       }
1279     }
1280   }
1281 
1282   // If OffReg is a multiply-by-constant and it's profitable to extract a shift
1283   // and use it in a shifted operand do so.
1284   if (OffReg.getOpcode() == ISD::MUL && N.hasOneUse()) {
1285     unsigned PowerOfTwo = 0;
1286     SDValue NewMulConst;
1287     if (canExtractShiftFromMul(OffReg, 3, PowerOfTwo, NewMulConst)) {
1288       HandleSDNode Handle(OffReg);
1289       replaceDAGValue(OffReg.getOperand(1), NewMulConst);
1290       OffReg = Handle.getValue();
1291       ShAmt = PowerOfTwo;
1292     }
1293   }
1294 
1295   ShImm = CurDAG->getTargetConstant(ShAmt, SDLoc(N), MVT::i32);
1296 
1297   return true;
1298 }
1299 
1300 bool ARMDAGToDAGISel::SelectT2AddrModeExclusive(SDValue N, SDValue &Base,
1301                                                 SDValue &OffImm) {
1302   // This *must* succeed since it's used for the irreplaceable ldrex and strex
1303   // instructions.
1304   Base = N;
1305   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1306 
1307   if (N.getOpcode() != ISD::ADD || !CurDAG->isBaseWithConstantOffset(N))
1308     return true;
1309 
1310   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
1311   if (!RHS)
1312     return true;
1313 
1314   uint32_t RHSC = (int)RHS->getZExtValue();
1315   if (RHSC > 1020 || RHSC % 4 != 0)
1316     return true;
1317 
1318   Base = N.getOperand(0);
1319   if (Base.getOpcode() == ISD::FrameIndex) {
1320     int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1321     Base = CurDAG->getTargetFrameIndex(
1322         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1323   }
1324 
1325   OffImm = CurDAG->getTargetConstant(RHSC/4, SDLoc(N), MVT::i32);
1326   return true;
1327 }
1328 
1329 //===--------------------------------------------------------------------===//
1330 
1331 /// getAL - Returns a ARMCC::AL immediate node.
1332 static inline SDValue getAL(SelectionDAG *CurDAG, const SDLoc &dl) {
1333   return CurDAG->getTargetConstant((uint64_t)ARMCC::AL, dl, MVT::i32);
1334 }
1335 
1336 void ARMDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
1337   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1338   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
1339   cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
1340 }
1341 
1342 bool ARMDAGToDAGISel::tryARMIndexedLoad(SDNode *N) {
1343   LoadSDNode *LD = cast<LoadSDNode>(N);
1344   ISD::MemIndexedMode AM = LD->getAddressingMode();
1345   if (AM == ISD::UNINDEXED)
1346     return false;
1347 
1348   EVT LoadedVT = LD->getMemoryVT();
1349   SDValue Offset, AMOpc;
1350   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1351   unsigned Opcode = 0;
1352   bool Match = false;
1353   if (LoadedVT == MVT::i32 && isPre &&
1354       SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1355     Opcode = ARM::LDR_PRE_IMM;
1356     Match = true;
1357   } else if (LoadedVT == MVT::i32 && !isPre &&
1358       SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1359     Opcode = ARM::LDR_POST_IMM;
1360     Match = true;
1361   } else if (LoadedVT == MVT::i32 &&
1362       SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1363     Opcode = isPre ? ARM::LDR_PRE_REG : ARM::LDR_POST_REG;
1364     Match = true;
1365 
1366   } else if (LoadedVT == MVT::i16 &&
1367              SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1368     Match = true;
1369     Opcode = (LD->getExtensionType() == ISD::SEXTLOAD)
1370       ? (isPre ? ARM::LDRSH_PRE : ARM::LDRSH_POST)
1371       : (isPre ? ARM::LDRH_PRE : ARM::LDRH_POST);
1372   } else if (LoadedVT == MVT::i8 || LoadedVT == MVT::i1) {
1373     if (LD->getExtensionType() == ISD::SEXTLOAD) {
1374       if (SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1375         Match = true;
1376         Opcode = isPre ? ARM::LDRSB_PRE : ARM::LDRSB_POST;
1377       }
1378     } else {
1379       if (isPre &&
1380           SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1381         Match = true;
1382         Opcode = ARM::LDRB_PRE_IMM;
1383       } else if (!isPre &&
1384                   SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1385         Match = true;
1386         Opcode = ARM::LDRB_POST_IMM;
1387       } else if (SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1388         Match = true;
1389         Opcode = isPre ? ARM::LDRB_PRE_REG : ARM::LDRB_POST_REG;
1390       }
1391     }
1392   }
1393 
1394   if (Match) {
1395     if (Opcode == ARM::LDR_PRE_IMM || Opcode == ARM::LDRB_PRE_IMM) {
1396       SDValue Chain = LD->getChain();
1397       SDValue Base = LD->getBasePtr();
1398       SDValue Ops[]= { Base, AMOpc, getAL(CurDAG, SDLoc(N)),
1399                        CurDAG->getRegister(0, MVT::i32), Chain };
1400       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1401                                            MVT::Other, Ops);
1402       transferMemOperands(N, New);
1403       ReplaceNode(N, New);
1404       return true;
1405     } else {
1406       SDValue Chain = LD->getChain();
1407       SDValue Base = LD->getBasePtr();
1408       SDValue Ops[]= { Base, Offset, AMOpc, getAL(CurDAG, SDLoc(N)),
1409                        CurDAG->getRegister(0, MVT::i32), Chain };
1410       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1411                                            MVT::Other, Ops);
1412       transferMemOperands(N, New);
1413       ReplaceNode(N, New);
1414       return true;
1415     }
1416   }
1417 
1418   return false;
1419 }
1420 
1421 bool ARMDAGToDAGISel::tryT1IndexedLoad(SDNode *N) {
1422   LoadSDNode *LD = cast<LoadSDNode>(N);
1423   EVT LoadedVT = LD->getMemoryVT();
1424   ISD::MemIndexedMode AM = LD->getAddressingMode();
1425   if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD ||
1426       LoadedVT.getSimpleVT().SimpleTy != MVT::i32)
1427     return false;
1428 
1429   auto *COffs = dyn_cast<ConstantSDNode>(LD->getOffset());
1430   if (!COffs || COffs->getZExtValue() != 4)
1431     return false;
1432 
1433   // A T1 post-indexed load is just a single register LDM: LDM r0!, {r1}.
1434   // The encoding of LDM is not how the rest of ISel expects a post-inc load to
1435   // look however, so we use a pseudo here and switch it for a tLDMIA_UPD after
1436   // ISel.
1437   SDValue Chain = LD->getChain();
1438   SDValue Base = LD->getBasePtr();
1439   SDValue Ops[]= { Base, getAL(CurDAG, SDLoc(N)),
1440                    CurDAG->getRegister(0, MVT::i32), Chain };
1441   SDNode *New = CurDAG->getMachineNode(ARM::tLDR_postidx, SDLoc(N), MVT::i32,
1442                                        MVT::i32, MVT::Other, Ops);
1443   transferMemOperands(N, New);
1444   ReplaceNode(N, New);
1445   return true;
1446 }
1447 
1448 bool ARMDAGToDAGISel::tryT2IndexedLoad(SDNode *N) {
1449   LoadSDNode *LD = cast<LoadSDNode>(N);
1450   ISD::MemIndexedMode AM = LD->getAddressingMode();
1451   if (AM == ISD::UNINDEXED)
1452     return false;
1453 
1454   EVT LoadedVT = LD->getMemoryVT();
1455   bool isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1456   SDValue Offset;
1457   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1458   unsigned Opcode = 0;
1459   bool Match = false;
1460   if (SelectT2AddrModeImm8Offset(N, LD->getOffset(), Offset)) {
1461     switch (LoadedVT.getSimpleVT().SimpleTy) {
1462     case MVT::i32:
1463       Opcode = isPre ? ARM::t2LDR_PRE : ARM::t2LDR_POST;
1464       break;
1465     case MVT::i16:
1466       if (isSExtLd)
1467         Opcode = isPre ? ARM::t2LDRSH_PRE : ARM::t2LDRSH_POST;
1468       else
1469         Opcode = isPre ? ARM::t2LDRH_PRE : ARM::t2LDRH_POST;
1470       break;
1471     case MVT::i8:
1472     case MVT::i1:
1473       if (isSExtLd)
1474         Opcode = isPre ? ARM::t2LDRSB_PRE : ARM::t2LDRSB_POST;
1475       else
1476         Opcode = isPre ? ARM::t2LDRB_PRE : ARM::t2LDRB_POST;
1477       break;
1478     default:
1479       return false;
1480     }
1481     Match = true;
1482   }
1483 
1484   if (Match) {
1485     SDValue Chain = LD->getChain();
1486     SDValue Base = LD->getBasePtr();
1487     SDValue Ops[]= { Base, Offset, getAL(CurDAG, SDLoc(N)),
1488                      CurDAG->getRegister(0, MVT::i32), Chain };
1489     SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1490                                          MVT::Other, Ops);
1491     transferMemOperands(N, New);
1492     ReplaceNode(N, New);
1493     return true;
1494   }
1495 
1496   return false;
1497 }
1498 
1499 /// \brief Form a GPRPair pseudo register from a pair of GPR regs.
1500 SDNode *ARMDAGToDAGISel::createGPRPairNode(EVT VT, SDValue V0, SDValue V1) {
1501   SDLoc dl(V0.getNode());
1502   SDValue RegClass =
1503     CurDAG->getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
1504   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
1505   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
1506   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1507   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1508 }
1509 
1510 /// \brief Form a D register from a pair of S registers.
1511 SDNode *ARMDAGToDAGISel::createSRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1512   SDLoc dl(V0.getNode());
1513   SDValue RegClass =
1514     CurDAG->getTargetConstant(ARM::DPR_VFP2RegClassID, dl, MVT::i32);
1515   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1516   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1517   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1518   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1519 }
1520 
1521 /// \brief Form a quad register from a pair of D registers.
1522 SDNode *ARMDAGToDAGISel::createDRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1523   SDLoc dl(V0.getNode());
1524   SDValue RegClass = CurDAG->getTargetConstant(ARM::QPRRegClassID, dl,
1525                                                MVT::i32);
1526   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1527   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1528   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1529   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1530 }
1531 
1532 /// \brief Form 4 consecutive D registers from a pair of Q registers.
1533 SDNode *ARMDAGToDAGISel::createQRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1534   SDLoc dl(V0.getNode());
1535   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1536                                                MVT::i32);
1537   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1538   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1539   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1540   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1541 }
1542 
1543 /// \brief Form 4 consecutive S registers.
1544 SDNode *ARMDAGToDAGISel::createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1,
1545                                    SDValue V2, SDValue V3) {
1546   SDLoc dl(V0.getNode());
1547   SDValue RegClass =
1548     CurDAG->getTargetConstant(ARM::QPR_VFP2RegClassID, dl, MVT::i32);
1549   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1550   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1551   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::ssub_2, dl, MVT::i32);
1552   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::ssub_3, dl, MVT::i32);
1553   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1554                                     V2, SubReg2, V3, SubReg3 };
1555   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1556 }
1557 
1558 /// \brief Form 4 consecutive D registers.
1559 SDNode *ARMDAGToDAGISel::createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1,
1560                                    SDValue V2, SDValue V3) {
1561   SDLoc dl(V0.getNode());
1562   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1563                                                MVT::i32);
1564   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1565   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1566   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::dsub_2, dl, MVT::i32);
1567   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::dsub_3, dl, MVT::i32);
1568   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1569                                     V2, SubReg2, V3, SubReg3 };
1570   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1571 }
1572 
1573 /// \brief Form 4 consecutive Q registers.
1574 SDNode *ARMDAGToDAGISel::createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1,
1575                                    SDValue V2, SDValue V3) {
1576   SDLoc dl(V0.getNode());
1577   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQQQPRRegClassID, dl,
1578                                                MVT::i32);
1579   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1580   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1581   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::qsub_2, dl, MVT::i32);
1582   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::qsub_3, dl, MVT::i32);
1583   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1584                                     V2, SubReg2, V3, SubReg3 };
1585   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1586 }
1587 
1588 /// GetVLDSTAlign - Get the alignment (in bytes) for the alignment operand
1589 /// of a NEON VLD or VST instruction.  The supported values depend on the
1590 /// number of registers being loaded.
1591 SDValue ARMDAGToDAGISel::GetVLDSTAlign(SDValue Align, const SDLoc &dl,
1592                                        unsigned NumVecs, bool is64BitVector) {
1593   unsigned NumRegs = NumVecs;
1594   if (!is64BitVector && NumVecs < 3)
1595     NumRegs *= 2;
1596 
1597   unsigned Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
1598   if (Alignment >= 32 && NumRegs == 4)
1599     Alignment = 32;
1600   else if (Alignment >= 16 && (NumRegs == 2 || NumRegs == 4))
1601     Alignment = 16;
1602   else if (Alignment >= 8)
1603     Alignment = 8;
1604   else
1605     Alignment = 0;
1606 
1607   return CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
1608 }
1609 
1610 static bool isVLDfixed(unsigned Opc)
1611 {
1612   switch (Opc) {
1613   default: return false;
1614   case ARM::VLD1d8wb_fixed : return true;
1615   case ARM::VLD1d16wb_fixed : return true;
1616   case ARM::VLD1d64Qwb_fixed : return true;
1617   case ARM::VLD1d32wb_fixed : return true;
1618   case ARM::VLD1d64wb_fixed : return true;
1619   case ARM::VLD1d64TPseudoWB_fixed : return true;
1620   case ARM::VLD1d64QPseudoWB_fixed : return true;
1621   case ARM::VLD1q8wb_fixed : return true;
1622   case ARM::VLD1q16wb_fixed : return true;
1623   case ARM::VLD1q32wb_fixed : return true;
1624   case ARM::VLD1q64wb_fixed : return true;
1625   case ARM::VLD1DUPd8wb_fixed : return true;
1626   case ARM::VLD1DUPd16wb_fixed : return true;
1627   case ARM::VLD1DUPd32wb_fixed : return true;
1628   case ARM::VLD1DUPq8wb_fixed : return true;
1629   case ARM::VLD1DUPq16wb_fixed : return true;
1630   case ARM::VLD1DUPq32wb_fixed : return true;
1631   case ARM::VLD2d8wb_fixed : return true;
1632   case ARM::VLD2d16wb_fixed : return true;
1633   case ARM::VLD2d32wb_fixed : return true;
1634   case ARM::VLD2q8PseudoWB_fixed : return true;
1635   case ARM::VLD2q16PseudoWB_fixed : return true;
1636   case ARM::VLD2q32PseudoWB_fixed : return true;
1637   case ARM::VLD2DUPd8wb_fixed : return true;
1638   case ARM::VLD2DUPd16wb_fixed : return true;
1639   case ARM::VLD2DUPd32wb_fixed : return true;
1640   }
1641 }
1642 
1643 static bool isVSTfixed(unsigned Opc)
1644 {
1645   switch (Opc) {
1646   default: return false;
1647   case ARM::VST1d8wb_fixed : return true;
1648   case ARM::VST1d16wb_fixed : return true;
1649   case ARM::VST1d32wb_fixed : return true;
1650   case ARM::VST1d64wb_fixed : return true;
1651   case ARM::VST1q8wb_fixed : return true;
1652   case ARM::VST1q16wb_fixed : return true;
1653   case ARM::VST1q32wb_fixed : return true;
1654   case ARM::VST1q64wb_fixed : return true;
1655   case ARM::VST1d64TPseudoWB_fixed : return true;
1656   case ARM::VST1d64QPseudoWB_fixed : return true;
1657   case ARM::VST2d8wb_fixed : return true;
1658   case ARM::VST2d16wb_fixed : return true;
1659   case ARM::VST2d32wb_fixed : return true;
1660   case ARM::VST2q8PseudoWB_fixed : return true;
1661   case ARM::VST2q16PseudoWB_fixed : return true;
1662   case ARM::VST2q32PseudoWB_fixed : return true;
1663   }
1664 }
1665 
1666 // Get the register stride update opcode of a VLD/VST instruction that
1667 // is otherwise equivalent to the given fixed stride updating instruction.
1668 static unsigned getVLDSTRegisterUpdateOpcode(unsigned Opc) {
1669   assert((isVLDfixed(Opc) || isVSTfixed(Opc))
1670     && "Incorrect fixed stride updating instruction.");
1671   switch (Opc) {
1672   default: break;
1673   case ARM::VLD1d8wb_fixed: return ARM::VLD1d8wb_register;
1674   case ARM::VLD1d16wb_fixed: return ARM::VLD1d16wb_register;
1675   case ARM::VLD1d32wb_fixed: return ARM::VLD1d32wb_register;
1676   case ARM::VLD1d64wb_fixed: return ARM::VLD1d64wb_register;
1677   case ARM::VLD1q8wb_fixed: return ARM::VLD1q8wb_register;
1678   case ARM::VLD1q16wb_fixed: return ARM::VLD1q16wb_register;
1679   case ARM::VLD1q32wb_fixed: return ARM::VLD1q32wb_register;
1680   case ARM::VLD1q64wb_fixed: return ARM::VLD1q64wb_register;
1681   case ARM::VLD1d64Twb_fixed: return ARM::VLD1d64Twb_register;
1682   case ARM::VLD1d64Qwb_fixed: return ARM::VLD1d64Qwb_register;
1683   case ARM::VLD1d64TPseudoWB_fixed: return ARM::VLD1d64TPseudoWB_register;
1684   case ARM::VLD1d64QPseudoWB_fixed: return ARM::VLD1d64QPseudoWB_register;
1685   case ARM::VLD1DUPd8wb_fixed : return ARM::VLD1DUPd8wb_register;
1686   case ARM::VLD1DUPd16wb_fixed : return ARM::VLD1DUPd16wb_register;
1687   case ARM::VLD1DUPd32wb_fixed : return ARM::VLD1DUPd32wb_register;
1688   case ARM::VLD1DUPq8wb_fixed : return ARM::VLD1DUPq8wb_register;
1689   case ARM::VLD1DUPq16wb_fixed : return ARM::VLD1DUPq16wb_register;
1690   case ARM::VLD1DUPq32wb_fixed : return ARM::VLD1DUPq32wb_register;
1691 
1692   case ARM::VST1d8wb_fixed: return ARM::VST1d8wb_register;
1693   case ARM::VST1d16wb_fixed: return ARM::VST1d16wb_register;
1694   case ARM::VST1d32wb_fixed: return ARM::VST1d32wb_register;
1695   case ARM::VST1d64wb_fixed: return ARM::VST1d64wb_register;
1696   case ARM::VST1q8wb_fixed: return ARM::VST1q8wb_register;
1697   case ARM::VST1q16wb_fixed: return ARM::VST1q16wb_register;
1698   case ARM::VST1q32wb_fixed: return ARM::VST1q32wb_register;
1699   case ARM::VST1q64wb_fixed: return ARM::VST1q64wb_register;
1700   case ARM::VST1d64TPseudoWB_fixed: return ARM::VST1d64TPseudoWB_register;
1701   case ARM::VST1d64QPseudoWB_fixed: return ARM::VST1d64QPseudoWB_register;
1702 
1703   case ARM::VLD2d8wb_fixed: return ARM::VLD2d8wb_register;
1704   case ARM::VLD2d16wb_fixed: return ARM::VLD2d16wb_register;
1705   case ARM::VLD2d32wb_fixed: return ARM::VLD2d32wb_register;
1706   case ARM::VLD2q8PseudoWB_fixed: return ARM::VLD2q8PseudoWB_register;
1707   case ARM::VLD2q16PseudoWB_fixed: return ARM::VLD2q16PseudoWB_register;
1708   case ARM::VLD2q32PseudoWB_fixed: return ARM::VLD2q32PseudoWB_register;
1709 
1710   case ARM::VST2d8wb_fixed: return ARM::VST2d8wb_register;
1711   case ARM::VST2d16wb_fixed: return ARM::VST2d16wb_register;
1712   case ARM::VST2d32wb_fixed: return ARM::VST2d32wb_register;
1713   case ARM::VST2q8PseudoWB_fixed: return ARM::VST2q8PseudoWB_register;
1714   case ARM::VST2q16PseudoWB_fixed: return ARM::VST2q16PseudoWB_register;
1715   case ARM::VST2q32PseudoWB_fixed: return ARM::VST2q32PseudoWB_register;
1716 
1717   case ARM::VLD2DUPd8wb_fixed: return ARM::VLD2DUPd8wb_register;
1718   case ARM::VLD2DUPd16wb_fixed: return ARM::VLD2DUPd16wb_register;
1719   case ARM::VLD2DUPd32wb_fixed: return ARM::VLD2DUPd32wb_register;
1720   }
1721   return Opc; // If not one we handle, return it unchanged.
1722 }
1723 
1724 /// Returns true if the given increment is a Constant known to be equal to the
1725 /// access size performed by a NEON load/store. This means the "[rN]!" form can
1726 /// be used.
1727 static bool isPerfectIncrement(SDValue Inc, EVT VecTy, unsigned NumVecs) {
1728   auto C = dyn_cast<ConstantSDNode>(Inc);
1729   return C && C->getZExtValue() == VecTy.getSizeInBits() / 8 * NumVecs;
1730 }
1731 
1732 void ARMDAGToDAGISel::SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
1733                                 const uint16_t *DOpcodes,
1734                                 const uint16_t *QOpcodes0,
1735                                 const uint16_t *QOpcodes1) {
1736   assert(NumVecs >= 1 && NumVecs <= 4 && "VLD NumVecs out-of-range");
1737   SDLoc dl(N);
1738 
1739   SDValue MemAddr, Align;
1740   unsigned AddrOpIdx = isUpdating ? 1 : 2;
1741   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
1742     return;
1743 
1744   SDValue Chain = N->getOperand(0);
1745   EVT VT = N->getValueType(0);
1746   bool is64BitVector = VT.is64BitVector();
1747   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
1748 
1749   unsigned OpcodeIndex;
1750   switch (VT.getSimpleVT().SimpleTy) {
1751   default: llvm_unreachable("unhandled vld type");
1752     // Double-register operations:
1753   case MVT::v8i8:  OpcodeIndex = 0; break;
1754   case MVT::v4i16: OpcodeIndex = 1; break;
1755   case MVT::v2f32:
1756   case MVT::v2i32: OpcodeIndex = 2; break;
1757   case MVT::v1i64: OpcodeIndex = 3; break;
1758     // Quad-register operations:
1759   case MVT::v16i8: OpcodeIndex = 0; break;
1760   case MVT::v8i16: OpcodeIndex = 1; break;
1761   case MVT::v4f32:
1762   case MVT::v4i32: OpcodeIndex = 2; break;
1763   case MVT::v2f64:
1764   case MVT::v2i64: OpcodeIndex = 3;
1765     assert(NumVecs == 1 && "v2i64 type only supported for VLD1");
1766     break;
1767   }
1768 
1769   EVT ResTy;
1770   if (NumVecs == 1)
1771     ResTy = VT;
1772   else {
1773     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
1774     if (!is64BitVector)
1775       ResTyElts *= 2;
1776     ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
1777   }
1778   std::vector<EVT> ResTys;
1779   ResTys.push_back(ResTy);
1780   if (isUpdating)
1781     ResTys.push_back(MVT::i32);
1782   ResTys.push_back(MVT::Other);
1783 
1784   SDValue Pred = getAL(CurDAG, dl);
1785   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
1786   SDNode *VLd;
1787   SmallVector<SDValue, 7> Ops;
1788 
1789   // Double registers and VLD1/VLD2 quad registers are directly supported.
1790   if (is64BitVector || NumVecs <= 2) {
1791     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
1792                     QOpcodes0[OpcodeIndex]);
1793     Ops.push_back(MemAddr);
1794     Ops.push_back(Align);
1795     if (isUpdating) {
1796       SDValue Inc = N->getOperand(AddrOpIdx + 1);
1797       // FIXME: VLD1/VLD2 fixed increment doesn't need Reg0. Remove the reg0
1798       // case entirely when the rest are updated to that form, too.
1799       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
1800       if ((NumVecs <= 2) && !IsImmUpdate)
1801         Opc = getVLDSTRegisterUpdateOpcode(Opc);
1802       // FIXME: We use a VLD1 for v1i64 even if the pseudo says vld2/3/4, so
1803       // check for that explicitly too. Horribly hacky, but temporary.
1804       if ((NumVecs > 2 && !isVLDfixed(Opc)) || !IsImmUpdate)
1805         Ops.push_back(IsImmUpdate ? Reg0 : Inc);
1806     }
1807     Ops.push_back(Pred);
1808     Ops.push_back(Reg0);
1809     Ops.push_back(Chain);
1810     VLd = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1811 
1812   } else {
1813     // Otherwise, quad registers are loaded with two separate instructions,
1814     // where one loads the even registers and the other loads the odd registers.
1815     EVT AddrTy = MemAddr.getValueType();
1816 
1817     // Load the even subregs.  This is always an updating load, so that it
1818     // provides the address to the second load for the odd subregs.
1819     SDValue ImplDef =
1820       SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
1821     const SDValue OpsA[] = { MemAddr, Align, Reg0, ImplDef, Pred, Reg0, Chain };
1822     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
1823                                           ResTy, AddrTy, MVT::Other, OpsA);
1824     Chain = SDValue(VLdA, 2);
1825 
1826     // Load the odd subregs.
1827     Ops.push_back(SDValue(VLdA, 1));
1828     Ops.push_back(Align);
1829     if (isUpdating) {
1830       SDValue Inc = N->getOperand(AddrOpIdx + 1);
1831       assert(isa<ConstantSDNode>(Inc.getNode()) &&
1832              "only constant post-increment update allowed for VLD3/4");
1833       (void)Inc;
1834       Ops.push_back(Reg0);
1835     }
1836     Ops.push_back(SDValue(VLdA, 0));
1837     Ops.push_back(Pred);
1838     Ops.push_back(Reg0);
1839     Ops.push_back(Chain);
1840     VLd = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, Ops);
1841   }
1842 
1843   // Transfer memoperands.
1844   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1845   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1846   cast<MachineSDNode>(VLd)->setMemRefs(MemOp, MemOp + 1);
1847 
1848   if (NumVecs == 1) {
1849     ReplaceNode(N, VLd);
1850     return;
1851   }
1852 
1853   // Extract out the subregisters.
1854   SDValue SuperReg = SDValue(VLd, 0);
1855   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
1856                     ARM::qsub_3 == ARM::qsub_0 + 3,
1857                 "Unexpected subreg numbering");
1858   unsigned Sub0 = (is64BitVector ? ARM::dsub_0 : ARM::qsub_0);
1859   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
1860     ReplaceUses(SDValue(N, Vec),
1861                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
1862   ReplaceUses(SDValue(N, NumVecs), SDValue(VLd, 1));
1863   if (isUpdating)
1864     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLd, 2));
1865   CurDAG->RemoveDeadNode(N);
1866 }
1867 
1868 void ARMDAGToDAGISel::SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
1869                                 const uint16_t *DOpcodes,
1870                                 const uint16_t *QOpcodes0,
1871                                 const uint16_t *QOpcodes1) {
1872   assert(NumVecs >= 1 && NumVecs <= 4 && "VST NumVecs out-of-range");
1873   SDLoc dl(N);
1874 
1875   SDValue MemAddr, Align;
1876   unsigned AddrOpIdx = isUpdating ? 1 : 2;
1877   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
1878   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
1879     return;
1880 
1881   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
1882   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1883 
1884   SDValue Chain = N->getOperand(0);
1885   EVT VT = N->getOperand(Vec0Idx).getValueType();
1886   bool is64BitVector = VT.is64BitVector();
1887   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
1888 
1889   unsigned OpcodeIndex;
1890   switch (VT.getSimpleVT().SimpleTy) {
1891   default: llvm_unreachable("unhandled vst type");
1892     // Double-register operations:
1893   case MVT::v8i8:  OpcodeIndex = 0; break;
1894   case MVT::v4i16: OpcodeIndex = 1; break;
1895   case MVT::v2f32:
1896   case MVT::v2i32: OpcodeIndex = 2; break;
1897   case MVT::v1i64: OpcodeIndex = 3; break;
1898     // Quad-register operations:
1899   case MVT::v16i8: OpcodeIndex = 0; break;
1900   case MVT::v8i16: OpcodeIndex = 1; break;
1901   case MVT::v4f32:
1902   case MVT::v4i32: OpcodeIndex = 2; break;
1903   case MVT::v2f64:
1904   case MVT::v2i64: OpcodeIndex = 3;
1905     assert(NumVecs == 1 && "v2i64 type only supported for VST1");
1906     break;
1907   }
1908 
1909   std::vector<EVT> ResTys;
1910   if (isUpdating)
1911     ResTys.push_back(MVT::i32);
1912   ResTys.push_back(MVT::Other);
1913 
1914   SDValue Pred = getAL(CurDAG, dl);
1915   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
1916   SmallVector<SDValue, 7> Ops;
1917 
1918   // Double registers and VST1/VST2 quad registers are directly supported.
1919   if (is64BitVector || NumVecs <= 2) {
1920     SDValue SrcReg;
1921     if (NumVecs == 1) {
1922       SrcReg = N->getOperand(Vec0Idx);
1923     } else if (is64BitVector) {
1924       // Form a REG_SEQUENCE to force register allocation.
1925       SDValue V0 = N->getOperand(Vec0Idx + 0);
1926       SDValue V1 = N->getOperand(Vec0Idx + 1);
1927       if (NumVecs == 2)
1928         SrcReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
1929       else {
1930         SDValue V2 = N->getOperand(Vec0Idx + 2);
1931         // If it's a vst3, form a quad D-register and leave the last part as
1932         // an undef.
1933         SDValue V3 = (NumVecs == 3)
1934           ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,dl,VT), 0)
1935           : N->getOperand(Vec0Idx + 3);
1936         SrcReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
1937       }
1938     } else {
1939       // Form a QQ register.
1940       SDValue Q0 = N->getOperand(Vec0Idx);
1941       SDValue Q1 = N->getOperand(Vec0Idx + 1);
1942       SrcReg = SDValue(createQRegPairNode(MVT::v4i64, Q0, Q1), 0);
1943     }
1944 
1945     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
1946                     QOpcodes0[OpcodeIndex]);
1947     Ops.push_back(MemAddr);
1948     Ops.push_back(Align);
1949     if (isUpdating) {
1950       SDValue Inc = N->getOperand(AddrOpIdx + 1);
1951       // FIXME: VST1/VST2 fixed increment doesn't need Reg0. Remove the reg0
1952       // case entirely when the rest are updated to that form, too.
1953       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
1954       if (NumVecs <= 2 && !IsImmUpdate)
1955         Opc = getVLDSTRegisterUpdateOpcode(Opc);
1956       // FIXME: We use a VST1 for v1i64 even if the pseudo says vld2/3/4, so
1957       // check for that explicitly too. Horribly hacky, but temporary.
1958       if  (!IsImmUpdate)
1959         Ops.push_back(Inc);
1960       else if (NumVecs > 2 && !isVSTfixed(Opc))
1961         Ops.push_back(Reg0);
1962     }
1963     Ops.push_back(SrcReg);
1964     Ops.push_back(Pred);
1965     Ops.push_back(Reg0);
1966     Ops.push_back(Chain);
1967     SDNode *VSt = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1968 
1969     // Transfer memoperands.
1970     cast<MachineSDNode>(VSt)->setMemRefs(MemOp, MemOp + 1);
1971 
1972     ReplaceNode(N, VSt);
1973     return;
1974   }
1975 
1976   // Otherwise, quad registers are stored with two separate instructions,
1977   // where one stores the even registers and the other stores the odd registers.
1978 
1979   // Form the QQQQ REG_SEQUENCE.
1980   SDValue V0 = N->getOperand(Vec0Idx + 0);
1981   SDValue V1 = N->getOperand(Vec0Idx + 1);
1982   SDValue V2 = N->getOperand(Vec0Idx + 2);
1983   SDValue V3 = (NumVecs == 3)
1984     ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
1985     : N->getOperand(Vec0Idx + 3);
1986   SDValue RegSeq = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
1987 
1988   // Store the even D registers.  This is always an updating store, so that it
1989   // provides the address to the second store for the odd subregs.
1990   const SDValue OpsA[] = { MemAddr, Align, Reg0, RegSeq, Pred, Reg0, Chain };
1991   SDNode *VStA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
1992                                         MemAddr.getValueType(),
1993                                         MVT::Other, OpsA);
1994   cast<MachineSDNode>(VStA)->setMemRefs(MemOp, MemOp + 1);
1995   Chain = SDValue(VStA, 1);
1996 
1997   // Store the odd D registers.
1998   Ops.push_back(SDValue(VStA, 0));
1999   Ops.push_back(Align);
2000   if (isUpdating) {
2001     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2002     assert(isa<ConstantSDNode>(Inc.getNode()) &&
2003            "only constant post-increment update allowed for VST3/4");
2004     (void)Inc;
2005     Ops.push_back(Reg0);
2006   }
2007   Ops.push_back(RegSeq);
2008   Ops.push_back(Pred);
2009   Ops.push_back(Reg0);
2010   Ops.push_back(Chain);
2011   SDNode *VStB = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys,
2012                                         Ops);
2013   cast<MachineSDNode>(VStB)->setMemRefs(MemOp, MemOp + 1);
2014   ReplaceNode(N, VStB);
2015 }
2016 
2017 void ARMDAGToDAGISel::SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
2018                                       unsigned NumVecs,
2019                                       const uint16_t *DOpcodes,
2020                                       const uint16_t *QOpcodes) {
2021   assert(NumVecs >=2 && NumVecs <= 4 && "VLDSTLane NumVecs out-of-range");
2022   SDLoc dl(N);
2023 
2024   SDValue MemAddr, Align;
2025   unsigned AddrOpIdx = isUpdating ? 1 : 2;
2026   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
2027   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2028     return;
2029 
2030   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2031   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2032 
2033   SDValue Chain = N->getOperand(0);
2034   unsigned Lane =
2035     cast<ConstantSDNode>(N->getOperand(Vec0Idx + NumVecs))->getZExtValue();
2036   EVT VT = N->getOperand(Vec0Idx).getValueType();
2037   bool is64BitVector = VT.is64BitVector();
2038 
2039   unsigned Alignment = 0;
2040   if (NumVecs != 3) {
2041     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2042     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2043     if (Alignment > NumBytes)
2044       Alignment = NumBytes;
2045     if (Alignment < 8 && Alignment < NumBytes)
2046       Alignment = 0;
2047     // Alignment must be a power of two; make sure of that.
2048     Alignment = (Alignment & -Alignment);
2049     if (Alignment == 1)
2050       Alignment = 0;
2051   }
2052   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2053 
2054   unsigned OpcodeIndex;
2055   switch (VT.getSimpleVT().SimpleTy) {
2056   default: llvm_unreachable("unhandled vld/vst lane type");
2057     // Double-register operations:
2058   case MVT::v8i8:  OpcodeIndex = 0; break;
2059   case MVT::v4i16: OpcodeIndex = 1; break;
2060   case MVT::v2f32:
2061   case MVT::v2i32: OpcodeIndex = 2; break;
2062     // Quad-register operations:
2063   case MVT::v8i16: OpcodeIndex = 0; break;
2064   case MVT::v4f32:
2065   case MVT::v4i32: OpcodeIndex = 1; break;
2066   }
2067 
2068   std::vector<EVT> ResTys;
2069   if (IsLoad) {
2070     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2071     if (!is64BitVector)
2072       ResTyElts *= 2;
2073     ResTys.push_back(EVT::getVectorVT(*CurDAG->getContext(),
2074                                       MVT::i64, ResTyElts));
2075   }
2076   if (isUpdating)
2077     ResTys.push_back(MVT::i32);
2078   ResTys.push_back(MVT::Other);
2079 
2080   SDValue Pred = getAL(CurDAG, dl);
2081   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2082 
2083   SmallVector<SDValue, 8> Ops;
2084   Ops.push_back(MemAddr);
2085   Ops.push_back(Align);
2086   if (isUpdating) {
2087     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2088     bool IsImmUpdate =
2089         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
2090     Ops.push_back(IsImmUpdate ? Reg0 : Inc);
2091   }
2092 
2093   SDValue SuperReg;
2094   SDValue V0 = N->getOperand(Vec0Idx + 0);
2095   SDValue V1 = N->getOperand(Vec0Idx + 1);
2096   if (NumVecs == 2) {
2097     if (is64BitVector)
2098       SuperReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
2099     else
2100       SuperReg = SDValue(createQRegPairNode(MVT::v4i64, V0, V1), 0);
2101   } else {
2102     SDValue V2 = N->getOperand(Vec0Idx + 2);
2103     SDValue V3 = (NumVecs == 3)
2104       ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
2105       : N->getOperand(Vec0Idx + 3);
2106     if (is64BitVector)
2107       SuperReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
2108     else
2109       SuperReg = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
2110   }
2111   Ops.push_back(SuperReg);
2112   Ops.push_back(getI32Imm(Lane, dl));
2113   Ops.push_back(Pred);
2114   Ops.push_back(Reg0);
2115   Ops.push_back(Chain);
2116 
2117   unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2118                                   QOpcodes[OpcodeIndex]);
2119   SDNode *VLdLn = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2120   cast<MachineSDNode>(VLdLn)->setMemRefs(MemOp, MemOp + 1);
2121   if (!IsLoad) {
2122     ReplaceNode(N, VLdLn);
2123     return;
2124   }
2125 
2126   // Extract the subregisters.
2127   SuperReg = SDValue(VLdLn, 0);
2128   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
2129                     ARM::qsub_3 == ARM::qsub_0 + 3,
2130                 "Unexpected subreg numbering");
2131   unsigned Sub0 = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
2132   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2133     ReplaceUses(SDValue(N, Vec),
2134                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
2135   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdLn, 1));
2136   if (isUpdating)
2137     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdLn, 2));
2138   CurDAG->RemoveDeadNode(N);
2139 }
2140 
2141 void ARMDAGToDAGISel::SelectVLDDup(SDNode *N, bool isUpdating, unsigned NumVecs,
2142                                    const uint16_t *DOpcodes,
2143                                    const uint16_t *QOpcodes) {
2144   assert(NumVecs >= 1 && NumVecs <= 4 && "VLDDup NumVecs out-of-range");
2145   SDLoc dl(N);
2146 
2147   SDValue MemAddr, Align;
2148   if (!SelectAddrMode6(N, N->getOperand(1), MemAddr, Align))
2149     return;
2150 
2151   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2152   MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2153 
2154   SDValue Chain = N->getOperand(0);
2155   EVT VT = N->getValueType(0);
2156 
2157   unsigned Alignment = 0;
2158   if (NumVecs != 3) {
2159     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2160     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2161     if (Alignment > NumBytes)
2162       Alignment = NumBytes;
2163     if (Alignment < 8 && Alignment < NumBytes)
2164       Alignment = 0;
2165     // Alignment must be a power of two; make sure of that.
2166     Alignment = (Alignment & -Alignment);
2167     if (Alignment == 1)
2168       Alignment = 0;
2169   }
2170   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2171 
2172   unsigned Opc;
2173   switch (VT.getSimpleVT().SimpleTy) {
2174   default: llvm_unreachable("unhandled vld-dup type");
2175   case MVT::v8i8:  Opc = DOpcodes[0]; break;
2176   case MVT::v16i8: Opc = QOpcodes[0]; break;
2177   case MVT::v4i16: Opc = DOpcodes[1]; break;
2178   case MVT::v8i16: Opc = QOpcodes[1]; break;
2179   case MVT::v2f32:
2180   case MVT::v2i32: Opc = DOpcodes[2]; break;
2181   case MVT::v4f32:
2182   case MVT::v4i32: Opc = QOpcodes[2]; break;
2183   }
2184 
2185   SDValue Pred = getAL(CurDAG, dl);
2186   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2187   SmallVector<SDValue, 6> Ops;
2188   Ops.push_back(MemAddr);
2189   Ops.push_back(Align);
2190   if (isUpdating) {
2191     // fixed-stride update instructions don't have an explicit writeback
2192     // operand. It's implicit in the opcode itself.
2193     SDValue Inc = N->getOperand(2);
2194     bool IsImmUpdate =
2195         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
2196     if (NumVecs <= 2 && !IsImmUpdate)
2197       Opc = getVLDSTRegisterUpdateOpcode(Opc);
2198     if (!IsImmUpdate)
2199       Ops.push_back(Inc);
2200     // FIXME: VLD3 and VLD4 haven't been updated to that form yet.
2201     else if (NumVecs > 2)
2202       Ops.push_back(Reg0);
2203   }
2204   Ops.push_back(Pred);
2205   Ops.push_back(Reg0);
2206   Ops.push_back(Chain);
2207 
2208   unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2209   std::vector<EVT> ResTys;
2210   ResTys.push_back(EVT::getVectorVT(*CurDAG->getContext(), MVT::i64,ResTyElts));
2211   if (isUpdating)
2212     ResTys.push_back(MVT::i32);
2213   ResTys.push_back(MVT::Other);
2214   SDNode *VLdDup = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2215   cast<MachineSDNode>(VLdDup)->setMemRefs(MemOp, MemOp + 1);
2216 
2217   // Extract the subregisters.
2218   if (NumVecs == 1) {
2219     ReplaceUses(SDValue(N, 0), SDValue(VLdDup, 0));
2220   } else {
2221     SDValue SuperReg = SDValue(VLdDup, 0);
2222     static_assert(ARM::dsub_7 == ARM::dsub_0 + 7, "Unexpected subreg numbering");
2223     unsigned SubIdx = ARM::dsub_0;
2224     for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2225       ReplaceUses(SDValue(N, Vec),
2226                   CurDAG->getTargetExtractSubreg(SubIdx+Vec, dl, VT, SuperReg));
2227   }
2228   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdDup, 1));
2229   if (isUpdating)
2230     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdDup, 2));
2231   CurDAG->RemoveDeadNode(N);
2232 }
2233 
2234 bool ARMDAGToDAGISel::tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned) {
2235   if (!Subtarget->hasV6T2Ops())
2236     return false;
2237 
2238   unsigned Opc = isSigned
2239     ? (Subtarget->isThumb() ? ARM::t2SBFX : ARM::SBFX)
2240     : (Subtarget->isThumb() ? ARM::t2UBFX : ARM::UBFX);
2241   SDLoc dl(N);
2242 
2243   // For unsigned extracts, check for a shift right and mask
2244   unsigned And_imm = 0;
2245   if (N->getOpcode() == ISD::AND) {
2246     if (isOpcWithIntImmediate(N, ISD::AND, And_imm)) {
2247 
2248       // The immediate is a mask of the low bits iff imm & (imm+1) == 0
2249       if (And_imm & (And_imm + 1))
2250         return false;
2251 
2252       unsigned Srl_imm = 0;
2253       if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL,
2254                                 Srl_imm)) {
2255         assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
2256 
2257         // Note: The width operand is encoded as width-1.
2258         unsigned Width = countTrailingOnes(And_imm) - 1;
2259         unsigned LSB = Srl_imm;
2260 
2261         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2262 
2263         if ((LSB + Width + 1) == N->getValueType(0).getSizeInBits()) {
2264           // It's cheaper to use a right shift to extract the top bits.
2265           if (Subtarget->isThumb()) {
2266             Opc = isSigned ? ARM::t2ASRri : ARM::t2LSRri;
2267             SDValue Ops[] = { N->getOperand(0).getOperand(0),
2268                               CurDAG->getTargetConstant(LSB, dl, MVT::i32),
2269                               getAL(CurDAG, dl), Reg0, Reg0 };
2270             CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2271             return true;
2272           }
2273 
2274           // ARM models shift instructions as MOVsi with shifter operand.
2275           ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(ISD::SRL);
2276           SDValue ShOpc =
2277             CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, LSB), dl,
2278                                       MVT::i32);
2279           SDValue Ops[] = { N->getOperand(0).getOperand(0), ShOpc,
2280                             getAL(CurDAG, dl), Reg0, Reg0 };
2281           CurDAG->SelectNodeTo(N, ARM::MOVsi, MVT::i32, Ops);
2282           return true;
2283         }
2284 
2285         SDValue Ops[] = { N->getOperand(0).getOperand(0),
2286                           CurDAG->getTargetConstant(LSB, dl, MVT::i32),
2287                           CurDAG->getTargetConstant(Width, dl, MVT::i32),
2288                           getAL(CurDAG, dl), Reg0 };
2289         CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2290         return true;
2291       }
2292     }
2293     return false;
2294   }
2295 
2296   // Otherwise, we're looking for a shift of a shift
2297   unsigned Shl_imm = 0;
2298   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, Shl_imm)) {
2299     assert(Shl_imm > 0 && Shl_imm < 32 && "bad amount in shift node!");
2300     unsigned Srl_imm = 0;
2301     if (isInt32Immediate(N->getOperand(1), Srl_imm)) {
2302       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
2303       // Note: The width operand is encoded as width-1.
2304       unsigned Width = 32 - Srl_imm - 1;
2305       int LSB = Srl_imm - Shl_imm;
2306       if (LSB < 0)
2307         return false;
2308       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2309       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2310                         CurDAG->getTargetConstant(LSB, dl, MVT::i32),
2311                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
2312                         getAL(CurDAG, dl), Reg0 };
2313       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2314       return true;
2315     }
2316   }
2317 
2318   // Or we are looking for a shift of an and, with a mask operand
2319   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, And_imm) &&
2320       isShiftedMask_32(And_imm)) {
2321     unsigned Srl_imm = 0;
2322     unsigned LSB = countTrailingZeros(And_imm);
2323     // Shift must be the same as the ands lsb
2324     if (isInt32Immediate(N->getOperand(1), Srl_imm) && Srl_imm == LSB) {
2325       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
2326       unsigned MSB = 31 - countLeadingZeros(And_imm);
2327       // Note: The width operand is encoded as width-1.
2328       unsigned Width = MSB - LSB;
2329       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2330       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2331                         CurDAG->getTargetConstant(Srl_imm, dl, MVT::i32),
2332                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
2333                         getAL(CurDAG, dl), Reg0 };
2334       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2335       return true;
2336     }
2337   }
2338 
2339   if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2340     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
2341     unsigned LSB = 0;
2342     if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL, LSB) &&
2343         !isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRA, LSB))
2344       return false;
2345 
2346     if (LSB + Width > 32)
2347       return false;
2348 
2349     SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2350     SDValue Ops[] = { N->getOperand(0).getOperand(0),
2351                       CurDAG->getTargetConstant(LSB, dl, MVT::i32),
2352                       CurDAG->getTargetConstant(Width - 1, dl, MVT::i32),
2353                       getAL(CurDAG, dl), Reg0 };
2354     CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2355     return true;
2356   }
2357 
2358   return false;
2359 }
2360 
2361 /// Target-specific DAG combining for ISD::XOR.
2362 /// Target-independent combining lowers SELECT_CC nodes of the form
2363 /// select_cc setg[ge] X,  0,  X, -X
2364 /// select_cc setgt    X, -1,  X, -X
2365 /// select_cc setl[te] X,  0, -X,  X
2366 /// select_cc setlt    X,  1, -X,  X
2367 /// which represent Integer ABS into:
2368 /// Y = sra (X, size(X)-1); xor (add (X, Y), Y)
2369 /// ARM instruction selection detects the latter and matches it to
2370 /// ARM::ABS or ARM::t2ABS machine node.
2371 bool ARMDAGToDAGISel::tryABSOp(SDNode *N){
2372   SDValue XORSrc0 = N->getOperand(0);
2373   SDValue XORSrc1 = N->getOperand(1);
2374   EVT VT = N->getValueType(0);
2375 
2376   if (Subtarget->isThumb1Only())
2377     return false;
2378 
2379   if (XORSrc0.getOpcode() != ISD::ADD || XORSrc1.getOpcode() != ISD::SRA)
2380     return false;
2381 
2382   SDValue ADDSrc0 = XORSrc0.getOperand(0);
2383   SDValue ADDSrc1 = XORSrc0.getOperand(1);
2384   SDValue SRASrc0 = XORSrc1.getOperand(0);
2385   SDValue SRASrc1 = XORSrc1.getOperand(1);
2386   ConstantSDNode *SRAConstant =  dyn_cast<ConstantSDNode>(SRASrc1);
2387   EVT XType = SRASrc0.getValueType();
2388   unsigned Size = XType.getSizeInBits() - 1;
2389 
2390   if (ADDSrc1 == XORSrc1 && ADDSrc0 == SRASrc0 &&
2391       XType.isInteger() && SRAConstant != nullptr &&
2392       Size == SRAConstant->getZExtValue()) {
2393     unsigned Opcode = Subtarget->isThumb2() ? ARM::t2ABS : ARM::ABS;
2394     CurDAG->SelectNodeTo(N, Opcode, VT, ADDSrc0);
2395     return true;
2396   }
2397 
2398   return false;
2399 }
2400 
2401 /// We've got special pseudo-instructions for these
2402 void ARMDAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
2403   unsigned Opcode;
2404   EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
2405   if (MemTy == MVT::i8)
2406     Opcode = ARM::CMP_SWAP_8;
2407   else if (MemTy == MVT::i16)
2408     Opcode = ARM::CMP_SWAP_16;
2409   else if (MemTy == MVT::i32)
2410     Opcode = ARM::CMP_SWAP_32;
2411   else
2412     llvm_unreachable("Unknown AtomicCmpSwap type");
2413 
2414   SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
2415                    N->getOperand(0)};
2416   SDNode *CmpSwap = CurDAG->getMachineNode(
2417       Opcode, SDLoc(N),
2418       CurDAG->getVTList(MVT::i32, MVT::i32, MVT::Other), Ops);
2419 
2420   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2421   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2422   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
2423 
2424   ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
2425   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
2426   CurDAG->RemoveDeadNode(N);
2427 }
2428 
2429 static Optional<std::pair<unsigned, unsigned>>
2430 getContiguousRangeOfSetBits(const APInt &A) {
2431   unsigned FirstOne = A.getBitWidth() - A.countLeadingZeros() - 1;
2432   unsigned LastOne = A.countTrailingZeros();
2433   if (A.countPopulation() != (FirstOne - LastOne + 1))
2434     return Optional<std::pair<unsigned,unsigned>>();
2435   return std::make_pair(FirstOne, LastOne);
2436 }
2437 
2438 void ARMDAGToDAGISel::SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI) {
2439   assert(N->getOpcode() == ARMISD::CMPZ);
2440   SwitchEQNEToPLMI = false;
2441 
2442   if (!Subtarget->isThumb())
2443     // FIXME: Work out whether it is profitable to do this in A32 mode - LSL and
2444     // LSR don't exist as standalone instructions - they need the barrel shifter.
2445     return;
2446 
2447   // select (cmpz (and X, C), #0) -> (LSLS X) or (LSRS X) or (LSRS (LSLS X))
2448   SDValue And = N->getOperand(0);
2449   if (!And->hasOneUse())
2450     return;
2451 
2452   SDValue Zero = N->getOperand(1);
2453   if (!isa<ConstantSDNode>(Zero) || !cast<ConstantSDNode>(Zero)->isNullValue() ||
2454       And->getOpcode() != ISD::AND)
2455     return;
2456   SDValue X = And.getOperand(0);
2457   auto C = dyn_cast<ConstantSDNode>(And.getOperand(1));
2458 
2459   if (!C || !X->hasOneUse())
2460     return;
2461   auto Range = getContiguousRangeOfSetBits(C->getAPIntValue());
2462   if (!Range)
2463     return;
2464 
2465   // There are several ways to lower this:
2466   SDNode *NewN;
2467   SDLoc dl(N);
2468 
2469   auto EmitShift = [&](unsigned Opc, SDValue Src, unsigned Imm) -> SDNode* {
2470     if (Subtarget->isThumb2()) {
2471       Opc = (Opc == ARM::tLSLri) ? ARM::t2LSLri : ARM::t2LSRri;
2472       SDValue Ops[] = { Src, CurDAG->getTargetConstant(Imm, dl, MVT::i32),
2473                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
2474                         CurDAG->getRegister(0, MVT::i32) };
2475       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
2476     } else {
2477       SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), Src,
2478                        CurDAG->getTargetConstant(Imm, dl, MVT::i32),
2479                        getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
2480       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
2481     }
2482   };
2483 
2484   if (Range->second == 0) {
2485     //  1. Mask includes the LSB -> Simply shift the top N bits off
2486     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
2487     ReplaceNode(And.getNode(), NewN);
2488   } else if (Range->first == 31) {
2489     //  2. Mask includes the MSB -> Simply shift the bottom N bits off
2490     NewN = EmitShift(ARM::tLSRri, X, Range->second);
2491     ReplaceNode(And.getNode(), NewN);
2492   } else if (Range->first == Range->second) {
2493     //  3. Only one bit is set. We can shift this into the sign bit and use a
2494     //     PL/MI comparison.
2495     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
2496     ReplaceNode(And.getNode(), NewN);
2497 
2498     SwitchEQNEToPLMI = true;
2499   } else if (!Subtarget->hasV6T2Ops()) {
2500     //  4. Do a double shift to clear bottom and top bits, but only in
2501     //     thumb-1 mode as in thumb-2 we can use UBFX.
2502     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
2503     NewN = EmitShift(ARM::tLSRri, SDValue(NewN, 0),
2504                      Range->second + (31 - Range->first));
2505     ReplaceNode(And.getNode(), NewN);
2506   }
2507 
2508 }
2509 
2510 void ARMDAGToDAGISel::Select(SDNode *N) {
2511   SDLoc dl(N);
2512 
2513   if (N->isMachineOpcode()) {
2514     N->setNodeId(-1);
2515     return;   // Already selected.
2516   }
2517 
2518   switch (N->getOpcode()) {
2519   default: break;
2520   case ISD::WRITE_REGISTER:
2521     if (tryWriteRegister(N))
2522       return;
2523     break;
2524   case ISD::READ_REGISTER:
2525     if (tryReadRegister(N))
2526       return;
2527     break;
2528   case ISD::INLINEASM:
2529     if (tryInlineAsm(N))
2530       return;
2531     break;
2532   case ISD::XOR:
2533     // Select special operations if XOR node forms integer ABS pattern
2534     if (tryABSOp(N))
2535       return;
2536     // Other cases are autogenerated.
2537     break;
2538   case ISD::Constant: {
2539     unsigned Val = cast<ConstantSDNode>(N)->getZExtValue();
2540     // If we can't materialize the constant we need to use a literal pool
2541     if (ConstantMaterializationCost(Val) > 2) {
2542       SDValue CPIdx = CurDAG->getTargetConstantPool(
2543           ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
2544           TLI->getPointerTy(CurDAG->getDataLayout()));
2545 
2546       SDNode *ResNode;
2547       if (Subtarget->isThumb()) {
2548         SDValue Ops[] = {
2549           CPIdx,
2550           getAL(CurDAG, dl),
2551           CurDAG->getRegister(0, MVT::i32),
2552           CurDAG->getEntryNode()
2553         };
2554         ResNode = CurDAG->getMachineNode(ARM::tLDRpci, dl, MVT::i32, MVT::Other,
2555                                          Ops);
2556       } else {
2557         SDValue Ops[] = {
2558           CPIdx,
2559           CurDAG->getTargetConstant(0, dl, MVT::i32),
2560           getAL(CurDAG, dl),
2561           CurDAG->getRegister(0, MVT::i32),
2562           CurDAG->getEntryNode()
2563         };
2564         ResNode = CurDAG->getMachineNode(ARM::LDRcp, dl, MVT::i32, MVT::Other,
2565                                          Ops);
2566       }
2567       // Annotate the Node with memory operand information so that MachineInstr
2568       // queries work properly. This e.g. gives the register allocation the
2569       // required information for rematerialization.
2570       MachineFunction& MF = CurDAG->getMachineFunction();
2571       MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
2572       MemOp[0] = MF.getMachineMemOperand(
2573           MachinePointerInfo::getConstantPool(MF),
2574           MachineMemOperand::MOLoad, 4, 4);
2575 
2576       cast<MachineSDNode>(ResNode)->setMemRefs(MemOp, MemOp+1);
2577 
2578       ReplaceNode(N, ResNode);
2579       return;
2580     }
2581 
2582     // Other cases are autogenerated.
2583     break;
2584   }
2585   case ISD::FrameIndex: {
2586     // Selects to ADDri FI, 0 which in turn will become ADDri SP, imm.
2587     int FI = cast<FrameIndexSDNode>(N)->getIndex();
2588     SDValue TFI = CurDAG->getTargetFrameIndex(
2589         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
2590     if (Subtarget->isThumb1Only()) {
2591       // Set the alignment of the frame object to 4, to avoid having to generate
2592       // more than one ADD
2593       MachineFrameInfo &MFI = MF->getFrameInfo();
2594       if (MFI.getObjectAlignment(FI) < 4)
2595         MFI.setObjectAlignment(FI, 4);
2596       CurDAG->SelectNodeTo(N, ARM::tADDframe, MVT::i32, TFI,
2597                            CurDAG->getTargetConstant(0, dl, MVT::i32));
2598       return;
2599     } else {
2600       unsigned Opc = ((Subtarget->isThumb() && Subtarget->hasThumb2()) ?
2601                       ARM::t2ADDri : ARM::ADDri);
2602       SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, dl, MVT::i32),
2603                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
2604                         CurDAG->getRegister(0, MVT::i32) };
2605       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
2606       return;
2607     }
2608   }
2609   case ISD::SRL:
2610     if (tryV6T2BitfieldExtractOp(N, false))
2611       return;
2612     break;
2613   case ISD::SIGN_EXTEND_INREG:
2614   case ISD::SRA:
2615     if (tryV6T2BitfieldExtractOp(N, true))
2616       return;
2617     break;
2618   case ISD::MUL:
2619     if (Subtarget->isThumb1Only())
2620       break;
2621     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
2622       unsigned RHSV = C->getZExtValue();
2623       if (!RHSV) break;
2624       if (isPowerOf2_32(RHSV-1)) {  // 2^n+1?
2625         unsigned ShImm = Log2_32(RHSV-1);
2626         if (ShImm >= 32)
2627           break;
2628         SDValue V = N->getOperand(0);
2629         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
2630         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
2631         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2632         if (Subtarget->isThumb()) {
2633           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
2634           CurDAG->SelectNodeTo(N, ARM::t2ADDrs, MVT::i32, Ops);
2635           return;
2636         } else {
2637           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
2638                             Reg0 };
2639           CurDAG->SelectNodeTo(N, ARM::ADDrsi, MVT::i32, Ops);
2640           return;
2641         }
2642       }
2643       if (isPowerOf2_32(RHSV+1)) {  // 2^n-1?
2644         unsigned ShImm = Log2_32(RHSV+1);
2645         if (ShImm >= 32)
2646           break;
2647         SDValue V = N->getOperand(0);
2648         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
2649         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
2650         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2651         if (Subtarget->isThumb()) {
2652           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
2653           CurDAG->SelectNodeTo(N, ARM::t2RSBrs, MVT::i32, Ops);
2654           return;
2655         } else {
2656           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
2657                             Reg0 };
2658           CurDAG->SelectNodeTo(N, ARM::RSBrsi, MVT::i32, Ops);
2659           return;
2660         }
2661       }
2662     }
2663     break;
2664   case ISD::AND: {
2665     // Check for unsigned bitfield extract
2666     if (tryV6T2BitfieldExtractOp(N, false))
2667       return;
2668 
2669     // If an immediate is used in an AND node, it is possible that the immediate
2670     // can be more optimally materialized when negated. If this is the case we
2671     // can negate the immediate and use a BIC instead.
2672     auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2673     if (N1C && N1C->hasOneUse() && Subtarget->isThumb()) {
2674       uint32_t Imm = (uint32_t) N1C->getZExtValue();
2675 
2676       // In Thumb2 mode, an AND can take a 12-bit immediate. If this
2677       // immediate can be negated and fit in the immediate operand of
2678       // a t2BIC, don't do any manual transform here as this can be
2679       // handled by the generic ISel machinery.
2680       bool PreferImmediateEncoding =
2681         Subtarget->hasThumb2() && (is_t2_so_imm(Imm) || is_t2_so_imm_not(Imm));
2682       if (!PreferImmediateEncoding &&
2683           ConstantMaterializationCost(Imm) >
2684               ConstantMaterializationCost(~Imm)) {
2685         // The current immediate costs more to materialize than a negated
2686         // immediate, so negate the immediate and use a BIC.
2687         SDValue NewImm =
2688           CurDAG->getConstant(~N1C->getZExtValue(), dl, MVT::i32);
2689         // If the new constant didn't exist before, reposition it in the topological
2690         // ordering so it is just before N. Otherwise, don't touch its location.
2691         if (NewImm->getNodeId() == -1)
2692           CurDAG->RepositionNode(N->getIterator(), NewImm.getNode());
2693 
2694         if (!Subtarget->hasThumb2()) {
2695           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32),
2696                            N->getOperand(0), NewImm, getAL(CurDAG, dl),
2697                            CurDAG->getRegister(0, MVT::i32)};
2698           ReplaceNode(N, CurDAG->getMachineNode(ARM::tBIC, dl, MVT::i32, Ops));
2699           return;
2700         } else {
2701           SDValue Ops[] = {N->getOperand(0), NewImm, getAL(CurDAG, dl),
2702                            CurDAG->getRegister(0, MVT::i32),
2703                            CurDAG->getRegister(0, MVT::i32)};
2704           ReplaceNode(N,
2705                       CurDAG->getMachineNode(ARM::t2BICrr, dl, MVT::i32, Ops));
2706           return;
2707         }
2708       }
2709     }
2710 
2711     // (and (or x, c2), c1) and top 16-bits of c1 and c2 match, lower 16-bits
2712     // of c1 are 0xffff, and lower 16-bit of c2 are 0. That is, the top 16-bits
2713     // are entirely contributed by c2 and lower 16-bits are entirely contributed
2714     // by x. That's equal to (or (and x, 0xffff), (and c1, 0xffff0000)).
2715     // Select it to: "movt x, ((c1 & 0xffff) >> 16)
2716     EVT VT = N->getValueType(0);
2717     if (VT != MVT::i32)
2718       break;
2719     unsigned Opc = (Subtarget->isThumb() && Subtarget->hasThumb2())
2720       ? ARM::t2MOVTi16
2721       : (Subtarget->hasV6T2Ops() ? ARM::MOVTi16 : 0);
2722     if (!Opc)
2723       break;
2724     SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2725     N1C = dyn_cast<ConstantSDNode>(N1);
2726     if (!N1C)
2727       break;
2728     if (N0.getOpcode() == ISD::OR && N0.getNode()->hasOneUse()) {
2729       SDValue N2 = N0.getOperand(1);
2730       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2731       if (!N2C)
2732         break;
2733       unsigned N1CVal = N1C->getZExtValue();
2734       unsigned N2CVal = N2C->getZExtValue();
2735       if ((N1CVal & 0xffff0000U) == (N2CVal & 0xffff0000U) &&
2736           (N1CVal & 0xffffU) == 0xffffU &&
2737           (N2CVal & 0xffffU) == 0x0U) {
2738         SDValue Imm16 = CurDAG->getTargetConstant((N2CVal & 0xFFFF0000U) >> 16,
2739                                                   dl, MVT::i32);
2740         SDValue Ops[] = { N0.getOperand(0), Imm16,
2741                           getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32) };
2742         ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
2743         return;
2744       }
2745     }
2746 
2747     break;
2748   }
2749   case ARMISD::UMAAL: {
2750     unsigned Opc = Subtarget->isThumb() ? ARM::t2UMAAL : ARM::UMAAL;
2751     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
2752                       N->getOperand(2), N->getOperand(3),
2753                       getAL(CurDAG, dl),
2754                       CurDAG->getRegister(0, MVT::i32) };
2755     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::i32, Ops));
2756     return;
2757   }
2758   case ARMISD::UMLAL:{
2759     if (Subtarget->isThumb()) {
2760       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
2761                         N->getOperand(3), getAL(CurDAG, dl),
2762                         CurDAG->getRegister(0, MVT::i32)};
2763       ReplaceNode(
2764           N, CurDAG->getMachineNode(ARM::t2UMLAL, dl, MVT::i32, MVT::i32, Ops));
2765       return;
2766     }else{
2767       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
2768                         N->getOperand(3), getAL(CurDAG, dl),
2769                         CurDAG->getRegister(0, MVT::i32),
2770                         CurDAG->getRegister(0, MVT::i32) };
2771       ReplaceNode(N, CurDAG->getMachineNode(
2772                          Subtarget->hasV6Ops() ? ARM::UMLAL : ARM::UMLALv5, dl,
2773                          MVT::i32, MVT::i32, Ops));
2774       return;
2775     }
2776   }
2777   case ARMISD::SMLAL:{
2778     if (Subtarget->isThumb()) {
2779       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
2780                         N->getOperand(3), getAL(CurDAG, dl),
2781                         CurDAG->getRegister(0, MVT::i32)};
2782       ReplaceNode(
2783           N, CurDAG->getMachineNode(ARM::t2SMLAL, dl, MVT::i32, MVT::i32, Ops));
2784       return;
2785     }else{
2786       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
2787                         N->getOperand(3), getAL(CurDAG, dl),
2788                         CurDAG->getRegister(0, MVT::i32),
2789                         CurDAG->getRegister(0, MVT::i32) };
2790       ReplaceNode(N, CurDAG->getMachineNode(
2791                          Subtarget->hasV6Ops() ? ARM::SMLAL : ARM::SMLALv5, dl,
2792                          MVT::i32, MVT::i32, Ops));
2793       return;
2794     }
2795   }
2796   case ARMISD::SUBE: {
2797     if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
2798       break;
2799     // Look for a pattern to match SMMLS
2800     // (sube a, (smul_loHi a, b), (subc 0, (smul_LOhi(a, b))))
2801     if (N->getOperand(1).getOpcode() != ISD::SMUL_LOHI ||
2802         N->getOperand(2).getOpcode() != ARMISD::SUBC ||
2803         !SDValue(N, 1).use_empty())
2804       break;
2805 
2806     if (Subtarget->isThumb())
2807       assert(Subtarget->hasThumb2() &&
2808              "This pattern should not be generated for Thumb");
2809 
2810     SDValue SmulLoHi = N->getOperand(1);
2811     SDValue Subc = N->getOperand(2);
2812     auto *Zero = dyn_cast<ConstantSDNode>(Subc.getOperand(0));
2813 
2814     if (!Zero || Zero->getZExtValue() != 0 ||
2815         Subc.getOperand(1) != SmulLoHi.getValue(0) ||
2816         N->getOperand(1) != SmulLoHi.getValue(1) ||
2817         N->getOperand(2) != Subc.getValue(1))
2818       break;
2819 
2820     unsigned Opc = Subtarget->isThumb2() ? ARM::t2SMMLS : ARM::SMMLS;
2821     SDValue Ops[] = { SmulLoHi.getOperand(0), SmulLoHi.getOperand(1),
2822                       N->getOperand(0), getAL(CurDAG, dl),
2823                       CurDAG->getRegister(0, MVT::i32) };
2824     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops));
2825     return;
2826   }
2827   case ISD::LOAD: {
2828     if (Subtarget->isThumb() && Subtarget->hasThumb2()) {
2829       if (tryT2IndexedLoad(N))
2830         return;
2831     } else if (Subtarget->isThumb()) {
2832       if (tryT1IndexedLoad(N))
2833         return;
2834     } else if (tryARMIndexedLoad(N))
2835       return;
2836     // Other cases are autogenerated.
2837     break;
2838   }
2839   case ARMISD::BRCOND: {
2840     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
2841     // Emits: (Bcc:void (bb:Other):$dst, (imm:i32):$cc)
2842     // Pattern complexity = 6  cost = 1  size = 0
2843 
2844     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
2845     // Emits: (tBcc:void (bb:Other):$dst, (imm:i32):$cc)
2846     // Pattern complexity = 6  cost = 1  size = 0
2847 
2848     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
2849     // Emits: (t2Bcc:void (bb:Other):$dst, (imm:i32):$cc)
2850     // Pattern complexity = 6  cost = 1  size = 0
2851 
2852     unsigned Opc = Subtarget->isThumb() ?
2853       ((Subtarget->hasThumb2()) ? ARM::t2Bcc : ARM::tBcc) : ARM::Bcc;
2854     SDValue Chain = N->getOperand(0);
2855     SDValue N1 = N->getOperand(1);
2856     SDValue N2 = N->getOperand(2);
2857     SDValue N3 = N->getOperand(3);
2858     SDValue InFlag = N->getOperand(4);
2859     assert(N1.getOpcode() == ISD::BasicBlock);
2860     assert(N2.getOpcode() == ISD::Constant);
2861     assert(N3.getOpcode() == ISD::Register);
2862 
2863     unsigned CC = (unsigned) cast<ConstantSDNode>(N2)->getZExtValue();
2864 
2865     if (InFlag.getOpcode() == ARMISD::CMPZ) {
2866       bool SwitchEQNEToPLMI;
2867       SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
2868       InFlag = N->getOperand(4);
2869 
2870       if (SwitchEQNEToPLMI) {
2871         switch ((ARMCC::CondCodes)CC) {
2872         default: llvm_unreachable("CMPZ must be either NE or EQ!");
2873         case ARMCC::NE:
2874           CC = (unsigned)ARMCC::MI;
2875           break;
2876         case ARMCC::EQ:
2877           CC = (unsigned)ARMCC::PL;
2878           break;
2879         }
2880       }
2881     }
2882 
2883     SDValue Tmp2 = CurDAG->getTargetConstant(CC, dl, MVT::i32);
2884     SDValue Ops[] = { N1, Tmp2, N3, Chain, InFlag };
2885     SDNode *ResNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
2886                                              MVT::Glue, Ops);
2887     Chain = SDValue(ResNode, 0);
2888     if (N->getNumValues() == 2) {
2889       InFlag = SDValue(ResNode, 1);
2890       ReplaceUses(SDValue(N, 1), InFlag);
2891     }
2892     ReplaceUses(SDValue(N, 0),
2893                 SDValue(Chain.getNode(), Chain.getResNo()));
2894     CurDAG->RemoveDeadNode(N);
2895     return;
2896   }
2897 
2898   case ARMISD::CMPZ: {
2899     // select (CMPZ X, #-C) -> (CMPZ (ADDS X, #C), #0)
2900     //   This allows us to avoid materializing the expensive negative constant.
2901     //   The CMPZ #0 is useless and will be peepholed away but we need to keep it
2902     //   for its glue output.
2903     SDValue X = N->getOperand(0);
2904     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1).getNode());
2905     if (C && C->getSExtValue() < 0 && Subtarget->isThumb()) {
2906       int64_t Addend = -C->getSExtValue();
2907 
2908       SDNode *Add = nullptr;
2909       // ADDS can be better than CMN if the immediate fits in a
2910       // 16-bit ADDS, which means either [0,256) for tADDi8 or [0,8) for tADDi3.
2911       // Outside that range we can just use a CMN which is 32-bit but has a
2912       // 12-bit immediate range.
2913       if (Addend < 1<<8) {
2914         if (Subtarget->isThumb2()) {
2915           SDValue Ops[] = { X, CurDAG->getTargetConstant(Addend, dl, MVT::i32),
2916                             getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
2917                             CurDAG->getRegister(0, MVT::i32) };
2918           Add = CurDAG->getMachineNode(ARM::t2ADDri, dl, MVT::i32, Ops);
2919         } else {
2920           unsigned Opc = (Addend < 1<<3) ? ARM::tADDi3 : ARM::tADDi8;
2921           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), X,
2922                            CurDAG->getTargetConstant(Addend, dl, MVT::i32),
2923                            getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
2924           Add = CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
2925         }
2926       }
2927       if (Add) {
2928         SDValue Ops2[] = {SDValue(Add, 0), CurDAG->getConstant(0, dl, MVT::i32)};
2929         CurDAG->MorphNodeTo(N, ARMISD::CMPZ, CurDAG->getVTList(MVT::Glue), Ops2);
2930       }
2931     }
2932     // Other cases are autogenerated.
2933     break;
2934   }
2935 
2936   case ARMISD::CMOV: {
2937     SDValue InFlag = N->getOperand(4);
2938 
2939     if (InFlag.getOpcode() == ARMISD::CMPZ) {
2940       bool SwitchEQNEToPLMI;
2941       SelectCMPZ(InFlag.getNode(), SwitchEQNEToPLMI);
2942 
2943       if (SwitchEQNEToPLMI) {
2944         SDValue ARMcc = N->getOperand(2);
2945         ARMCC::CondCodes CC =
2946           (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
2947 
2948         switch (CC) {
2949         default: llvm_unreachable("CMPZ must be either NE or EQ!");
2950         case ARMCC::NE:
2951           CC = ARMCC::MI;
2952           break;
2953         case ARMCC::EQ:
2954           CC = ARMCC::PL;
2955           break;
2956         }
2957         SDValue NewARMcc = CurDAG->getConstant((unsigned)CC, dl, MVT::i32);
2958         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), NewARMcc,
2959                          N->getOperand(3), N->getOperand(4)};
2960         CurDAG->MorphNodeTo(N, ARMISD::CMOV, N->getVTList(), Ops);
2961       }
2962 
2963     }
2964     // Other cases are autogenerated.
2965     break;
2966   }
2967 
2968   case ARMISD::VZIP: {
2969     unsigned Opc = 0;
2970     EVT VT = N->getValueType(0);
2971     switch (VT.getSimpleVT().SimpleTy) {
2972     default: return;
2973     case MVT::v8i8:  Opc = ARM::VZIPd8; break;
2974     case MVT::v4i16: Opc = ARM::VZIPd16; break;
2975     case MVT::v2f32:
2976     // vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
2977     case MVT::v2i32: Opc = ARM::VTRNd32; break;
2978     case MVT::v16i8: Opc = ARM::VZIPq8; break;
2979     case MVT::v8i16: Opc = ARM::VZIPq16; break;
2980     case MVT::v4f32:
2981     case MVT::v4i32: Opc = ARM::VZIPq32; break;
2982     }
2983     SDValue Pred = getAL(CurDAG, dl);
2984     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
2985     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
2986     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
2987     return;
2988   }
2989   case ARMISD::VUZP: {
2990     unsigned Opc = 0;
2991     EVT VT = N->getValueType(0);
2992     switch (VT.getSimpleVT().SimpleTy) {
2993     default: return;
2994     case MVT::v8i8:  Opc = ARM::VUZPd8; break;
2995     case MVT::v4i16: Opc = ARM::VUZPd16; break;
2996     case MVT::v2f32:
2997     // vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
2998     case MVT::v2i32: Opc = ARM::VTRNd32; break;
2999     case MVT::v16i8: Opc = ARM::VUZPq8; break;
3000     case MVT::v8i16: Opc = ARM::VUZPq16; break;
3001     case MVT::v4f32:
3002     case MVT::v4i32: Opc = ARM::VUZPq32; break;
3003     }
3004     SDValue Pred = getAL(CurDAG, dl);
3005     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
3006     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
3007     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
3008     return;
3009   }
3010   case ARMISD::VTRN: {
3011     unsigned Opc = 0;
3012     EVT VT = N->getValueType(0);
3013     switch (VT.getSimpleVT().SimpleTy) {
3014     default: return;
3015     case MVT::v8i8:  Opc = ARM::VTRNd8; break;
3016     case MVT::v4i16: Opc = ARM::VTRNd16; break;
3017     case MVT::v2f32:
3018     case MVT::v2i32: Opc = ARM::VTRNd32; break;
3019     case MVT::v16i8: Opc = ARM::VTRNq8; break;
3020     case MVT::v8i16: Opc = ARM::VTRNq16; break;
3021     case MVT::v4f32:
3022     case MVT::v4i32: Opc = ARM::VTRNq32; break;
3023     }
3024     SDValue Pred = getAL(CurDAG, dl);
3025     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
3026     SDValue Ops[] = { N->getOperand(0), N->getOperand(1), Pred, PredReg };
3027     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
3028     return;
3029   }
3030   case ARMISD::BUILD_VECTOR: {
3031     EVT VecVT = N->getValueType(0);
3032     EVT EltVT = VecVT.getVectorElementType();
3033     unsigned NumElts = VecVT.getVectorNumElements();
3034     if (EltVT == MVT::f64) {
3035       assert(NumElts == 2 && "unexpected type for BUILD_VECTOR");
3036       ReplaceNode(
3037           N, createDRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
3038       return;
3039     }
3040     assert(EltVT == MVT::f32 && "unexpected type for BUILD_VECTOR");
3041     if (NumElts == 2) {
3042       ReplaceNode(
3043           N, createSRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
3044       return;
3045     }
3046     assert(NumElts == 4 && "unexpected type for BUILD_VECTOR");
3047     ReplaceNode(N,
3048                 createQuadSRegsNode(VecVT, N->getOperand(0), N->getOperand(1),
3049                                     N->getOperand(2), N->getOperand(3)));
3050     return;
3051   }
3052 
3053   case ARMISD::VLD1DUP: {
3054     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8, ARM::VLD1DUPd16,
3055                                          ARM::VLD1DUPd32 };
3056     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8, ARM::VLD1DUPq16,
3057                                          ARM::VLD1DUPq32 };
3058     SelectVLDDup(N, false, 1, DOpcodes, QOpcodes);
3059     return;
3060   }
3061 
3062   case ARMISD::VLD2DUP: {
3063     static const uint16_t Opcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
3064                                         ARM::VLD2DUPd32 };
3065     SelectVLDDup(N, false, 2, Opcodes);
3066     return;
3067   }
3068 
3069   case ARMISD::VLD3DUP: {
3070     static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo,
3071                                         ARM::VLD3DUPd16Pseudo,
3072                                         ARM::VLD3DUPd32Pseudo };
3073     SelectVLDDup(N, false, 3, Opcodes);
3074     return;
3075   }
3076 
3077   case ARMISD::VLD4DUP: {
3078     static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo,
3079                                         ARM::VLD4DUPd16Pseudo,
3080                                         ARM::VLD4DUPd32Pseudo };
3081     SelectVLDDup(N, false, 4, Opcodes);
3082     return;
3083   }
3084 
3085   case ARMISD::VLD1DUP_UPD: {
3086     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8wb_fixed,
3087                                          ARM::VLD1DUPd16wb_fixed,
3088                                          ARM::VLD1DUPd32wb_fixed };
3089     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8wb_fixed,
3090                                          ARM::VLD1DUPq16wb_fixed,
3091                                          ARM::VLD1DUPq32wb_fixed };
3092     SelectVLDDup(N, true, 1, DOpcodes, QOpcodes);
3093     return;
3094   }
3095 
3096   case ARMISD::VLD2DUP_UPD: {
3097     static const uint16_t Opcodes[] = { ARM::VLD2DUPd8wb_fixed,
3098                                         ARM::VLD2DUPd16wb_fixed,
3099                                         ARM::VLD2DUPd32wb_fixed };
3100     SelectVLDDup(N, true, 2, Opcodes);
3101     return;
3102   }
3103 
3104   case ARMISD::VLD3DUP_UPD: {
3105     static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo_UPD,
3106                                         ARM::VLD3DUPd16Pseudo_UPD,
3107                                         ARM::VLD3DUPd32Pseudo_UPD };
3108     SelectVLDDup(N, true, 3, Opcodes);
3109     return;
3110   }
3111 
3112   case ARMISD::VLD4DUP_UPD: {
3113     static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo_UPD,
3114                                         ARM::VLD4DUPd16Pseudo_UPD,
3115                                         ARM::VLD4DUPd32Pseudo_UPD };
3116     SelectVLDDup(N, true, 4, Opcodes);
3117     return;
3118   }
3119 
3120   case ARMISD::VLD1_UPD: {
3121     static const uint16_t DOpcodes[] = { ARM::VLD1d8wb_fixed,
3122                                          ARM::VLD1d16wb_fixed,
3123                                          ARM::VLD1d32wb_fixed,
3124                                          ARM::VLD1d64wb_fixed };
3125     static const uint16_t QOpcodes[] = { ARM::VLD1q8wb_fixed,
3126                                          ARM::VLD1q16wb_fixed,
3127                                          ARM::VLD1q32wb_fixed,
3128                                          ARM::VLD1q64wb_fixed };
3129     SelectVLD(N, true, 1, DOpcodes, QOpcodes, nullptr);
3130     return;
3131   }
3132 
3133   case ARMISD::VLD2_UPD: {
3134     static const uint16_t DOpcodes[] = { ARM::VLD2d8wb_fixed,
3135                                          ARM::VLD2d16wb_fixed,
3136                                          ARM::VLD2d32wb_fixed,
3137                                          ARM::VLD1q64wb_fixed};
3138     static const uint16_t QOpcodes[] = { ARM::VLD2q8PseudoWB_fixed,
3139                                          ARM::VLD2q16PseudoWB_fixed,
3140                                          ARM::VLD2q32PseudoWB_fixed };
3141     SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
3142     return;
3143   }
3144 
3145   case ARMISD::VLD3_UPD: {
3146     static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo_UPD,
3147                                          ARM::VLD3d16Pseudo_UPD,
3148                                          ARM::VLD3d32Pseudo_UPD,
3149                                          ARM::VLD1d64TPseudoWB_fixed};
3150     static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
3151                                           ARM::VLD3q16Pseudo_UPD,
3152                                           ARM::VLD3q32Pseudo_UPD };
3153     static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo_UPD,
3154                                           ARM::VLD3q16oddPseudo_UPD,
3155                                           ARM::VLD3q32oddPseudo_UPD };
3156     SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
3157     return;
3158   }
3159 
3160   case ARMISD::VLD4_UPD: {
3161     static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo_UPD,
3162                                          ARM::VLD4d16Pseudo_UPD,
3163                                          ARM::VLD4d32Pseudo_UPD,
3164                                          ARM::VLD1d64QPseudoWB_fixed};
3165     static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
3166                                           ARM::VLD4q16Pseudo_UPD,
3167                                           ARM::VLD4q32Pseudo_UPD };
3168     static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo_UPD,
3169                                           ARM::VLD4q16oddPseudo_UPD,
3170                                           ARM::VLD4q32oddPseudo_UPD };
3171     SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
3172     return;
3173   }
3174 
3175   case ARMISD::VLD2LN_UPD: {
3176     static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo_UPD,
3177                                          ARM::VLD2LNd16Pseudo_UPD,
3178                                          ARM::VLD2LNd32Pseudo_UPD };
3179     static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo_UPD,
3180                                          ARM::VLD2LNq32Pseudo_UPD };
3181     SelectVLDSTLane(N, true, true, 2, DOpcodes, QOpcodes);
3182     return;
3183   }
3184 
3185   case ARMISD::VLD3LN_UPD: {
3186     static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo_UPD,
3187                                          ARM::VLD3LNd16Pseudo_UPD,
3188                                          ARM::VLD3LNd32Pseudo_UPD };
3189     static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo_UPD,
3190                                          ARM::VLD3LNq32Pseudo_UPD };
3191     SelectVLDSTLane(N, true, true, 3, DOpcodes, QOpcodes);
3192     return;
3193   }
3194 
3195   case ARMISD::VLD4LN_UPD: {
3196     static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo_UPD,
3197                                          ARM::VLD4LNd16Pseudo_UPD,
3198                                          ARM::VLD4LNd32Pseudo_UPD };
3199     static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo_UPD,
3200                                          ARM::VLD4LNq32Pseudo_UPD };
3201     SelectVLDSTLane(N, true, true, 4, DOpcodes, QOpcodes);
3202     return;
3203   }
3204 
3205   case ARMISD::VST1_UPD: {
3206     static const uint16_t DOpcodes[] = { ARM::VST1d8wb_fixed,
3207                                          ARM::VST1d16wb_fixed,
3208                                          ARM::VST1d32wb_fixed,
3209                                          ARM::VST1d64wb_fixed };
3210     static const uint16_t QOpcodes[] = { ARM::VST1q8wb_fixed,
3211                                          ARM::VST1q16wb_fixed,
3212                                          ARM::VST1q32wb_fixed,
3213                                          ARM::VST1q64wb_fixed };
3214     SelectVST(N, true, 1, DOpcodes, QOpcodes, nullptr);
3215     return;
3216   }
3217 
3218   case ARMISD::VST2_UPD: {
3219     static const uint16_t DOpcodes[] = { ARM::VST2d8wb_fixed,
3220                                          ARM::VST2d16wb_fixed,
3221                                          ARM::VST2d32wb_fixed,
3222                                          ARM::VST1q64wb_fixed};
3223     static const uint16_t QOpcodes[] = { ARM::VST2q8PseudoWB_fixed,
3224                                          ARM::VST2q16PseudoWB_fixed,
3225                                          ARM::VST2q32PseudoWB_fixed };
3226     SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
3227     return;
3228   }
3229 
3230   case ARMISD::VST3_UPD: {
3231     static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo_UPD,
3232                                          ARM::VST3d16Pseudo_UPD,
3233                                          ARM::VST3d32Pseudo_UPD,
3234                                          ARM::VST1d64TPseudoWB_fixed};
3235     static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
3236                                           ARM::VST3q16Pseudo_UPD,
3237                                           ARM::VST3q32Pseudo_UPD };
3238     static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo_UPD,
3239                                           ARM::VST3q16oddPseudo_UPD,
3240                                           ARM::VST3q32oddPseudo_UPD };
3241     SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
3242     return;
3243   }
3244 
3245   case ARMISD::VST4_UPD: {
3246     static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo_UPD,
3247                                          ARM::VST4d16Pseudo_UPD,
3248                                          ARM::VST4d32Pseudo_UPD,
3249                                          ARM::VST1d64QPseudoWB_fixed};
3250     static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
3251                                           ARM::VST4q16Pseudo_UPD,
3252                                           ARM::VST4q32Pseudo_UPD };
3253     static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo_UPD,
3254                                           ARM::VST4q16oddPseudo_UPD,
3255                                           ARM::VST4q32oddPseudo_UPD };
3256     SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
3257     return;
3258   }
3259 
3260   case ARMISD::VST2LN_UPD: {
3261     static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo_UPD,
3262                                          ARM::VST2LNd16Pseudo_UPD,
3263                                          ARM::VST2LNd32Pseudo_UPD };
3264     static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo_UPD,
3265                                          ARM::VST2LNq32Pseudo_UPD };
3266     SelectVLDSTLane(N, false, true, 2, DOpcodes, QOpcodes);
3267     return;
3268   }
3269 
3270   case ARMISD::VST3LN_UPD: {
3271     static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo_UPD,
3272                                          ARM::VST3LNd16Pseudo_UPD,
3273                                          ARM::VST3LNd32Pseudo_UPD };
3274     static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo_UPD,
3275                                          ARM::VST3LNq32Pseudo_UPD };
3276     SelectVLDSTLane(N, false, true, 3, DOpcodes, QOpcodes);
3277     return;
3278   }
3279 
3280   case ARMISD::VST4LN_UPD: {
3281     static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo_UPD,
3282                                          ARM::VST4LNd16Pseudo_UPD,
3283                                          ARM::VST4LNd32Pseudo_UPD };
3284     static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo_UPD,
3285                                          ARM::VST4LNq32Pseudo_UPD };
3286     SelectVLDSTLane(N, false, true, 4, DOpcodes, QOpcodes);
3287     return;
3288   }
3289 
3290   case ISD::INTRINSIC_VOID:
3291   case ISD::INTRINSIC_W_CHAIN: {
3292     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3293     switch (IntNo) {
3294     default:
3295       break;
3296 
3297     case Intrinsic::arm_mrrc:
3298     case Intrinsic::arm_mrrc2: {
3299       SDLoc dl(N);
3300       SDValue Chain = N->getOperand(0);
3301       unsigned Opc;
3302 
3303       if (Subtarget->isThumb())
3304         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::t2MRRC : ARM::t2MRRC2);
3305       else
3306         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::MRRC : ARM::MRRC2);
3307 
3308       SmallVector<SDValue, 5> Ops;
3309       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(), dl)); /* coproc */
3310       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(3))->getZExtValue(), dl)); /* opc */
3311       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(4))->getZExtValue(), dl)); /* CRm */
3312 
3313       // The mrrc2 instruction in ARM doesn't allow predicates, the top 4 bits of the encoded
3314       // instruction will always be '1111' but it is possible in assembly language to specify
3315       // AL as a predicate to mrrc2 but it doesn't make any difference to the encoded instruction.
3316       if (Opc != ARM::MRRC2) {
3317         Ops.push_back(getAL(CurDAG, dl));
3318         Ops.push_back(CurDAG->getRegister(0, MVT::i32));
3319       }
3320 
3321       Ops.push_back(Chain);
3322 
3323       // Writes to two registers.
3324       const EVT RetType[] = {MVT::i32, MVT::i32, MVT::Other};
3325 
3326       ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, RetType, Ops));
3327       return;
3328     }
3329     case Intrinsic::arm_ldaexd:
3330     case Intrinsic::arm_ldrexd: {
3331       SDLoc dl(N);
3332       SDValue Chain = N->getOperand(0);
3333       SDValue MemAddr = N->getOperand(2);
3334       bool isThumb = Subtarget->isThumb() && Subtarget->hasV8MBaselineOps();
3335 
3336       bool IsAcquire = IntNo == Intrinsic::arm_ldaexd;
3337       unsigned NewOpc = isThumb ? (IsAcquire ? ARM::t2LDAEXD : ARM::t2LDREXD)
3338                                 : (IsAcquire ? ARM::LDAEXD : ARM::LDREXD);
3339 
3340       // arm_ldrexd returns a i64 value in {i32, i32}
3341       std::vector<EVT> ResTys;
3342       if (isThumb) {
3343         ResTys.push_back(MVT::i32);
3344         ResTys.push_back(MVT::i32);
3345       } else
3346         ResTys.push_back(MVT::Untyped);
3347       ResTys.push_back(MVT::Other);
3348 
3349       // Place arguments in the right order.
3350       SDValue Ops[] = {MemAddr, getAL(CurDAG, dl),
3351                        CurDAG->getRegister(0, MVT::i32), Chain};
3352       SDNode *Ld = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
3353       // Transfer memoperands.
3354       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3355       MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
3356       cast<MachineSDNode>(Ld)->setMemRefs(MemOp, MemOp + 1);
3357 
3358       // Remap uses.
3359       SDValue OutChain = isThumb ? SDValue(Ld, 2) : SDValue(Ld, 1);
3360       if (!SDValue(N, 0).use_empty()) {
3361         SDValue Result;
3362         if (isThumb)
3363           Result = SDValue(Ld, 0);
3364         else {
3365           SDValue SubRegIdx =
3366             CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
3367           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
3368               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
3369           Result = SDValue(ResNode,0);
3370         }
3371         ReplaceUses(SDValue(N, 0), Result);
3372       }
3373       if (!SDValue(N, 1).use_empty()) {
3374         SDValue Result;
3375         if (isThumb)
3376           Result = SDValue(Ld, 1);
3377         else {
3378           SDValue SubRegIdx =
3379             CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
3380           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
3381               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
3382           Result = SDValue(ResNode,0);
3383         }
3384         ReplaceUses(SDValue(N, 1), Result);
3385       }
3386       ReplaceUses(SDValue(N, 2), OutChain);
3387       CurDAG->RemoveDeadNode(N);
3388       return;
3389     }
3390     case Intrinsic::arm_stlexd:
3391     case Intrinsic::arm_strexd: {
3392       SDLoc dl(N);
3393       SDValue Chain = N->getOperand(0);
3394       SDValue Val0 = N->getOperand(2);
3395       SDValue Val1 = N->getOperand(3);
3396       SDValue MemAddr = N->getOperand(4);
3397 
3398       // Store exclusive double return a i32 value which is the return status
3399       // of the issued store.
3400       const EVT ResTys[] = {MVT::i32, MVT::Other};
3401 
3402       bool isThumb = Subtarget->isThumb() && Subtarget->hasThumb2();
3403       // Place arguments in the right order.
3404       SmallVector<SDValue, 7> Ops;
3405       if (isThumb) {
3406         Ops.push_back(Val0);
3407         Ops.push_back(Val1);
3408       } else
3409         // arm_strexd uses GPRPair.
3410         Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, Val0, Val1), 0));
3411       Ops.push_back(MemAddr);
3412       Ops.push_back(getAL(CurDAG, dl));
3413       Ops.push_back(CurDAG->getRegister(0, MVT::i32));
3414       Ops.push_back(Chain);
3415 
3416       bool IsRelease = IntNo == Intrinsic::arm_stlexd;
3417       unsigned NewOpc = isThumb ? (IsRelease ? ARM::t2STLEXD : ARM::t2STREXD)
3418                                 : (IsRelease ? ARM::STLEXD : ARM::STREXD);
3419 
3420       SDNode *St = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
3421       // Transfer memoperands.
3422       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3423       MemOp[0] = cast<MemIntrinsicSDNode>(N)->getMemOperand();
3424       cast<MachineSDNode>(St)->setMemRefs(MemOp, MemOp + 1);
3425 
3426       ReplaceNode(N, St);
3427       return;
3428     }
3429 
3430     case Intrinsic::arm_neon_vld1: {
3431       static const uint16_t DOpcodes[] = { ARM::VLD1d8, ARM::VLD1d16,
3432                                            ARM::VLD1d32, ARM::VLD1d64 };
3433       static const uint16_t QOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
3434                                            ARM::VLD1q32, ARM::VLD1q64};
3435       SelectVLD(N, false, 1, DOpcodes, QOpcodes, nullptr);
3436       return;
3437     }
3438 
3439     case Intrinsic::arm_neon_vld2: {
3440       static const uint16_t DOpcodes[] = { ARM::VLD2d8, ARM::VLD2d16,
3441                                            ARM::VLD2d32, ARM::VLD1q64 };
3442       static const uint16_t QOpcodes[] = { ARM::VLD2q8Pseudo, ARM::VLD2q16Pseudo,
3443                                            ARM::VLD2q32Pseudo };
3444       SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
3445       return;
3446     }
3447 
3448     case Intrinsic::arm_neon_vld3: {
3449       static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo,
3450                                            ARM::VLD3d16Pseudo,
3451                                            ARM::VLD3d32Pseudo,
3452                                            ARM::VLD1d64TPseudo };
3453       static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
3454                                             ARM::VLD3q16Pseudo_UPD,
3455                                             ARM::VLD3q32Pseudo_UPD };
3456       static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo,
3457                                             ARM::VLD3q16oddPseudo,
3458                                             ARM::VLD3q32oddPseudo };
3459       SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
3460       return;
3461     }
3462 
3463     case Intrinsic::arm_neon_vld4: {
3464       static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo,
3465                                            ARM::VLD4d16Pseudo,
3466                                            ARM::VLD4d32Pseudo,
3467                                            ARM::VLD1d64QPseudo };
3468       static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
3469                                             ARM::VLD4q16Pseudo_UPD,
3470                                             ARM::VLD4q32Pseudo_UPD };
3471       static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo,
3472                                             ARM::VLD4q16oddPseudo,
3473                                             ARM::VLD4q32oddPseudo };
3474       SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
3475       return;
3476     }
3477 
3478     case Intrinsic::arm_neon_vld2lane: {
3479       static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo,
3480                                            ARM::VLD2LNd16Pseudo,
3481                                            ARM::VLD2LNd32Pseudo };
3482       static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo,
3483                                            ARM::VLD2LNq32Pseudo };
3484       SelectVLDSTLane(N, true, false, 2, DOpcodes, QOpcodes);
3485       return;
3486     }
3487 
3488     case Intrinsic::arm_neon_vld3lane: {
3489       static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo,
3490                                            ARM::VLD3LNd16Pseudo,
3491                                            ARM::VLD3LNd32Pseudo };
3492       static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo,
3493                                            ARM::VLD3LNq32Pseudo };
3494       SelectVLDSTLane(N, true, false, 3, DOpcodes, QOpcodes);
3495       return;
3496     }
3497 
3498     case Intrinsic::arm_neon_vld4lane: {
3499       static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo,
3500                                            ARM::VLD4LNd16Pseudo,
3501                                            ARM::VLD4LNd32Pseudo };
3502       static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo,
3503                                            ARM::VLD4LNq32Pseudo };
3504       SelectVLDSTLane(N, true, false, 4, DOpcodes, QOpcodes);
3505       return;
3506     }
3507 
3508     case Intrinsic::arm_neon_vst1: {
3509       static const uint16_t DOpcodes[] = { ARM::VST1d8, ARM::VST1d16,
3510                                            ARM::VST1d32, ARM::VST1d64 };
3511       static const uint16_t QOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
3512                                            ARM::VST1q32, ARM::VST1q64 };
3513       SelectVST(N, false, 1, DOpcodes, QOpcodes, nullptr);
3514       return;
3515     }
3516 
3517     case Intrinsic::arm_neon_vst2: {
3518       static const uint16_t DOpcodes[] = { ARM::VST2d8, ARM::VST2d16,
3519                                            ARM::VST2d32, ARM::VST1q64 };
3520       static const uint16_t QOpcodes[] = { ARM::VST2q8Pseudo, ARM::VST2q16Pseudo,
3521                                            ARM::VST2q32Pseudo };
3522       SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
3523       return;
3524     }
3525 
3526     case Intrinsic::arm_neon_vst3: {
3527       static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo,
3528                                            ARM::VST3d16Pseudo,
3529                                            ARM::VST3d32Pseudo,
3530                                            ARM::VST1d64TPseudo };
3531       static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
3532                                             ARM::VST3q16Pseudo_UPD,
3533                                             ARM::VST3q32Pseudo_UPD };
3534       static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo,
3535                                             ARM::VST3q16oddPseudo,
3536                                             ARM::VST3q32oddPseudo };
3537       SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
3538       return;
3539     }
3540 
3541     case Intrinsic::arm_neon_vst4: {
3542       static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo,
3543                                            ARM::VST4d16Pseudo,
3544                                            ARM::VST4d32Pseudo,
3545                                            ARM::VST1d64QPseudo };
3546       static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
3547                                             ARM::VST4q16Pseudo_UPD,
3548                                             ARM::VST4q32Pseudo_UPD };
3549       static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo,
3550                                             ARM::VST4q16oddPseudo,
3551                                             ARM::VST4q32oddPseudo };
3552       SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
3553       return;
3554     }
3555 
3556     case Intrinsic::arm_neon_vst2lane: {
3557       static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo,
3558                                            ARM::VST2LNd16Pseudo,
3559                                            ARM::VST2LNd32Pseudo };
3560       static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo,
3561                                            ARM::VST2LNq32Pseudo };
3562       SelectVLDSTLane(N, false, false, 2, DOpcodes, QOpcodes);
3563       return;
3564     }
3565 
3566     case Intrinsic::arm_neon_vst3lane: {
3567       static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo,
3568                                            ARM::VST3LNd16Pseudo,
3569                                            ARM::VST3LNd32Pseudo };
3570       static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo,
3571                                            ARM::VST3LNq32Pseudo };
3572       SelectVLDSTLane(N, false, false, 3, DOpcodes, QOpcodes);
3573       return;
3574     }
3575 
3576     case Intrinsic::arm_neon_vst4lane: {
3577       static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo,
3578                                            ARM::VST4LNd16Pseudo,
3579                                            ARM::VST4LNd32Pseudo };
3580       static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo,
3581                                            ARM::VST4LNq32Pseudo };
3582       SelectVLDSTLane(N, false, false, 4, DOpcodes, QOpcodes);
3583       return;
3584     }
3585     }
3586     break;
3587   }
3588 
3589   case ISD::ATOMIC_CMP_SWAP:
3590     SelectCMP_SWAP(N);
3591     return;
3592   }
3593 
3594   SelectCode(N);
3595 }
3596 
3597 // Inspect a register string of the form
3598 // cp<coprocessor>:<opc1>:c<CRn>:c<CRm>:<opc2> (32bit) or
3599 // cp<coprocessor>:<opc1>:c<CRm> (64bit) inspect the fields of the string
3600 // and obtain the integer operands from them, adding these operands to the
3601 // provided vector.
3602 static void getIntOperandsFromRegisterString(StringRef RegString,
3603                                              SelectionDAG *CurDAG,
3604                                              const SDLoc &DL,
3605                                              std::vector<SDValue> &Ops) {
3606   SmallVector<StringRef, 5> Fields;
3607   RegString.split(Fields, ':');
3608 
3609   if (Fields.size() > 1) {
3610     bool AllIntFields = true;
3611 
3612     for (StringRef Field : Fields) {
3613       // Need to trim out leading 'cp' characters and get the integer field.
3614       unsigned IntField;
3615       AllIntFields &= !Field.trim("CPcp").getAsInteger(10, IntField);
3616       Ops.push_back(CurDAG->getTargetConstant(IntField, DL, MVT::i32));
3617     }
3618 
3619     assert(AllIntFields &&
3620             "Unexpected non-integer value in special register string.");
3621   }
3622 }
3623 
3624 // Maps a Banked Register string to its mask value. The mask value returned is
3625 // for use in the MRSbanked / MSRbanked instruction nodes as the Banked Register
3626 // mask operand, which expresses which register is to be used, e.g. r8, and in
3627 // which mode it is to be used, e.g. usr. Returns -1 to signify that the string
3628 // was invalid.
3629 static inline int getBankedRegisterMask(StringRef RegString) {
3630   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegString.lower());
3631   if (!TheReg)
3632      return -1;
3633   return TheReg->Encoding;
3634 }
3635 
3636 // The flags here are common to those allowed for apsr in the A class cores and
3637 // those allowed for the special registers in the M class cores. Returns a
3638 // value representing which flags were present, -1 if invalid.
3639 static inline int getMClassFlagsMask(StringRef Flags) {
3640   return StringSwitch<int>(Flags)
3641           .Case("", 0x2) // no flags means nzcvq for psr registers, and 0x2 is
3642                          // correct when flags are not permitted
3643           .Case("g", 0x1)
3644           .Case("nzcvq", 0x2)
3645           .Case("nzcvqg", 0x3)
3646           .Default(-1);
3647 }
3648 
3649 // Maps MClass special registers string to its value for use in the
3650 // t2MRS_M/t2MSR_M instruction nodes as the SYSm value operand.
3651 // Returns -1 to signify that the string was invalid.
3652 static int getMClassRegisterMask(StringRef Reg, const ARMSubtarget *Subtarget) {
3653   auto TheReg = ARMSysReg::lookupMClassSysRegByName(Reg);
3654   const FeatureBitset &FeatureBits = Subtarget->getFeatureBits();
3655   if (!TheReg || !TheReg->hasRequiredFeatures(FeatureBits))
3656     return -1;
3657   return (int)(TheReg->Encoding & 0xFFF); // SYSm value
3658 }
3659 
3660 static int getARClassRegisterMask(StringRef Reg, StringRef Flags) {
3661   // The mask operand contains the special register (R Bit) in bit 4, whether
3662   // the register is spsr (R bit is 1) or one of cpsr/apsr (R bit is 0), and
3663   // bits 3-0 contains the fields to be accessed in the special register, set by
3664   // the flags provided with the register.
3665   int Mask = 0;
3666   if (Reg == "apsr") {
3667     // The flags permitted for apsr are the same flags that are allowed in
3668     // M class registers. We get the flag value and then shift the flags into
3669     // the correct place to combine with the mask.
3670     Mask = getMClassFlagsMask(Flags);
3671     if (Mask == -1)
3672       return -1;
3673     return Mask << 2;
3674   }
3675 
3676   if (Reg != "cpsr" && Reg != "spsr") {
3677     return -1;
3678   }
3679 
3680   // This is the same as if the flags were "fc"
3681   if (Flags.empty() || Flags == "all")
3682     return Mask | 0x9;
3683 
3684   // Inspect the supplied flags string and set the bits in the mask for
3685   // the relevant and valid flags allowed for cpsr and spsr.
3686   for (char Flag : Flags) {
3687     int FlagVal;
3688     switch (Flag) {
3689       case 'c':
3690         FlagVal = 0x1;
3691         break;
3692       case 'x':
3693         FlagVal = 0x2;
3694         break;
3695       case 's':
3696         FlagVal = 0x4;
3697         break;
3698       case 'f':
3699         FlagVal = 0x8;
3700         break;
3701       default:
3702         FlagVal = 0;
3703     }
3704 
3705     // This avoids allowing strings where the same flag bit appears twice.
3706     if (!FlagVal || (Mask & FlagVal))
3707       return -1;
3708     Mask |= FlagVal;
3709   }
3710 
3711   // If the register is spsr then we need to set the R bit.
3712   if (Reg == "spsr")
3713     Mask |= 0x10;
3714 
3715   return Mask;
3716 }
3717 
3718 // Lower the read_register intrinsic to ARM specific DAG nodes
3719 // using the supplied metadata string to select the instruction node to use
3720 // and the registers/masks to construct as operands for the node.
3721 bool ARMDAGToDAGISel::tryReadRegister(SDNode *N){
3722   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
3723   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
3724   bool IsThumb2 = Subtarget->isThumb2();
3725   SDLoc DL(N);
3726 
3727   std::vector<SDValue> Ops;
3728   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
3729 
3730   if (!Ops.empty()) {
3731     // If the special register string was constructed of fields (as defined
3732     // in the ACLE) then need to lower to MRC node (32 bit) or
3733     // MRRC node(64 bit), we can make the distinction based on the number of
3734     // operands we have.
3735     unsigned Opcode;
3736     SmallVector<EVT, 3> ResTypes;
3737     if (Ops.size() == 5){
3738       Opcode = IsThumb2 ? ARM::t2MRC : ARM::MRC;
3739       ResTypes.append({ MVT::i32, MVT::Other });
3740     } else {
3741       assert(Ops.size() == 3 &&
3742               "Invalid number of fields in special register string.");
3743       Opcode = IsThumb2 ? ARM::t2MRRC : ARM::MRRC;
3744       ResTypes.append({ MVT::i32, MVT::i32, MVT::Other });
3745     }
3746 
3747     Ops.push_back(getAL(CurDAG, DL));
3748     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
3749     Ops.push_back(N->getOperand(0));
3750     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, ResTypes, Ops));
3751     return true;
3752   }
3753 
3754   std::string SpecialReg = RegString->getString().lower();
3755 
3756   int BankedReg = getBankedRegisterMask(SpecialReg);
3757   if (BankedReg != -1) {
3758     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32),
3759             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3760             N->getOperand(0) };
3761     ReplaceNode(
3762         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSbanked : ARM::MRSbanked,
3763                                   DL, MVT::i32, MVT::Other, Ops));
3764     return true;
3765   }
3766 
3767   // The VFP registers are read by creating SelectionDAG nodes with opcodes
3768   // corresponding to the register that is being read from. So we switch on the
3769   // string to find which opcode we need to use.
3770   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
3771                     .Case("fpscr", ARM::VMRS)
3772                     .Case("fpexc", ARM::VMRS_FPEXC)
3773                     .Case("fpsid", ARM::VMRS_FPSID)
3774                     .Case("mvfr0", ARM::VMRS_MVFR0)
3775                     .Case("mvfr1", ARM::VMRS_MVFR1)
3776                     .Case("mvfr2", ARM::VMRS_MVFR2)
3777                     .Case("fpinst", ARM::VMRS_FPINST)
3778                     .Case("fpinst2", ARM::VMRS_FPINST2)
3779                     .Default(0);
3780 
3781   // If an opcode was found then we can lower the read to a VFP instruction.
3782   if (Opcode) {
3783     if (!Subtarget->hasVFP2())
3784       return false;
3785     if (Opcode == ARM::VMRS_MVFR2 && !Subtarget->hasFPARMv8())
3786       return false;
3787 
3788     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3789             N->getOperand(0) };
3790     ReplaceNode(N,
3791                 CurDAG->getMachineNode(Opcode, DL, MVT::i32, MVT::Other, Ops));
3792     return true;
3793   }
3794 
3795   // If the target is M Class then need to validate that the register string
3796   // is an acceptable value, so check that a mask can be constructed from the
3797   // string.
3798   if (Subtarget->isMClass()) {
3799     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
3800     if (SYSmValue == -1)
3801       return false;
3802 
3803     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
3804                       getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3805                       N->getOperand(0) };
3806     ReplaceNode(
3807         N, CurDAG->getMachineNode(ARM::t2MRS_M, DL, MVT::i32, MVT::Other, Ops));
3808     return true;
3809   }
3810 
3811   // Here we know the target is not M Class so we need to check if it is one
3812   // of the remaining possible values which are apsr, cpsr or spsr.
3813   if (SpecialReg == "apsr" || SpecialReg == "cpsr") {
3814     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3815             N->getOperand(0) };
3816     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRS_AR : ARM::MRS,
3817                                           DL, MVT::i32, MVT::Other, Ops));
3818     return true;
3819   }
3820 
3821   if (SpecialReg == "spsr") {
3822     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3823             N->getOperand(0) };
3824     ReplaceNode(
3825         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSsys_AR : ARM::MRSsys, DL,
3826                                   MVT::i32, MVT::Other, Ops));
3827     return true;
3828   }
3829 
3830   return false;
3831 }
3832 
3833 // Lower the write_register intrinsic to ARM specific DAG nodes
3834 // using the supplied metadata string to select the instruction node to use
3835 // and the registers/masks to use in the nodes
3836 bool ARMDAGToDAGISel::tryWriteRegister(SDNode *N){
3837   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
3838   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
3839   bool IsThumb2 = Subtarget->isThumb2();
3840   SDLoc DL(N);
3841 
3842   std::vector<SDValue> Ops;
3843   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
3844 
3845   if (!Ops.empty()) {
3846     // If the special register string was constructed of fields (as defined
3847     // in the ACLE) then need to lower to MCR node (32 bit) or
3848     // MCRR node(64 bit), we can make the distinction based on the number of
3849     // operands we have.
3850     unsigned Opcode;
3851     if (Ops.size() == 5) {
3852       Opcode = IsThumb2 ? ARM::t2MCR : ARM::MCR;
3853       Ops.insert(Ops.begin()+2, N->getOperand(2));
3854     } else {
3855       assert(Ops.size() == 3 &&
3856               "Invalid number of fields in special register string.");
3857       Opcode = IsThumb2 ? ARM::t2MCRR : ARM::MCRR;
3858       SDValue WriteValue[] = { N->getOperand(2), N->getOperand(3) };
3859       Ops.insert(Ops.begin()+2, WriteValue, WriteValue+2);
3860     }
3861 
3862     Ops.push_back(getAL(CurDAG, DL));
3863     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
3864     Ops.push_back(N->getOperand(0));
3865 
3866     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
3867     return true;
3868   }
3869 
3870   std::string SpecialReg = RegString->getString().lower();
3871   int BankedReg = getBankedRegisterMask(SpecialReg);
3872   if (BankedReg != -1) {
3873     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32), N->getOperand(2),
3874             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3875             N->getOperand(0) };
3876     ReplaceNode(
3877         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSRbanked : ARM::MSRbanked,
3878                                   DL, MVT::Other, Ops));
3879     return true;
3880   }
3881 
3882   // The VFP registers are written to by creating SelectionDAG nodes with
3883   // opcodes corresponding to the register that is being written. So we switch
3884   // on the string to find which opcode we need to use.
3885   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
3886                     .Case("fpscr", ARM::VMSR)
3887                     .Case("fpexc", ARM::VMSR_FPEXC)
3888                     .Case("fpsid", ARM::VMSR_FPSID)
3889                     .Case("fpinst", ARM::VMSR_FPINST)
3890                     .Case("fpinst2", ARM::VMSR_FPINST2)
3891                     .Default(0);
3892 
3893   if (Opcode) {
3894     if (!Subtarget->hasVFP2())
3895       return false;
3896     Ops = { N->getOperand(2), getAL(CurDAG, DL),
3897             CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
3898     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
3899     return true;
3900   }
3901 
3902   std::pair<StringRef, StringRef> Fields;
3903   Fields = StringRef(SpecialReg).rsplit('_');
3904   std::string Reg = Fields.first.str();
3905   StringRef Flags = Fields.second;
3906 
3907   // If the target was M Class then need to validate the special register value
3908   // and retrieve the mask for use in the instruction node.
3909   if (Subtarget->isMClass()) {
3910     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
3911     if (SYSmValue == -1)
3912       return false;
3913 
3914     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
3915                       N->getOperand(2), getAL(CurDAG, DL),
3916                       CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
3917     ReplaceNode(N, CurDAG->getMachineNode(ARM::t2MSR_M, DL, MVT::Other, Ops));
3918     return true;
3919   }
3920 
3921   // We then check to see if a valid mask can be constructed for one of the
3922   // register string values permitted for the A and R class cores. These values
3923   // are apsr, spsr and cpsr; these are also valid on older cores.
3924   int Mask = getARClassRegisterMask(Reg, Flags);
3925   if (Mask != -1) {
3926     Ops = { CurDAG->getTargetConstant(Mask, DL, MVT::i32), N->getOperand(2),
3927             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
3928             N->getOperand(0) };
3929     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSR_AR : ARM::MSR,
3930                                           DL, MVT::Other, Ops));
3931     return true;
3932   }
3933 
3934   return false;
3935 }
3936 
3937 bool ARMDAGToDAGISel::tryInlineAsm(SDNode *N){
3938   std::vector<SDValue> AsmNodeOperands;
3939   unsigned Flag, Kind;
3940   bool Changed = false;
3941   unsigned NumOps = N->getNumOperands();
3942 
3943   // Normally, i64 data is bounded to two arbitrary GRPs for "%r" constraint.
3944   // However, some instrstions (e.g. ldrexd/strexd in ARM mode) require
3945   // (even/even+1) GPRs and use %n and %Hn to refer to the individual regs
3946   // respectively. Since there is no constraint to explicitly specify a
3947   // reg pair, we use GPRPair reg class for "%r" for 64-bit data. For Thumb,
3948   // the 64-bit data may be referred by H, Q, R modifiers, so we still pack
3949   // them into a GPRPair.
3950 
3951   SDLoc dl(N);
3952   SDValue Glue = N->getGluedNode() ? N->getOperand(NumOps-1)
3953                                    : SDValue(nullptr,0);
3954 
3955   SmallVector<bool, 8> OpChanged;
3956   // Glue node will be appended late.
3957   for(unsigned i = 0, e = N->getGluedNode() ? NumOps - 1 : NumOps; i < e; ++i) {
3958     SDValue op = N->getOperand(i);
3959     AsmNodeOperands.push_back(op);
3960 
3961     if (i < InlineAsm::Op_FirstOperand)
3962       continue;
3963 
3964     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(i))) {
3965       Flag = C->getZExtValue();
3966       Kind = InlineAsm::getKind(Flag);
3967     }
3968     else
3969       continue;
3970 
3971     // Immediate operands to inline asm in the SelectionDAG are modeled with
3972     // two operands. The first is a constant of value InlineAsm::Kind_Imm, and
3973     // the second is a constant with the value of the immediate. If we get here
3974     // and we have a Kind_Imm, skip the next operand, and continue.
3975     if (Kind == InlineAsm::Kind_Imm) {
3976       SDValue op = N->getOperand(++i);
3977       AsmNodeOperands.push_back(op);
3978       continue;
3979     }
3980 
3981     unsigned NumRegs = InlineAsm::getNumOperandRegisters(Flag);
3982     if (NumRegs)
3983       OpChanged.push_back(false);
3984 
3985     unsigned DefIdx = 0;
3986     bool IsTiedToChangedOp = false;
3987     // If it's a use that is tied with a previous def, it has no
3988     // reg class constraint.
3989     if (Changed && InlineAsm::isUseOperandTiedToDef(Flag, DefIdx))
3990       IsTiedToChangedOp = OpChanged[DefIdx];
3991 
3992     // Memory operands to inline asm in the SelectionDAG are modeled with two
3993     // operands: a constant of value InlineAsm::Kind_Mem followed by the input
3994     // operand. If we get here and we have a Kind_Mem, skip the next operand (so
3995     // it doesn't get misinterpreted), and continue. We do this here because
3996     // it's important to update the OpChanged array correctly before moving on.
3997     if (Kind == InlineAsm::Kind_Mem) {
3998       SDValue op = N->getOperand(++i);
3999       AsmNodeOperands.push_back(op);
4000       continue;
4001     }
4002 
4003     if (Kind != InlineAsm::Kind_RegUse && Kind != InlineAsm::Kind_RegDef
4004         && Kind != InlineAsm::Kind_RegDefEarlyClobber)
4005       continue;
4006 
4007     unsigned RC;
4008     bool HasRC = InlineAsm::hasRegClassConstraint(Flag, RC);
4009     if ((!IsTiedToChangedOp && (!HasRC || RC != ARM::GPRRegClassID))
4010         || NumRegs != 2)
4011       continue;
4012 
4013     assert((i+2 < NumOps) && "Invalid number of operands in inline asm");
4014     SDValue V0 = N->getOperand(i+1);
4015     SDValue V1 = N->getOperand(i+2);
4016     unsigned Reg0 = cast<RegisterSDNode>(V0)->getReg();
4017     unsigned Reg1 = cast<RegisterSDNode>(V1)->getReg();
4018     SDValue PairedReg;
4019     MachineRegisterInfo &MRI = MF->getRegInfo();
4020 
4021     if (Kind == InlineAsm::Kind_RegDef ||
4022         Kind == InlineAsm::Kind_RegDefEarlyClobber) {
4023       // Replace the two GPRs with 1 GPRPair and copy values from GPRPair to
4024       // the original GPRs.
4025 
4026       unsigned GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
4027       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
4028       SDValue Chain = SDValue(N,0);
4029 
4030       SDNode *GU = N->getGluedUser();
4031       SDValue RegCopy = CurDAG->getCopyFromReg(Chain, dl, GPVR, MVT::Untyped,
4032                                                Chain.getValue(1));
4033 
4034       // Extract values from a GPRPair reg and copy to the original GPR reg.
4035       SDValue Sub0 = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
4036                                                     RegCopy);
4037       SDValue Sub1 = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
4038                                                     RegCopy);
4039       SDValue T0 = CurDAG->getCopyToReg(Sub0, dl, Reg0, Sub0,
4040                                         RegCopy.getValue(1));
4041       SDValue T1 = CurDAG->getCopyToReg(Sub1, dl, Reg1, Sub1, T0.getValue(1));
4042 
4043       // Update the original glue user.
4044       std::vector<SDValue> Ops(GU->op_begin(), GU->op_end()-1);
4045       Ops.push_back(T1.getValue(1));
4046       CurDAG->UpdateNodeOperands(GU, Ops);
4047     }
4048     else {
4049       // For Kind  == InlineAsm::Kind_RegUse, we first copy two GPRs into a
4050       // GPRPair and then pass the GPRPair to the inline asm.
4051       SDValue Chain = AsmNodeOperands[InlineAsm::Op_InputChain];
4052 
4053       // As REG_SEQ doesn't take RegisterSDNode, we copy them first.
4054       SDValue T0 = CurDAG->getCopyFromReg(Chain, dl, Reg0, MVT::i32,
4055                                           Chain.getValue(1));
4056       SDValue T1 = CurDAG->getCopyFromReg(Chain, dl, Reg1, MVT::i32,
4057                                           T0.getValue(1));
4058       SDValue Pair = SDValue(createGPRPairNode(MVT::Untyped, T0, T1), 0);
4059 
4060       // Copy REG_SEQ into a GPRPair-typed VR and replace the original two
4061       // i32 VRs of inline asm with it.
4062       unsigned GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
4063       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
4064       Chain = CurDAG->getCopyToReg(T1, dl, GPVR, Pair, T1.getValue(1));
4065 
4066       AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
4067       Glue = Chain.getValue(1);
4068     }
4069 
4070     Changed = true;
4071 
4072     if(PairedReg.getNode()) {
4073       OpChanged[OpChanged.size() -1 ] = true;
4074       Flag = InlineAsm::getFlagWord(Kind, 1 /* RegNum*/);
4075       if (IsTiedToChangedOp)
4076         Flag = InlineAsm::getFlagWordForMatchingOp(Flag, DefIdx);
4077       else
4078         Flag = InlineAsm::getFlagWordForRegClass(Flag, ARM::GPRPairRegClassID);
4079       // Replace the current flag.
4080       AsmNodeOperands[AsmNodeOperands.size() -1] = CurDAG->getTargetConstant(
4081           Flag, dl, MVT::i32);
4082       // Add the new register node and skip the original two GPRs.
4083       AsmNodeOperands.push_back(PairedReg);
4084       // Skip the next two GPRs.
4085       i += 2;
4086     }
4087   }
4088 
4089   if (Glue.getNode())
4090     AsmNodeOperands.push_back(Glue);
4091   if (!Changed)
4092     return false;
4093 
4094   SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N),
4095       CurDAG->getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
4096   New->setNodeId(-1);
4097   ReplaceNode(N, New.getNode());
4098   return true;
4099 }
4100 
4101 
4102 bool ARMDAGToDAGISel::
4103 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
4104                              std::vector<SDValue> &OutOps) {
4105   switch(ConstraintID) {
4106   default:
4107     llvm_unreachable("Unexpected asm memory constraint");
4108   case InlineAsm::Constraint_i:
4109     // FIXME: It seems strange that 'i' is needed here since it's supposed to
4110     //        be an immediate and not a memory constraint.
4111     LLVM_FALLTHROUGH;
4112   case InlineAsm::Constraint_m:
4113   case InlineAsm::Constraint_o:
4114   case InlineAsm::Constraint_Q:
4115   case InlineAsm::Constraint_Um:
4116   case InlineAsm::Constraint_Un:
4117   case InlineAsm::Constraint_Uq:
4118   case InlineAsm::Constraint_Us:
4119   case InlineAsm::Constraint_Ut:
4120   case InlineAsm::Constraint_Uv:
4121   case InlineAsm::Constraint_Uy:
4122     // Require the address to be in a register.  That is safe for all ARM
4123     // variants and it is hard to do anything much smarter without knowing
4124     // how the operand is used.
4125     OutOps.push_back(Op);
4126     return false;
4127   }
4128   return true;
4129 }
4130 
4131 /// createARMISelDag - This pass converts a legalized DAG into a
4132 /// ARM-specific DAG, ready for instruction scheduling.
4133 ///
4134 FunctionPass *llvm::createARMISelDag(ARMBaseTargetMachine &TM,
4135                                      CodeGenOpt::Level OptLevel) {
4136   return new ARMDAGToDAGISel(TM, OptLevel);
4137 }
4138