1 //===- AArch64InstructionSelector.cpp ----------------------------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the targeting of the InstructionSelector class for
10 /// AArch64.
11 /// \todo This should be generated by TableGen.
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64GlobalISelUtils.h"
15 #include "AArch64InstrInfo.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64RegisterBankInfo.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "AArch64TargetMachine.h"
21 #include "AArch64GlobalISelUtils.h"
22 #include "MCTargetDesc/AArch64AddressingModes.h"
23 #include "MCTargetDesc/AArch64MCTargetDesc.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
26 #include "llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h"
27 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/TargetOpcodes.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/IR/IntrinsicsAArch64.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 
47 #define DEBUG_TYPE "aarch64-isel"
48 
49 using namespace llvm;
50 using namespace MIPatternMatch;
51 using namespace AArch64GISelUtils;
52 
53 namespace llvm {
54 class BlockFrequencyInfo;
55 class ProfileSummaryInfo;
56 }
57 
58 namespace {
59 
60 #define GET_GLOBALISEL_PREDICATE_BITSET
61 #include "AArch64GenGlobalISel.inc"
62 #undef GET_GLOBALISEL_PREDICATE_BITSET
63 
64 class AArch64InstructionSelector : public InstructionSelector {
65 public:
66   AArch64InstructionSelector(const AArch64TargetMachine &TM,
67                              const AArch64Subtarget &STI,
68                              const AArch64RegisterBankInfo &RBI);
69 
70   bool select(MachineInstr &I) override;
71   static const char *getName() { return DEBUG_TYPE; }
72 
73   void setupMF(MachineFunction &MF, GISelKnownBits *KB,
74                CodeGenCoverage &CoverageInfo, ProfileSummaryInfo *PSI,
75                BlockFrequencyInfo *BFI) override {
76     InstructionSelector::setupMF(MF, KB, CoverageInfo, PSI, BFI);
77 
78     // hasFnAttribute() is expensive to call on every BRCOND selection, so
79     // cache it here for each run of the selector.
80     ProduceNonFlagSettingCondBr =
81         !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
82     MFReturnAddr = Register();
83 
84     processPHIs(MF);
85   }
86 
87 private:
88   /// tblgen-erated 'select' implementation, used as the initial selector for
89   /// the patterns that don't require complex C++.
90   bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
91 
92   // A lowering phase that runs before any selection attempts.
93   // Returns true if the instruction was modified.
94   bool preISelLower(MachineInstr &I);
95 
96   // An early selection function that runs before the selectImpl() call.
97   bool earlySelect(MachineInstr &I) const;
98 
99   // Do some preprocessing of G_PHIs before we begin selection.
100   void processPHIs(MachineFunction &MF);
101 
102   bool earlySelectSHL(MachineInstr &I, MachineRegisterInfo &MRI) const;
103 
104   /// Eliminate same-sized cross-bank copies into stores before selectImpl().
105   bool contractCrossBankCopyIntoStore(MachineInstr &I,
106                                       MachineRegisterInfo &MRI);
107 
108   bool convertPtrAddToAdd(MachineInstr &I, MachineRegisterInfo &MRI);
109 
110   bool selectVaStartAAPCS(MachineInstr &I, MachineFunction &MF,
111                           MachineRegisterInfo &MRI) const;
112   bool selectVaStartDarwin(MachineInstr &I, MachineFunction &MF,
113                            MachineRegisterInfo &MRI) const;
114 
115   ///@{
116   /// Helper functions for selectCompareBranch.
117   bool selectCompareBranchFedByFCmp(MachineInstr &I, MachineInstr &FCmp,
118                                     MachineIRBuilder &MIB) const;
119   bool selectCompareBranchFedByICmp(MachineInstr &I, MachineInstr &ICmp,
120                                     MachineIRBuilder &MIB) const;
121   bool tryOptCompareBranchFedByICmp(MachineInstr &I, MachineInstr &ICmp,
122                                     MachineIRBuilder &MIB) const;
123   bool tryOptAndIntoCompareBranch(MachineInstr &AndInst, bool Invert,
124                                   MachineBasicBlock *DstMBB,
125                                   MachineIRBuilder &MIB) const;
126   ///@}
127 
128   bool selectCompareBranch(MachineInstr &I, MachineFunction &MF,
129                            MachineRegisterInfo &MRI) const;
130 
131   bool selectVectorAshrLshr(MachineInstr &I, MachineRegisterInfo &MRI) const;
132   bool selectVectorSHL(MachineInstr &I, MachineRegisterInfo &MRI) const;
133 
134   // Helper to generate an equivalent of scalar_to_vector into a new register,
135   // returned via 'Dst'.
136   MachineInstr *emitScalarToVector(unsigned EltSize,
137                                    const TargetRegisterClass *DstRC,
138                                    Register Scalar,
139                                    MachineIRBuilder &MIRBuilder) const;
140 
141   /// Emit a lane insert into \p DstReg, or a new vector register if None is
142   /// provided.
143   ///
144   /// The lane inserted into is defined by \p LaneIdx. The vector source
145   /// register is given by \p SrcReg. The register containing the element is
146   /// given by \p EltReg.
147   MachineInstr *emitLaneInsert(Optional<Register> DstReg, Register SrcReg,
148                                Register EltReg, unsigned LaneIdx,
149                                const RegisterBank &RB,
150                                MachineIRBuilder &MIRBuilder) const;
151 
152   /// Emit a sequence of instructions representing a constant \p CV for a
153   /// vector register \p Dst. (E.g. a MOV, or a load from a constant pool.)
154   ///
155   /// \returns the last instruction in the sequence on success, and nullptr
156   /// otherwise.
157   MachineInstr *emitConstantVector(Register Dst, Constant *CV,
158                                    MachineIRBuilder &MIRBuilder,
159                                    MachineRegisterInfo &MRI) const;
160 
161   bool selectInsertElt(MachineInstr &I, MachineRegisterInfo &MRI) const;
162   bool tryOptConstantBuildVec(MachineInstr &MI, LLT DstTy,
163                               MachineRegisterInfo &MRI) const;
164   bool selectBuildVector(MachineInstr &I, MachineRegisterInfo &MRI) const;
165   bool selectMergeValues(MachineInstr &I, MachineRegisterInfo &MRI) const;
166   bool selectUnmergeValues(MachineInstr &I, MachineRegisterInfo &MRI) const;
167 
168   bool selectShuffleVector(MachineInstr &I, MachineRegisterInfo &MRI) const;
169   bool selectExtractElt(MachineInstr &I, MachineRegisterInfo &MRI) const;
170   bool selectConcatVectors(MachineInstr &I, MachineRegisterInfo &MRI) const;
171   bool selectSplitVectorUnmerge(MachineInstr &I,
172                                 MachineRegisterInfo &MRI) const;
173   bool selectIntrinsicWithSideEffects(MachineInstr &I,
174                                       MachineRegisterInfo &MRI) const;
175   bool selectIntrinsic(MachineInstr &I, MachineRegisterInfo &MRI);
176   bool selectVectorICmp(MachineInstr &I, MachineRegisterInfo &MRI) const;
177   bool selectIntrinsicTrunc(MachineInstr &I, MachineRegisterInfo &MRI) const;
178   bool selectIntrinsicRound(MachineInstr &I, MachineRegisterInfo &MRI) const;
179   bool selectJumpTable(MachineInstr &I, MachineRegisterInfo &MRI) const;
180   bool selectBrJT(MachineInstr &I, MachineRegisterInfo &MRI) const;
181   bool selectTLSGlobalValue(MachineInstr &I, MachineRegisterInfo &MRI) const;
182   bool selectReduction(MachineInstr &I, MachineRegisterInfo &MRI) const;
183 
184   unsigned emitConstantPoolEntry(const Constant *CPVal,
185                                  MachineFunction &MF) const;
186   MachineInstr *emitLoadFromConstantPool(const Constant *CPVal,
187                                          MachineIRBuilder &MIRBuilder) const;
188 
189   // Emit a vector concat operation.
190   MachineInstr *emitVectorConcat(Optional<Register> Dst, Register Op1,
191                                  Register Op2,
192                                  MachineIRBuilder &MIRBuilder) const;
193 
194   // Emit an integer compare between LHS and RHS, which checks for Predicate.
195   MachineInstr *emitIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
196                                    MachineOperand &Predicate,
197                                    MachineIRBuilder &MIRBuilder) const;
198 
199   /// Emit a floating point comparison between \p LHS and \p RHS.
200   /// \p Pred if given is the intended predicate to use.
201   MachineInstr *emitFPCompare(Register LHS, Register RHS,
202                               MachineIRBuilder &MIRBuilder,
203                               Optional<CmpInst::Predicate> = None) const;
204 
205   MachineInstr *emitInstr(unsigned Opcode,
206                           std::initializer_list<llvm::DstOp> DstOps,
207                           std::initializer_list<llvm::SrcOp> SrcOps,
208                           MachineIRBuilder &MIRBuilder,
209                           const ComplexRendererFns &RenderFns = None) const;
210   /// Helper function to emit an add or sub instruction.
211   ///
212   /// \p AddrModeAndSizeToOpcode must contain each of the opcode variants above
213   /// in a specific order.
214   ///
215   /// Below is an example of the expected input to \p AddrModeAndSizeToOpcode.
216   ///
217   /// \code
218   ///   const std::array<std::array<unsigned, 2>, 4> Table {
219   ///    {{AArch64::ADDXri, AArch64::ADDWri},
220   ///     {AArch64::ADDXrs, AArch64::ADDWrs},
221   ///     {AArch64::ADDXrr, AArch64::ADDWrr},
222   ///     {AArch64::SUBXri, AArch64::SUBWri},
223   ///     {AArch64::ADDXrx, AArch64::ADDWrx}}};
224   /// \endcode
225   ///
226   /// Each row in the table corresponds to a different addressing mode. Each
227   /// column corresponds to a different register size.
228   ///
229   /// \attention Rows must be structured as follows:
230   ///   - Row 0: The ri opcode variants
231   ///   - Row 1: The rs opcode variants
232   ///   - Row 2: The rr opcode variants
233   ///   - Row 3: The ri opcode variants for negative immediates
234   ///   - Row 4: The rx opcode variants
235   ///
236   /// \attention Columns must be structured as follows:
237   ///   - Column 0: The 64-bit opcode variants
238   ///   - Column 1: The 32-bit opcode variants
239   ///
240   /// \p Dst is the destination register of the binop to emit.
241   /// \p LHS is the left-hand operand of the binop to emit.
242   /// \p RHS is the right-hand operand of the binop to emit.
243   MachineInstr *emitAddSub(
244       const std::array<std::array<unsigned, 2>, 5> &AddrModeAndSizeToOpcode,
245       Register Dst, MachineOperand &LHS, MachineOperand &RHS,
246       MachineIRBuilder &MIRBuilder) const;
247   MachineInstr *emitADD(Register DefReg, MachineOperand &LHS,
248                         MachineOperand &RHS,
249                         MachineIRBuilder &MIRBuilder) const;
250   MachineInstr *emitADDS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
251                          MachineIRBuilder &MIRBuilder) const;
252   MachineInstr *emitSUBS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
253                          MachineIRBuilder &MIRBuilder) const;
254   MachineInstr *emitCMN(MachineOperand &LHS, MachineOperand &RHS,
255                         MachineIRBuilder &MIRBuilder) const;
256   MachineInstr *emitTST(MachineOperand &LHS, MachineOperand &RHS,
257                         MachineIRBuilder &MIRBuilder) const;
258   MachineInstr *emitSelect(Register Dst, Register LHS, Register RHS,
259                            AArch64CC::CondCode CC,
260                            MachineIRBuilder &MIRBuilder) const;
261   MachineInstr *emitExtractVectorElt(Optional<Register> DstReg,
262                                      const RegisterBank &DstRB, LLT ScalarTy,
263                                      Register VecReg, unsigned LaneIdx,
264                                      MachineIRBuilder &MIRBuilder) const;
265 
266   /// Emit a CSet for an integer compare.
267   ///
268   /// \p DefReg and \p SrcReg are expected to be 32-bit scalar registers.
269   MachineInstr *emitCSetForICMP(Register DefReg, unsigned Pred,
270                                 MachineIRBuilder &MIRBuilder,
271                                 Register SrcReg = AArch64::WZR) const;
272   /// Emit a CSet for a FP compare.
273   ///
274   /// \p Dst is expected to be a 32-bit scalar register.
275   MachineInstr *emitCSetForFCmp(Register Dst, CmpInst::Predicate Pred,
276                                 MachineIRBuilder &MIRBuilder) const;
277 
278   /// Emit the overflow op for \p Opcode.
279   ///
280   /// \p Opcode is expected to be an overflow op's opcode, e.g. G_UADDO,
281   /// G_USUBO, etc.
282   std::pair<MachineInstr *, AArch64CC::CondCode>
283   emitOverflowOp(unsigned Opcode, Register Dst, MachineOperand &LHS,
284                  MachineOperand &RHS, MachineIRBuilder &MIRBuilder) const;
285 
286   /// Emit a TB(N)Z instruction which tests \p Bit in \p TestReg.
287   /// \p IsNegative is true if the test should be "not zero".
288   /// This will also optimize the test bit instruction when possible.
289   MachineInstr *emitTestBit(Register TestReg, uint64_t Bit, bool IsNegative,
290                             MachineBasicBlock *DstMBB,
291                             MachineIRBuilder &MIB) const;
292 
293   /// Emit a CB(N)Z instruction which branches to \p DestMBB.
294   MachineInstr *emitCBZ(Register CompareReg, bool IsNegative,
295                         MachineBasicBlock *DestMBB,
296                         MachineIRBuilder &MIB) const;
297 
298   // Equivalent to the i32shift_a and friends from AArch64InstrInfo.td.
299   // We use these manually instead of using the importer since it doesn't
300   // support SDNodeXForm.
301   ComplexRendererFns selectShiftA_32(const MachineOperand &Root) const;
302   ComplexRendererFns selectShiftB_32(const MachineOperand &Root) const;
303   ComplexRendererFns selectShiftA_64(const MachineOperand &Root) const;
304   ComplexRendererFns selectShiftB_64(const MachineOperand &Root) const;
305 
306   ComplexRendererFns select12BitValueWithLeftShift(uint64_t Immed) const;
307   ComplexRendererFns selectArithImmed(MachineOperand &Root) const;
308   ComplexRendererFns selectNegArithImmed(MachineOperand &Root) const;
309 
310   ComplexRendererFns selectAddrModeUnscaled(MachineOperand &Root,
311                                             unsigned Size) const;
312 
313   ComplexRendererFns selectAddrModeUnscaled8(MachineOperand &Root) const {
314     return selectAddrModeUnscaled(Root, 1);
315   }
316   ComplexRendererFns selectAddrModeUnscaled16(MachineOperand &Root) const {
317     return selectAddrModeUnscaled(Root, 2);
318   }
319   ComplexRendererFns selectAddrModeUnscaled32(MachineOperand &Root) const {
320     return selectAddrModeUnscaled(Root, 4);
321   }
322   ComplexRendererFns selectAddrModeUnscaled64(MachineOperand &Root) const {
323     return selectAddrModeUnscaled(Root, 8);
324   }
325   ComplexRendererFns selectAddrModeUnscaled128(MachineOperand &Root) const {
326     return selectAddrModeUnscaled(Root, 16);
327   }
328 
329   /// Helper to try to fold in a GISEL_ADD_LOW into an immediate, to be used
330   /// from complex pattern matchers like selectAddrModeIndexed().
331   ComplexRendererFns tryFoldAddLowIntoImm(MachineInstr &RootDef, unsigned Size,
332                                           MachineRegisterInfo &MRI) const;
333 
334   ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root,
335                                            unsigned Size) const;
336   template <int Width>
337   ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root) const {
338     return selectAddrModeIndexed(Root, Width / 8);
339   }
340 
341   bool isWorthFoldingIntoExtendedReg(MachineInstr &MI,
342                                      const MachineRegisterInfo &MRI) const;
343   ComplexRendererFns
344   selectAddrModeShiftedExtendXReg(MachineOperand &Root,
345                                   unsigned SizeInBytes) const;
346 
347   /// Returns a \p ComplexRendererFns which contains a base, offset, and whether
348   /// or not a shift + extend should be folded into an addressing mode. Returns
349   /// None when this is not profitable or possible.
350   ComplexRendererFns
351   selectExtendedSHL(MachineOperand &Root, MachineOperand &Base,
352                     MachineOperand &Offset, unsigned SizeInBytes,
353                     bool WantsExt) const;
354   ComplexRendererFns selectAddrModeRegisterOffset(MachineOperand &Root) const;
355   ComplexRendererFns selectAddrModeXRO(MachineOperand &Root,
356                                        unsigned SizeInBytes) const;
357   template <int Width>
358   ComplexRendererFns selectAddrModeXRO(MachineOperand &Root) const {
359     return selectAddrModeXRO(Root, Width / 8);
360   }
361 
362   ComplexRendererFns selectAddrModeWRO(MachineOperand &Root,
363                                        unsigned SizeInBytes) const;
364   template <int Width>
365   ComplexRendererFns selectAddrModeWRO(MachineOperand &Root) const {
366     return selectAddrModeWRO(Root, Width / 8);
367   }
368 
369   ComplexRendererFns selectShiftedRegister(MachineOperand &Root) const;
370 
371   ComplexRendererFns selectArithShiftedRegister(MachineOperand &Root) const {
372     return selectShiftedRegister(Root);
373   }
374 
375   ComplexRendererFns selectLogicalShiftedRegister(MachineOperand &Root) const {
376     // TODO: selectShiftedRegister should allow for rotates on logical shifts.
377     // For now, make them the same. The only difference between the two is that
378     // logical shifts are allowed to fold in rotates. Otherwise, these are
379     // functionally the same.
380     return selectShiftedRegister(Root);
381   }
382 
383   /// Given an extend instruction, determine the correct shift-extend type for
384   /// that instruction.
385   ///
386   /// If the instruction is going to be used in a load or store, pass
387   /// \p IsLoadStore = true.
388   AArch64_AM::ShiftExtendType
389   getExtendTypeForInst(MachineInstr &MI, MachineRegisterInfo &MRI,
390                        bool IsLoadStore = false) const;
391 
392   /// Move \p Reg to \p RC if \p Reg is not already on \p RC.
393   ///
394   /// \returns Either \p Reg if no change was necessary, or the new register
395   /// created by moving \p Reg.
396   ///
397   /// Note: This uses emitCopy right now.
398   Register moveScalarRegClass(Register Reg, const TargetRegisterClass &RC,
399                               MachineIRBuilder &MIB) const;
400 
401   ComplexRendererFns selectArithExtendedRegister(MachineOperand &Root) const;
402 
403   void renderTruncImm(MachineInstrBuilder &MIB, const MachineInstr &MI,
404                       int OpIdx = -1) const;
405   void renderLogicalImm32(MachineInstrBuilder &MIB, const MachineInstr &I,
406                           int OpIdx = -1) const;
407   void renderLogicalImm64(MachineInstrBuilder &MIB, const MachineInstr &I,
408                           int OpIdx = -1) const;
409   void renderFPImm16(MachineInstrBuilder &MIB, const MachineInstr &MI,
410                      int OpIdx = -1) const;
411   void renderFPImm32(MachineInstrBuilder &MIB, const MachineInstr &MI,
412                      int OpIdx = -1) const;
413   void renderFPImm64(MachineInstrBuilder &MIB, const MachineInstr &MI,
414                      int OpIdx = -1) const;
415 
416   // Materialize a GlobalValue or BlockAddress using a movz+movk sequence.
417   void materializeLargeCMVal(MachineInstr &I, const Value *V,
418                              unsigned OpFlags) const;
419 
420   // Optimization methods.
421   bool tryOptSelect(MachineInstr &MI) const;
422   MachineInstr *tryFoldIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
423                                       MachineOperand &Predicate,
424                                       MachineIRBuilder &MIRBuilder) const;
425 
426   /// Return true if \p MI is a load or store of \p NumBytes bytes.
427   bool isLoadStoreOfNumBytes(const MachineInstr &MI, unsigned NumBytes) const;
428 
429   /// Returns true if \p MI is guaranteed to have the high-half of a 64-bit
430   /// register zeroed out. In other words, the result of MI has been explicitly
431   /// zero extended.
432   bool isDef32(const MachineInstr &MI) const;
433 
434   const AArch64TargetMachine &TM;
435   const AArch64Subtarget &STI;
436   const AArch64InstrInfo &TII;
437   const AArch64RegisterInfo &TRI;
438   const AArch64RegisterBankInfo &RBI;
439 
440   bool ProduceNonFlagSettingCondBr = false;
441 
442   // Some cached values used during selection.
443   // We use LR as a live-in register, and we keep track of it here as it can be
444   // clobbered by calls.
445   Register MFReturnAddr;
446 
447 #define GET_GLOBALISEL_PREDICATES_DECL
448 #include "AArch64GenGlobalISel.inc"
449 #undef GET_GLOBALISEL_PREDICATES_DECL
450 
451 // We declare the temporaries used by selectImpl() in the class to minimize the
452 // cost of constructing placeholder values.
453 #define GET_GLOBALISEL_TEMPORARIES_DECL
454 #include "AArch64GenGlobalISel.inc"
455 #undef GET_GLOBALISEL_TEMPORARIES_DECL
456 };
457 
458 } // end anonymous namespace
459 
460 #define GET_GLOBALISEL_IMPL
461 #include "AArch64GenGlobalISel.inc"
462 #undef GET_GLOBALISEL_IMPL
463 
464 AArch64InstructionSelector::AArch64InstructionSelector(
465     const AArch64TargetMachine &TM, const AArch64Subtarget &STI,
466     const AArch64RegisterBankInfo &RBI)
467     : InstructionSelector(), TM(TM), STI(STI), TII(*STI.getInstrInfo()),
468       TRI(*STI.getRegisterInfo()), RBI(RBI),
469 #define GET_GLOBALISEL_PREDICATES_INIT
470 #include "AArch64GenGlobalISel.inc"
471 #undef GET_GLOBALISEL_PREDICATES_INIT
472 #define GET_GLOBALISEL_TEMPORARIES_INIT
473 #include "AArch64GenGlobalISel.inc"
474 #undef GET_GLOBALISEL_TEMPORARIES_INIT
475 {
476 }
477 
478 // FIXME: This should be target-independent, inferred from the types declared
479 // for each class in the bank.
480 static const TargetRegisterClass *
481 getRegClassForTypeOnBank(LLT Ty, const RegisterBank &RB,
482                          const RegisterBankInfo &RBI,
483                          bool GetAllRegSet = false) {
484   if (RB.getID() == AArch64::GPRRegBankID) {
485     if (Ty.getSizeInBits() <= 32)
486       return GetAllRegSet ? &AArch64::GPR32allRegClass
487                           : &AArch64::GPR32RegClass;
488     if (Ty.getSizeInBits() == 64)
489       return GetAllRegSet ? &AArch64::GPR64allRegClass
490                           : &AArch64::GPR64RegClass;
491     return nullptr;
492   }
493 
494   if (RB.getID() == AArch64::FPRRegBankID) {
495     if (Ty.getSizeInBits() <= 16)
496       return &AArch64::FPR16RegClass;
497     if (Ty.getSizeInBits() == 32)
498       return &AArch64::FPR32RegClass;
499     if (Ty.getSizeInBits() == 64)
500       return &AArch64::FPR64RegClass;
501     if (Ty.getSizeInBits() == 128)
502       return &AArch64::FPR128RegClass;
503     return nullptr;
504   }
505 
506   return nullptr;
507 }
508 
509 /// Given a register bank, and size in bits, return the smallest register class
510 /// that can represent that combination.
511 static const TargetRegisterClass *
512 getMinClassForRegBank(const RegisterBank &RB, unsigned SizeInBits,
513                       bool GetAllRegSet = false) {
514   unsigned RegBankID = RB.getID();
515 
516   if (RegBankID == AArch64::GPRRegBankID) {
517     if (SizeInBits <= 32)
518       return GetAllRegSet ? &AArch64::GPR32allRegClass
519                           : &AArch64::GPR32RegClass;
520     if (SizeInBits == 64)
521       return GetAllRegSet ? &AArch64::GPR64allRegClass
522                           : &AArch64::GPR64RegClass;
523   }
524 
525   if (RegBankID == AArch64::FPRRegBankID) {
526     switch (SizeInBits) {
527     default:
528       return nullptr;
529     case 8:
530       return &AArch64::FPR8RegClass;
531     case 16:
532       return &AArch64::FPR16RegClass;
533     case 32:
534       return &AArch64::FPR32RegClass;
535     case 64:
536       return &AArch64::FPR64RegClass;
537     case 128:
538       return &AArch64::FPR128RegClass;
539     }
540   }
541 
542   return nullptr;
543 }
544 
545 /// Returns the correct subregister to use for a given register class.
546 static bool getSubRegForClass(const TargetRegisterClass *RC,
547                               const TargetRegisterInfo &TRI, unsigned &SubReg) {
548   switch (TRI.getRegSizeInBits(*RC)) {
549   case 8:
550     SubReg = AArch64::bsub;
551     break;
552   case 16:
553     SubReg = AArch64::hsub;
554     break;
555   case 32:
556     if (RC != &AArch64::FPR32RegClass)
557       SubReg = AArch64::sub_32;
558     else
559       SubReg = AArch64::ssub;
560     break;
561   case 64:
562     SubReg = AArch64::dsub;
563     break;
564   default:
565     LLVM_DEBUG(
566         dbgs() << "Couldn't find appropriate subregister for register class.");
567     return false;
568   }
569 
570   return true;
571 }
572 
573 /// Returns the minimum size the given register bank can hold.
574 static unsigned getMinSizeForRegBank(const RegisterBank &RB) {
575   switch (RB.getID()) {
576   case AArch64::GPRRegBankID:
577     return 32;
578   case AArch64::FPRRegBankID:
579     return 8;
580   default:
581     llvm_unreachable("Tried to get minimum size for unknown register bank.");
582   }
583 }
584 
585 static Optional<uint64_t> getImmedFromMO(const MachineOperand &Root) {
586   auto &MI = *Root.getParent();
587   auto &MBB = *MI.getParent();
588   auto &MF = *MBB.getParent();
589   auto &MRI = MF.getRegInfo();
590   uint64_t Immed;
591   if (Root.isImm())
592     Immed = Root.getImm();
593   else if (Root.isCImm())
594     Immed = Root.getCImm()->getZExtValue();
595   else if (Root.isReg()) {
596     auto ValAndVReg =
597         getConstantVRegValWithLookThrough(Root.getReg(), MRI, true);
598     if (!ValAndVReg)
599       return None;
600     Immed = ValAndVReg->Value.getSExtValue();
601   } else
602     return None;
603   return Immed;
604 }
605 
606 /// Check whether \p I is a currently unsupported binary operation:
607 /// - it has an unsized type
608 /// - an operand is not a vreg
609 /// - all operands are not in the same bank
610 /// These are checks that should someday live in the verifier, but right now,
611 /// these are mostly limitations of the aarch64 selector.
612 static bool unsupportedBinOp(const MachineInstr &I,
613                              const AArch64RegisterBankInfo &RBI,
614                              const MachineRegisterInfo &MRI,
615                              const AArch64RegisterInfo &TRI) {
616   LLT Ty = MRI.getType(I.getOperand(0).getReg());
617   if (!Ty.isValid()) {
618     LLVM_DEBUG(dbgs() << "Generic binop register should be typed\n");
619     return true;
620   }
621 
622   const RegisterBank *PrevOpBank = nullptr;
623   for (auto &MO : I.operands()) {
624     // FIXME: Support non-register operands.
625     if (!MO.isReg()) {
626       LLVM_DEBUG(dbgs() << "Generic inst non-reg operands are unsupported\n");
627       return true;
628     }
629 
630     // FIXME: Can generic operations have physical registers operands? If
631     // so, this will need to be taught about that, and we'll need to get the
632     // bank out of the minimal class for the register.
633     // Either way, this needs to be documented (and possibly verified).
634     if (!Register::isVirtualRegister(MO.getReg())) {
635       LLVM_DEBUG(dbgs() << "Generic inst has physical register operand\n");
636       return true;
637     }
638 
639     const RegisterBank *OpBank = RBI.getRegBank(MO.getReg(), MRI, TRI);
640     if (!OpBank) {
641       LLVM_DEBUG(dbgs() << "Generic register has no bank or class\n");
642       return true;
643     }
644 
645     if (PrevOpBank && OpBank != PrevOpBank) {
646       LLVM_DEBUG(dbgs() << "Generic inst operands have different banks\n");
647       return true;
648     }
649     PrevOpBank = OpBank;
650   }
651   return false;
652 }
653 
654 /// Select the AArch64 opcode for the basic binary operation \p GenericOpc
655 /// (such as G_OR or G_SDIV), appropriate for the register bank \p RegBankID
656 /// and of size \p OpSize.
657 /// \returns \p GenericOpc if the combination is unsupported.
658 static unsigned selectBinaryOp(unsigned GenericOpc, unsigned RegBankID,
659                                unsigned OpSize) {
660   switch (RegBankID) {
661   case AArch64::GPRRegBankID:
662     if (OpSize == 32) {
663       switch (GenericOpc) {
664       case TargetOpcode::G_SHL:
665         return AArch64::LSLVWr;
666       case TargetOpcode::G_LSHR:
667         return AArch64::LSRVWr;
668       case TargetOpcode::G_ASHR:
669         return AArch64::ASRVWr;
670       default:
671         return GenericOpc;
672       }
673     } else if (OpSize == 64) {
674       switch (GenericOpc) {
675       case TargetOpcode::G_PTR_ADD:
676         return AArch64::ADDXrr;
677       case TargetOpcode::G_SHL:
678         return AArch64::LSLVXr;
679       case TargetOpcode::G_LSHR:
680         return AArch64::LSRVXr;
681       case TargetOpcode::G_ASHR:
682         return AArch64::ASRVXr;
683       default:
684         return GenericOpc;
685       }
686     }
687     break;
688   case AArch64::FPRRegBankID:
689     switch (OpSize) {
690     case 32:
691       switch (GenericOpc) {
692       case TargetOpcode::G_FADD:
693         return AArch64::FADDSrr;
694       case TargetOpcode::G_FSUB:
695         return AArch64::FSUBSrr;
696       case TargetOpcode::G_FMUL:
697         return AArch64::FMULSrr;
698       case TargetOpcode::G_FDIV:
699         return AArch64::FDIVSrr;
700       default:
701         return GenericOpc;
702       }
703     case 64:
704       switch (GenericOpc) {
705       case TargetOpcode::G_FADD:
706         return AArch64::FADDDrr;
707       case TargetOpcode::G_FSUB:
708         return AArch64::FSUBDrr;
709       case TargetOpcode::G_FMUL:
710         return AArch64::FMULDrr;
711       case TargetOpcode::G_FDIV:
712         return AArch64::FDIVDrr;
713       case TargetOpcode::G_OR:
714         return AArch64::ORRv8i8;
715       default:
716         return GenericOpc;
717       }
718     }
719     break;
720   }
721   return GenericOpc;
722 }
723 
724 /// Select the AArch64 opcode for the G_LOAD or G_STORE operation \p GenericOpc,
725 /// appropriate for the (value) register bank \p RegBankID and of memory access
726 /// size \p OpSize.  This returns the variant with the base+unsigned-immediate
727 /// addressing mode (e.g., LDRXui).
728 /// \returns \p GenericOpc if the combination is unsupported.
729 static unsigned selectLoadStoreUIOp(unsigned GenericOpc, unsigned RegBankID,
730                                     unsigned OpSize) {
731   const bool isStore = GenericOpc == TargetOpcode::G_STORE;
732   switch (RegBankID) {
733   case AArch64::GPRRegBankID:
734     switch (OpSize) {
735     case 8:
736       return isStore ? AArch64::STRBBui : AArch64::LDRBBui;
737     case 16:
738       return isStore ? AArch64::STRHHui : AArch64::LDRHHui;
739     case 32:
740       return isStore ? AArch64::STRWui : AArch64::LDRWui;
741     case 64:
742       return isStore ? AArch64::STRXui : AArch64::LDRXui;
743     }
744     break;
745   case AArch64::FPRRegBankID:
746     switch (OpSize) {
747     case 8:
748       return isStore ? AArch64::STRBui : AArch64::LDRBui;
749     case 16:
750       return isStore ? AArch64::STRHui : AArch64::LDRHui;
751     case 32:
752       return isStore ? AArch64::STRSui : AArch64::LDRSui;
753     case 64:
754       return isStore ? AArch64::STRDui : AArch64::LDRDui;
755     }
756     break;
757   }
758   return GenericOpc;
759 }
760 
761 #ifndef NDEBUG
762 /// Helper function that verifies that we have a valid copy at the end of
763 /// selectCopy. Verifies that the source and dest have the expected sizes and
764 /// then returns true.
765 static bool isValidCopy(const MachineInstr &I, const RegisterBank &DstBank,
766                         const MachineRegisterInfo &MRI,
767                         const TargetRegisterInfo &TRI,
768                         const RegisterBankInfo &RBI) {
769   const Register DstReg = I.getOperand(0).getReg();
770   const Register SrcReg = I.getOperand(1).getReg();
771   const unsigned DstSize = RBI.getSizeInBits(DstReg, MRI, TRI);
772   const unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI);
773 
774   // Make sure the size of the source and dest line up.
775   assert(
776       (DstSize == SrcSize ||
777        // Copies are a mean to setup initial types, the number of
778        // bits may not exactly match.
779        (Register::isPhysicalRegister(SrcReg) && DstSize <= SrcSize) ||
780        // Copies are a mean to copy bits around, as long as we are
781        // on the same register class, that's fine. Otherwise, that
782        // means we need some SUBREG_TO_REG or AND & co.
783        (((DstSize + 31) / 32 == (SrcSize + 31) / 32) && DstSize > SrcSize)) &&
784       "Copy with different width?!");
785 
786   // Check the size of the destination.
787   assert((DstSize <= 64 || DstBank.getID() == AArch64::FPRRegBankID) &&
788          "GPRs cannot get more than 64-bit width values");
789 
790   return true;
791 }
792 #endif
793 
794 /// Helper function for selectCopy. Inserts a subregister copy from \p SrcReg
795 /// to \p *To.
796 ///
797 /// E.g "To = COPY SrcReg:SubReg"
798 static bool copySubReg(MachineInstr &I, MachineRegisterInfo &MRI,
799                        const RegisterBankInfo &RBI, Register SrcReg,
800                        const TargetRegisterClass *To, unsigned SubReg) {
801   assert(SrcReg.isValid() && "Expected a valid source register?");
802   assert(To && "Destination register class cannot be null");
803   assert(SubReg && "Expected a valid subregister");
804 
805   MachineIRBuilder MIB(I);
806   auto SubRegCopy =
807       MIB.buildInstr(TargetOpcode::COPY, {To}, {}).addReg(SrcReg, 0, SubReg);
808   MachineOperand &RegOp = I.getOperand(1);
809   RegOp.setReg(SubRegCopy.getReg(0));
810 
811   // It's possible that the destination register won't be constrained. Make
812   // sure that happens.
813   if (!Register::isPhysicalRegister(I.getOperand(0).getReg()))
814     RBI.constrainGenericRegister(I.getOperand(0).getReg(), *To, MRI);
815 
816   return true;
817 }
818 
819 /// Helper function to get the source and destination register classes for a
820 /// copy. Returns a std::pair containing the source register class for the
821 /// copy, and the destination register class for the copy. If a register class
822 /// cannot be determined, then it will be nullptr.
823 static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
824 getRegClassesForCopy(MachineInstr &I, const TargetInstrInfo &TII,
825                      MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
826                      const RegisterBankInfo &RBI) {
827   Register DstReg = I.getOperand(0).getReg();
828   Register SrcReg = I.getOperand(1).getReg();
829   const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
830   const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
831   unsigned DstSize = RBI.getSizeInBits(DstReg, MRI, TRI);
832   unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI);
833 
834   // Special casing for cross-bank copies of s1s. We can technically represent
835   // a 1-bit value with any size of register. The minimum size for a GPR is 32
836   // bits. So, we need to put the FPR on 32 bits as well.
837   //
838   // FIXME: I'm not sure if this case holds true outside of copies. If it does,
839   // then we can pull it into the helpers that get the appropriate class for a
840   // register bank. Or make a new helper that carries along some constraint
841   // information.
842   if (SrcRegBank != DstRegBank && (DstSize == 1 && SrcSize == 1))
843     SrcSize = DstSize = 32;
844 
845   return {getMinClassForRegBank(SrcRegBank, SrcSize, true),
846           getMinClassForRegBank(DstRegBank, DstSize, true)};
847 }
848 
849 static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII,
850                        MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
851                        const RegisterBankInfo &RBI) {
852   Register DstReg = I.getOperand(0).getReg();
853   Register SrcReg = I.getOperand(1).getReg();
854   const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
855   const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
856 
857   // Find the correct register classes for the source and destination registers.
858   const TargetRegisterClass *SrcRC;
859   const TargetRegisterClass *DstRC;
860   std::tie(SrcRC, DstRC) = getRegClassesForCopy(I, TII, MRI, TRI, RBI);
861 
862   if (!DstRC) {
863     LLVM_DEBUG(dbgs() << "Unexpected dest size "
864                       << RBI.getSizeInBits(DstReg, MRI, TRI) << '\n');
865     return false;
866   }
867 
868   // A couple helpers below, for making sure that the copy we produce is valid.
869 
870   // Set to true if we insert a SUBREG_TO_REG. If we do this, then we don't want
871   // to verify that the src and dst are the same size, since that's handled by
872   // the SUBREG_TO_REG.
873   bool KnownValid = false;
874 
875   // Returns true, or asserts if something we don't expect happens. Instead of
876   // returning true, we return isValidCopy() to ensure that we verify the
877   // result.
878   auto CheckCopy = [&]() {
879     // If we have a bitcast or something, we can't have physical registers.
880     assert((I.isCopy() ||
881             (!Register::isPhysicalRegister(I.getOperand(0).getReg()) &&
882              !Register::isPhysicalRegister(I.getOperand(1).getReg()))) &&
883            "No phys reg on generic operator!");
884     bool ValidCopy = true;
885 #ifndef NDEBUG
886     ValidCopy = KnownValid || isValidCopy(I, DstRegBank, MRI, TRI, RBI);
887     assert(ValidCopy && "Invalid copy.");
888 #endif
889     (void)KnownValid;
890     return ValidCopy;
891   };
892 
893   // Is this a copy? If so, then we may need to insert a subregister copy.
894   if (I.isCopy()) {
895     // Yes. Check if there's anything to fix up.
896     if (!SrcRC) {
897       LLVM_DEBUG(dbgs() << "Couldn't determine source register class\n");
898       return false;
899     }
900 
901     unsigned SrcSize = TRI.getRegSizeInBits(*SrcRC);
902     unsigned DstSize = TRI.getRegSizeInBits(*DstRC);
903     unsigned SubReg;
904 
905     // If the source bank doesn't support a subregister copy small enough,
906     // then we first need to copy to the destination bank.
907     if (getMinSizeForRegBank(SrcRegBank) > DstSize) {
908       const TargetRegisterClass *DstTempRC =
909           getMinClassForRegBank(DstRegBank, SrcSize, /* GetAllRegSet */ true);
910       getSubRegForClass(DstRC, TRI, SubReg);
911 
912       MachineIRBuilder MIB(I);
913       auto Copy = MIB.buildCopy({DstTempRC}, {SrcReg});
914       copySubReg(I, MRI, RBI, Copy.getReg(0), DstRC, SubReg);
915     } else if (SrcSize > DstSize) {
916       // If the source register is bigger than the destination we need to
917       // perform a subregister copy.
918       const TargetRegisterClass *SubRegRC =
919           getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
920       getSubRegForClass(SubRegRC, TRI, SubReg);
921       copySubReg(I, MRI, RBI, SrcReg, DstRC, SubReg);
922     } else if (DstSize > SrcSize) {
923       // If the destination register is bigger than the source we need to do
924       // a promotion using SUBREG_TO_REG.
925       const TargetRegisterClass *PromotionRC =
926           getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
927       getSubRegForClass(SrcRC, TRI, SubReg);
928 
929       Register PromoteReg = MRI.createVirtualRegister(PromotionRC);
930       BuildMI(*I.getParent(), I, I.getDebugLoc(),
931               TII.get(AArch64::SUBREG_TO_REG), PromoteReg)
932           .addImm(0)
933           .addUse(SrcReg)
934           .addImm(SubReg);
935       MachineOperand &RegOp = I.getOperand(1);
936       RegOp.setReg(PromoteReg);
937 
938       // Promise that the copy is implicitly validated by the SUBREG_TO_REG.
939       KnownValid = true;
940     }
941 
942     // If the destination is a physical register, then there's nothing to
943     // change, so we're done.
944     if (Register::isPhysicalRegister(DstReg))
945       return CheckCopy();
946   }
947 
948   // No need to constrain SrcReg. It will get constrained when we hit another
949   // of its use or its defs. Copies do not have constraints.
950   if (!RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
951     LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode())
952                       << " operand\n");
953     return false;
954   }
955   I.setDesc(TII.get(AArch64::COPY));
956   return CheckCopy();
957 }
958 
959 static unsigned selectFPConvOpc(unsigned GenericOpc, LLT DstTy, LLT SrcTy) {
960   if (!DstTy.isScalar() || !SrcTy.isScalar())
961     return GenericOpc;
962 
963   const unsigned DstSize = DstTy.getSizeInBits();
964   const unsigned SrcSize = SrcTy.getSizeInBits();
965 
966   switch (DstSize) {
967   case 32:
968     switch (SrcSize) {
969     case 32:
970       switch (GenericOpc) {
971       case TargetOpcode::G_SITOFP:
972         return AArch64::SCVTFUWSri;
973       case TargetOpcode::G_UITOFP:
974         return AArch64::UCVTFUWSri;
975       case TargetOpcode::G_FPTOSI:
976         return AArch64::FCVTZSUWSr;
977       case TargetOpcode::G_FPTOUI:
978         return AArch64::FCVTZUUWSr;
979       default:
980         return GenericOpc;
981       }
982     case 64:
983       switch (GenericOpc) {
984       case TargetOpcode::G_SITOFP:
985         return AArch64::SCVTFUXSri;
986       case TargetOpcode::G_UITOFP:
987         return AArch64::UCVTFUXSri;
988       case TargetOpcode::G_FPTOSI:
989         return AArch64::FCVTZSUWDr;
990       case TargetOpcode::G_FPTOUI:
991         return AArch64::FCVTZUUWDr;
992       default:
993         return GenericOpc;
994       }
995     default:
996       return GenericOpc;
997     }
998   case 64:
999     switch (SrcSize) {
1000     case 32:
1001       switch (GenericOpc) {
1002       case TargetOpcode::G_SITOFP:
1003         return AArch64::SCVTFUWDri;
1004       case TargetOpcode::G_UITOFP:
1005         return AArch64::UCVTFUWDri;
1006       case TargetOpcode::G_FPTOSI:
1007         return AArch64::FCVTZSUXSr;
1008       case TargetOpcode::G_FPTOUI:
1009         return AArch64::FCVTZUUXSr;
1010       default:
1011         return GenericOpc;
1012       }
1013     case 64:
1014       switch (GenericOpc) {
1015       case TargetOpcode::G_SITOFP:
1016         return AArch64::SCVTFUXDri;
1017       case TargetOpcode::G_UITOFP:
1018         return AArch64::UCVTFUXDri;
1019       case TargetOpcode::G_FPTOSI:
1020         return AArch64::FCVTZSUXDr;
1021       case TargetOpcode::G_FPTOUI:
1022         return AArch64::FCVTZUUXDr;
1023       default:
1024         return GenericOpc;
1025       }
1026     default:
1027       return GenericOpc;
1028     }
1029   default:
1030     return GenericOpc;
1031   };
1032   return GenericOpc;
1033 }
1034 
1035 MachineInstr *
1036 AArch64InstructionSelector::emitSelect(Register Dst, Register True,
1037                                        Register False, AArch64CC::CondCode CC,
1038                                        MachineIRBuilder &MIB) const {
1039   MachineRegisterInfo &MRI = *MIB.getMRI();
1040   assert(RBI.getRegBank(False, MRI, TRI)->getID() ==
1041              RBI.getRegBank(True, MRI, TRI)->getID() &&
1042          "Expected both select operands to have the same regbank?");
1043   LLT Ty = MRI.getType(True);
1044   if (Ty.isVector())
1045     return nullptr;
1046   const unsigned Size = Ty.getSizeInBits();
1047   assert((Size == 32 || Size == 64) &&
1048          "Expected 32 bit or 64 bit select only?");
1049   const bool Is32Bit = Size == 32;
1050   if (RBI.getRegBank(True, MRI, TRI)->getID() != AArch64::GPRRegBankID) {
1051     unsigned Opc = Is32Bit ? AArch64::FCSELSrrr : AArch64::FCSELDrrr;
1052     auto FCSel = MIB.buildInstr(Opc, {Dst}, {True, False}).addImm(CC);
1053     constrainSelectedInstRegOperands(*FCSel, TII, TRI, RBI);
1054     return &*FCSel;
1055   }
1056 
1057   // By default, we'll try and emit a CSEL.
1058   unsigned Opc = Is32Bit ? AArch64::CSELWr : AArch64::CSELXr;
1059   bool Optimized = false;
1060   auto TryFoldBinOpIntoSelect = [&Opc, Is32Bit, &CC, &MRI,
1061                                  &Optimized](Register &Reg, Register &OtherReg,
1062                                              bool Invert) {
1063     if (Optimized)
1064       return false;
1065 
1066     // Attempt to fold:
1067     //
1068     // %sub = G_SUB 0, %x
1069     // %select = G_SELECT cc, %reg, %sub
1070     //
1071     // Into:
1072     // %select = CSNEG %reg, %x, cc
1073     Register MatchReg;
1074     if (mi_match(Reg, MRI, m_Neg(m_Reg(MatchReg)))) {
1075       Opc = Is32Bit ? AArch64::CSNEGWr : AArch64::CSNEGXr;
1076       Reg = MatchReg;
1077       if (Invert) {
1078         CC = AArch64CC::getInvertedCondCode(CC);
1079         std::swap(Reg, OtherReg);
1080       }
1081       return true;
1082     }
1083 
1084     // Attempt to fold:
1085     //
1086     // %xor = G_XOR %x, -1
1087     // %select = G_SELECT cc, %reg, %xor
1088     //
1089     // Into:
1090     // %select = CSINV %reg, %x, cc
1091     if (mi_match(Reg, MRI, m_Not(m_Reg(MatchReg)))) {
1092       Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
1093       Reg = MatchReg;
1094       if (Invert) {
1095         CC = AArch64CC::getInvertedCondCode(CC);
1096         std::swap(Reg, OtherReg);
1097       }
1098       return true;
1099     }
1100 
1101     // Attempt to fold:
1102     //
1103     // %add = G_ADD %x, 1
1104     // %select = G_SELECT cc, %reg, %add
1105     //
1106     // Into:
1107     // %select = CSINC %reg, %x, cc
1108     if (mi_match(Reg, MRI,
1109                  m_any_of(m_GAdd(m_Reg(MatchReg), m_SpecificICst(1)),
1110                           m_GPtrAdd(m_Reg(MatchReg), m_SpecificICst(1))))) {
1111       Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
1112       Reg = MatchReg;
1113       if (Invert) {
1114         CC = AArch64CC::getInvertedCondCode(CC);
1115         std::swap(Reg, OtherReg);
1116       }
1117       return true;
1118     }
1119 
1120     return false;
1121   };
1122 
1123   // Helper lambda which tries to use CSINC/CSINV for the instruction when its
1124   // true/false values are constants.
1125   // FIXME: All of these patterns already exist in tablegen. We should be
1126   // able to import these.
1127   auto TryOptSelectCst = [&Opc, &True, &False, &CC, Is32Bit, &MRI,
1128                           &Optimized]() {
1129     if (Optimized)
1130       return false;
1131     auto TrueCst = getConstantVRegValWithLookThrough(True, MRI);
1132     auto FalseCst = getConstantVRegValWithLookThrough(False, MRI);
1133     if (!TrueCst && !FalseCst)
1134       return false;
1135 
1136     Register ZReg = Is32Bit ? AArch64::WZR : AArch64::XZR;
1137     if (TrueCst && FalseCst) {
1138       int64_t T = TrueCst->Value.getSExtValue();
1139       int64_t F = FalseCst->Value.getSExtValue();
1140 
1141       if (T == 0 && F == 1) {
1142         // G_SELECT cc, 0, 1 -> CSINC zreg, zreg, cc
1143         Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
1144         True = ZReg;
1145         False = ZReg;
1146         return true;
1147       }
1148 
1149       if (T == 0 && F == -1) {
1150         // G_SELECT cc 0, -1 -> CSINV zreg, zreg cc
1151         Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
1152         True = ZReg;
1153         False = ZReg;
1154         return true;
1155       }
1156     }
1157 
1158     if (TrueCst) {
1159       int64_t T = TrueCst->Value.getSExtValue();
1160       if (T == 1) {
1161         // G_SELECT cc, 1, f -> CSINC f, zreg, inv_cc
1162         Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
1163         True = False;
1164         False = ZReg;
1165         CC = AArch64CC::getInvertedCondCode(CC);
1166         return true;
1167       }
1168 
1169       if (T == -1) {
1170         // G_SELECT cc, -1, f -> CSINV f, zreg, inv_cc
1171         Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
1172         True = False;
1173         False = ZReg;
1174         CC = AArch64CC::getInvertedCondCode(CC);
1175         return true;
1176       }
1177     }
1178 
1179     if (FalseCst) {
1180       int64_t F = FalseCst->Value.getSExtValue();
1181       if (F == 1) {
1182         // G_SELECT cc, t, 1 -> CSINC t, zreg, cc
1183         Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
1184         False = ZReg;
1185         return true;
1186       }
1187 
1188       if (F == -1) {
1189         // G_SELECT cc, t, -1 -> CSINC t, zreg, cc
1190         Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
1191         False = ZReg;
1192         return true;
1193       }
1194     }
1195     return false;
1196   };
1197 
1198   Optimized |= TryFoldBinOpIntoSelect(False, True, /*Invert = */ false);
1199   Optimized |= TryFoldBinOpIntoSelect(True, False, /*Invert = */ true);
1200   Optimized |= TryOptSelectCst();
1201   auto SelectInst = MIB.buildInstr(Opc, {Dst}, {True, False}).addImm(CC);
1202   constrainSelectedInstRegOperands(*SelectInst, TII, TRI, RBI);
1203   return &*SelectInst;
1204 }
1205 
1206 static AArch64CC::CondCode changeICMPPredToAArch64CC(CmpInst::Predicate P) {
1207   switch (P) {
1208   default:
1209     llvm_unreachable("Unknown condition code!");
1210   case CmpInst::ICMP_NE:
1211     return AArch64CC::NE;
1212   case CmpInst::ICMP_EQ:
1213     return AArch64CC::EQ;
1214   case CmpInst::ICMP_SGT:
1215     return AArch64CC::GT;
1216   case CmpInst::ICMP_SGE:
1217     return AArch64CC::GE;
1218   case CmpInst::ICMP_SLT:
1219     return AArch64CC::LT;
1220   case CmpInst::ICMP_SLE:
1221     return AArch64CC::LE;
1222   case CmpInst::ICMP_UGT:
1223     return AArch64CC::HI;
1224   case CmpInst::ICMP_UGE:
1225     return AArch64CC::HS;
1226   case CmpInst::ICMP_ULT:
1227     return AArch64CC::LO;
1228   case CmpInst::ICMP_ULE:
1229     return AArch64CC::LS;
1230   }
1231 }
1232 
1233 static void changeFCMPPredToAArch64CC(CmpInst::Predicate P,
1234                                       AArch64CC::CondCode &CondCode,
1235                                       AArch64CC::CondCode &CondCode2) {
1236   CondCode2 = AArch64CC::AL;
1237   switch (P) {
1238   default:
1239     llvm_unreachable("Unknown FP condition!");
1240   case CmpInst::FCMP_OEQ:
1241     CondCode = AArch64CC::EQ;
1242     break;
1243   case CmpInst::FCMP_OGT:
1244     CondCode = AArch64CC::GT;
1245     break;
1246   case CmpInst::FCMP_OGE:
1247     CondCode = AArch64CC::GE;
1248     break;
1249   case CmpInst::FCMP_OLT:
1250     CondCode = AArch64CC::MI;
1251     break;
1252   case CmpInst::FCMP_OLE:
1253     CondCode = AArch64CC::LS;
1254     break;
1255   case CmpInst::FCMP_ONE:
1256     CondCode = AArch64CC::MI;
1257     CondCode2 = AArch64CC::GT;
1258     break;
1259   case CmpInst::FCMP_ORD:
1260     CondCode = AArch64CC::VC;
1261     break;
1262   case CmpInst::FCMP_UNO:
1263     CondCode = AArch64CC::VS;
1264     break;
1265   case CmpInst::FCMP_UEQ:
1266     CondCode = AArch64CC::EQ;
1267     CondCode2 = AArch64CC::VS;
1268     break;
1269   case CmpInst::FCMP_UGT:
1270     CondCode = AArch64CC::HI;
1271     break;
1272   case CmpInst::FCMP_UGE:
1273     CondCode = AArch64CC::PL;
1274     break;
1275   case CmpInst::FCMP_ULT:
1276     CondCode = AArch64CC::LT;
1277     break;
1278   case CmpInst::FCMP_ULE:
1279     CondCode = AArch64CC::LE;
1280     break;
1281   case CmpInst::FCMP_UNE:
1282     CondCode = AArch64CC::NE;
1283     break;
1284   }
1285 }
1286 
1287 /// Return a register which can be used as a bit to test in a TB(N)Z.
1288 static Register getTestBitReg(Register Reg, uint64_t &Bit, bool &Invert,
1289                               MachineRegisterInfo &MRI) {
1290   assert(Reg.isValid() && "Expected valid register!");
1291   while (MachineInstr *MI = getDefIgnoringCopies(Reg, MRI)) {
1292     unsigned Opc = MI->getOpcode();
1293 
1294     if (!MI->getOperand(0).isReg() ||
1295         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1296       break;
1297 
1298     // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
1299     //
1300     // (tbz (trunc x), b) -> (tbz x, b) is always safe, because the bit number
1301     // on the truncated x is the same as the bit number on x.
1302     if (Opc == TargetOpcode::G_ANYEXT || Opc == TargetOpcode::G_ZEXT ||
1303         Opc == TargetOpcode::G_TRUNC) {
1304       Register NextReg = MI->getOperand(1).getReg();
1305       // Did we find something worth folding?
1306       if (!NextReg.isValid() || !MRI.hasOneNonDBGUse(NextReg))
1307         break;
1308 
1309       // NextReg is worth folding. Keep looking.
1310       Reg = NextReg;
1311       continue;
1312     }
1313 
1314     // Attempt to find a suitable operation with a constant on one side.
1315     Optional<uint64_t> C;
1316     Register TestReg;
1317     switch (Opc) {
1318     default:
1319       break;
1320     case TargetOpcode::G_AND:
1321     case TargetOpcode::G_XOR: {
1322       TestReg = MI->getOperand(1).getReg();
1323       Register ConstantReg = MI->getOperand(2).getReg();
1324       auto VRegAndVal = getConstantVRegValWithLookThrough(ConstantReg, MRI);
1325       if (!VRegAndVal) {
1326         // AND commutes, check the other side for a constant.
1327         // FIXME: Can we canonicalize the constant so that it's always on the
1328         // same side at some point earlier?
1329         std::swap(ConstantReg, TestReg);
1330         VRegAndVal = getConstantVRegValWithLookThrough(ConstantReg, MRI);
1331       }
1332       if (VRegAndVal)
1333         C = VRegAndVal->Value.getSExtValue();
1334       break;
1335     }
1336     case TargetOpcode::G_ASHR:
1337     case TargetOpcode::G_LSHR:
1338     case TargetOpcode::G_SHL: {
1339       TestReg = MI->getOperand(1).getReg();
1340       auto VRegAndVal =
1341           getConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1342       if (VRegAndVal)
1343         C = VRegAndVal->Value.getSExtValue();
1344       break;
1345     }
1346     }
1347 
1348     // Didn't find a constant or viable register. Bail out of the loop.
1349     if (!C || !TestReg.isValid())
1350       break;
1351 
1352     // We found a suitable instruction with a constant. Check to see if we can
1353     // walk through the instruction.
1354     Register NextReg;
1355     unsigned TestRegSize = MRI.getType(TestReg).getSizeInBits();
1356     switch (Opc) {
1357     default:
1358       break;
1359     case TargetOpcode::G_AND:
1360       // (tbz (and x, m), b) -> (tbz x, b) when the b-th bit of m is set.
1361       if ((*C >> Bit) & 1)
1362         NextReg = TestReg;
1363       break;
1364     case TargetOpcode::G_SHL:
1365       // (tbz (shl x, c), b) -> (tbz x, b-c) when b-c is positive and fits in
1366       // the type of the register.
1367       if (*C <= Bit && (Bit - *C) < TestRegSize) {
1368         NextReg = TestReg;
1369         Bit = Bit - *C;
1370       }
1371       break;
1372     case TargetOpcode::G_ASHR:
1373       // (tbz (ashr x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits
1374       // in x
1375       NextReg = TestReg;
1376       Bit = Bit + *C;
1377       if (Bit >= TestRegSize)
1378         Bit = TestRegSize - 1;
1379       break;
1380     case TargetOpcode::G_LSHR:
1381       // (tbz (lshr x, c), b) -> (tbz x, b+c) when b + c is < # bits in x
1382       if ((Bit + *C) < TestRegSize) {
1383         NextReg = TestReg;
1384         Bit = Bit + *C;
1385       }
1386       break;
1387     case TargetOpcode::G_XOR:
1388       // We can walk through a G_XOR by inverting whether we use tbz/tbnz when
1389       // appropriate.
1390       //
1391       // e.g. If x' = xor x, c, and the b-th bit is set in c then
1392       //
1393       // tbz x', b -> tbnz x, b
1394       //
1395       // Because x' only has the b-th bit set if x does not.
1396       if ((*C >> Bit) & 1)
1397         Invert = !Invert;
1398       NextReg = TestReg;
1399       break;
1400     }
1401 
1402     // Check if we found anything worth folding.
1403     if (!NextReg.isValid())
1404       return Reg;
1405     Reg = NextReg;
1406   }
1407 
1408   return Reg;
1409 }
1410 
1411 MachineInstr *AArch64InstructionSelector::emitTestBit(
1412     Register TestReg, uint64_t Bit, bool IsNegative, MachineBasicBlock *DstMBB,
1413     MachineIRBuilder &MIB) const {
1414   assert(TestReg.isValid());
1415   assert(ProduceNonFlagSettingCondBr &&
1416          "Cannot emit TB(N)Z with speculation tracking!");
1417   MachineRegisterInfo &MRI = *MIB.getMRI();
1418 
1419   // Attempt to optimize the test bit by walking over instructions.
1420   TestReg = getTestBitReg(TestReg, Bit, IsNegative, MRI);
1421   LLT Ty = MRI.getType(TestReg);
1422   unsigned Size = Ty.getSizeInBits();
1423   assert(!Ty.isVector() && "Expected a scalar!");
1424   assert(Bit < 64 && "Bit is too large!");
1425 
1426   // When the test register is a 64-bit register, we have to narrow to make
1427   // TBNZW work.
1428   bool UseWReg = Bit < 32;
1429   unsigned NecessarySize = UseWReg ? 32 : 64;
1430   if (Size != NecessarySize)
1431     TestReg = moveScalarRegClass(
1432         TestReg, UseWReg ? AArch64::GPR32RegClass : AArch64::GPR64RegClass,
1433         MIB);
1434 
1435   static const unsigned OpcTable[2][2] = {{AArch64::TBZX, AArch64::TBNZX},
1436                                           {AArch64::TBZW, AArch64::TBNZW}};
1437   unsigned Opc = OpcTable[UseWReg][IsNegative];
1438   auto TestBitMI =
1439       MIB.buildInstr(Opc).addReg(TestReg).addImm(Bit).addMBB(DstMBB);
1440   constrainSelectedInstRegOperands(*TestBitMI, TII, TRI, RBI);
1441   return &*TestBitMI;
1442 }
1443 
1444 bool AArch64InstructionSelector::tryOptAndIntoCompareBranch(
1445     MachineInstr &AndInst, bool Invert, MachineBasicBlock *DstMBB,
1446     MachineIRBuilder &MIB) const {
1447   assert(AndInst.getOpcode() == TargetOpcode::G_AND && "Expected G_AND only?");
1448   // Given something like this:
1449   //
1450   //  %x = ...Something...
1451   //  %one = G_CONSTANT i64 1
1452   //  %zero = G_CONSTANT i64 0
1453   //  %and = G_AND %x, %one
1454   //  %cmp = G_ICMP intpred(ne), %and, %zero
1455   //  %cmp_trunc = G_TRUNC %cmp
1456   //  G_BRCOND %cmp_trunc, %bb.3
1457   //
1458   // We want to try and fold the AND into the G_BRCOND and produce either a
1459   // TBNZ (when we have intpred(ne)) or a TBZ (when we have intpred(eq)).
1460   //
1461   // In this case, we'd get
1462   //
1463   // TBNZ %x %bb.3
1464   //
1465 
1466   // Check if the AND has a constant on its RHS which we can use as a mask.
1467   // If it's a power of 2, then it's the same as checking a specific bit.
1468   // (e.g, ANDing with 8 == ANDing with 000...100 == testing if bit 3 is set)
1469   auto MaybeBit = getConstantVRegValWithLookThrough(
1470       AndInst.getOperand(2).getReg(), *MIB.getMRI());
1471   if (!MaybeBit)
1472     return false;
1473 
1474   int32_t Bit = MaybeBit->Value.exactLogBase2();
1475   if (Bit < 0)
1476     return false;
1477 
1478   Register TestReg = AndInst.getOperand(1).getReg();
1479 
1480   // Emit a TB(N)Z.
1481   emitTestBit(TestReg, Bit, Invert, DstMBB, MIB);
1482   return true;
1483 }
1484 
1485 MachineInstr *AArch64InstructionSelector::emitCBZ(Register CompareReg,
1486                                                   bool IsNegative,
1487                                                   MachineBasicBlock *DestMBB,
1488                                                   MachineIRBuilder &MIB) const {
1489   assert(ProduceNonFlagSettingCondBr && "CBZ does not set flags!");
1490   MachineRegisterInfo &MRI = *MIB.getMRI();
1491   assert(RBI.getRegBank(CompareReg, MRI, TRI)->getID() ==
1492              AArch64::GPRRegBankID &&
1493          "Expected GPRs only?");
1494   auto Ty = MRI.getType(CompareReg);
1495   unsigned Width = Ty.getSizeInBits();
1496   assert(!Ty.isVector() && "Expected scalar only?");
1497   assert(Width <= 64 && "Expected width to be at most 64?");
1498   static const unsigned OpcTable[2][2] = {{AArch64::CBZW, AArch64::CBZX},
1499                                           {AArch64::CBNZW, AArch64::CBNZX}};
1500   unsigned Opc = OpcTable[IsNegative][Width == 64];
1501   auto BranchMI = MIB.buildInstr(Opc, {}, {CompareReg}).addMBB(DestMBB);
1502   constrainSelectedInstRegOperands(*BranchMI, TII, TRI, RBI);
1503   return &*BranchMI;
1504 }
1505 
1506 bool AArch64InstructionSelector::selectCompareBranchFedByFCmp(
1507     MachineInstr &I, MachineInstr &FCmp, MachineIRBuilder &MIB) const {
1508   assert(FCmp.getOpcode() == TargetOpcode::G_FCMP);
1509   assert(I.getOpcode() == TargetOpcode::G_BRCOND);
1510   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
1511   // totally clean.  Some of them require two branches to implement.
1512   auto Pred = (CmpInst::Predicate)FCmp.getOperand(1).getPredicate();
1513   emitFPCompare(FCmp.getOperand(2).getReg(), FCmp.getOperand(3).getReg(), MIB,
1514                 Pred);
1515   AArch64CC::CondCode CC1, CC2;
1516   changeFCMPPredToAArch64CC(static_cast<CmpInst::Predicate>(Pred), CC1, CC2);
1517   MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
1518   MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC1).addMBB(DestMBB);
1519   if (CC2 != AArch64CC::AL)
1520     MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC2).addMBB(DestMBB);
1521   I.eraseFromParent();
1522   return true;
1523 }
1524 
1525 bool AArch64InstructionSelector::tryOptCompareBranchFedByICmp(
1526     MachineInstr &I, MachineInstr &ICmp, MachineIRBuilder &MIB) const {
1527   assert(ICmp.getOpcode() == TargetOpcode::G_ICMP);
1528   assert(I.getOpcode() == TargetOpcode::G_BRCOND);
1529   // Attempt to optimize the G_BRCOND + G_ICMP into a TB(N)Z/CB(N)Z.
1530   //
1531   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z
1532   // instructions will not be produced, as they are conditional branch
1533   // instructions that do not set flags.
1534   if (!ProduceNonFlagSettingCondBr)
1535     return false;
1536 
1537   MachineRegisterInfo &MRI = *MIB.getMRI();
1538   MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
1539   auto Pred =
1540       static_cast<CmpInst::Predicate>(ICmp.getOperand(1).getPredicate());
1541   Register LHS = ICmp.getOperand(2).getReg();
1542   Register RHS = ICmp.getOperand(3).getReg();
1543 
1544   // We're allowed to emit a TB(N)Z/CB(N)Z. Try to do that.
1545   auto VRegAndVal = getConstantVRegValWithLookThrough(RHS, MRI);
1546   MachineInstr *AndInst = getOpcodeDef(TargetOpcode::G_AND, LHS, MRI);
1547 
1548   // When we can emit a TB(N)Z, prefer that.
1549   //
1550   // Handle non-commutative condition codes first.
1551   // Note that we don't want to do this when we have a G_AND because it can
1552   // become a tst. The tst will make the test bit in the TB(N)Z redundant.
1553   if (VRegAndVal && !AndInst) {
1554     int64_t C = VRegAndVal->Value.getSExtValue();
1555 
1556     // When we have a greater-than comparison, we can just test if the msb is
1557     // zero.
1558     if (C == -1 && Pred == CmpInst::ICMP_SGT) {
1559       uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
1560       emitTestBit(LHS, Bit, /*IsNegative = */ false, DestMBB, MIB);
1561       I.eraseFromParent();
1562       return true;
1563     }
1564 
1565     // When we have a less than comparison, we can just test if the msb is not
1566     // zero.
1567     if (C == 0 && Pred == CmpInst::ICMP_SLT) {
1568       uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
1569       emitTestBit(LHS, Bit, /*IsNegative = */ true, DestMBB, MIB);
1570       I.eraseFromParent();
1571       return true;
1572     }
1573   }
1574 
1575   // Attempt to handle commutative condition codes. Right now, that's only
1576   // eq/ne.
1577   if (ICmpInst::isEquality(Pred)) {
1578     if (!VRegAndVal) {
1579       std::swap(RHS, LHS);
1580       VRegAndVal = getConstantVRegValWithLookThrough(RHS, MRI);
1581       AndInst = getOpcodeDef(TargetOpcode::G_AND, LHS, MRI);
1582     }
1583 
1584     if (VRegAndVal && VRegAndVal->Value == 0) {
1585       // If there's a G_AND feeding into this branch, try to fold it away by
1586       // emitting a TB(N)Z instead.
1587       //
1588       // Note: If we have LT, then it *is* possible to fold, but it wouldn't be
1589       // beneficial. When we have an AND and LT, we need a TST/ANDS, so folding
1590       // would be redundant.
1591       if (AndInst &&
1592           tryOptAndIntoCompareBranch(
1593               *AndInst, /*Invert = */ Pred == CmpInst::ICMP_NE, DestMBB, MIB)) {
1594         I.eraseFromParent();
1595         return true;
1596       }
1597 
1598       // Otherwise, try to emit a CB(N)Z instead.
1599       auto LHSTy = MRI.getType(LHS);
1600       if (!LHSTy.isVector() && LHSTy.getSizeInBits() <= 64) {
1601         emitCBZ(LHS, /*IsNegative = */ Pred == CmpInst::ICMP_NE, DestMBB, MIB);
1602         I.eraseFromParent();
1603         return true;
1604       }
1605     }
1606   }
1607 
1608   return false;
1609 }
1610 
1611 bool AArch64InstructionSelector::selectCompareBranchFedByICmp(
1612     MachineInstr &I, MachineInstr &ICmp, MachineIRBuilder &MIB) const {
1613   assert(ICmp.getOpcode() == TargetOpcode::G_ICMP);
1614   assert(I.getOpcode() == TargetOpcode::G_BRCOND);
1615   if (tryOptCompareBranchFedByICmp(I, ICmp, MIB))
1616     return true;
1617 
1618   // Couldn't optimize. Emit a compare + a Bcc.
1619   MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
1620   auto PredOp = ICmp.getOperand(1);
1621   emitIntegerCompare(ICmp.getOperand(2), ICmp.getOperand(3), PredOp, MIB);
1622   const AArch64CC::CondCode CC = changeICMPPredToAArch64CC(
1623       static_cast<CmpInst::Predicate>(PredOp.getPredicate()));
1624   MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC).addMBB(DestMBB);
1625   I.eraseFromParent();
1626   return true;
1627 }
1628 
1629 bool AArch64InstructionSelector::selectCompareBranch(
1630     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1631   Register CondReg = I.getOperand(0).getReg();
1632   MachineInstr *CCMI = MRI.getVRegDef(CondReg);
1633   if (CCMI->getOpcode() == TargetOpcode::G_TRUNC) {
1634     CondReg = CCMI->getOperand(1).getReg();
1635     CCMI = MRI.getVRegDef(CondReg);
1636   }
1637 
1638   // Try to select the G_BRCOND using whatever is feeding the condition if
1639   // possible.
1640   MachineIRBuilder MIB(I);
1641   unsigned CCMIOpc = CCMI->getOpcode();
1642   if (CCMIOpc == TargetOpcode::G_FCMP)
1643     return selectCompareBranchFedByFCmp(I, *CCMI, MIB);
1644   if (CCMIOpc == TargetOpcode::G_ICMP)
1645     return selectCompareBranchFedByICmp(I, *CCMI, MIB);
1646 
1647   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z
1648   // instructions will not be produced, as they are conditional branch
1649   // instructions that do not set flags.
1650   if (ProduceNonFlagSettingCondBr) {
1651     emitTestBit(CondReg, /*Bit = */ 0, /*IsNegative = */ true,
1652                 I.getOperand(1).getMBB(), MIB);
1653     I.eraseFromParent();
1654     return true;
1655   }
1656 
1657   // Can't emit TB(N)Z/CB(N)Z. Emit a tst + bcc instead.
1658   auto TstMI =
1659       MIB.buildInstr(AArch64::ANDSWri, {LLT::scalar(32)}, {CondReg}).addImm(1);
1660   constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
1661   auto Bcc = MIB.buildInstr(AArch64::Bcc)
1662                  .addImm(AArch64CC::EQ)
1663                  .addMBB(I.getOperand(1).getMBB());
1664   I.eraseFromParent();
1665   return constrainSelectedInstRegOperands(*Bcc, TII, TRI, RBI);
1666 }
1667 
1668 /// Returns the element immediate value of a vector shift operand if found.
1669 /// This needs to detect a splat-like operation, e.g. a G_BUILD_VECTOR.
1670 static Optional<int64_t> getVectorShiftImm(Register Reg,
1671                                            MachineRegisterInfo &MRI) {
1672   assert(MRI.getType(Reg).isVector() && "Expected a *vector* shift operand");
1673   MachineInstr *OpMI = MRI.getVRegDef(Reg);
1674   assert(OpMI && "Expected to find a vreg def for vector shift operand");
1675   return getAArch64VectorSplatScalar(*OpMI, MRI);
1676 }
1677 
1678 /// Matches and returns the shift immediate value for a SHL instruction given
1679 /// a shift operand.
1680 static Optional<int64_t> getVectorSHLImm(LLT SrcTy, Register Reg, MachineRegisterInfo &MRI) {
1681   Optional<int64_t> ShiftImm = getVectorShiftImm(Reg, MRI);
1682   if (!ShiftImm)
1683     return None;
1684   // Check the immediate is in range for a SHL.
1685   int64_t Imm = *ShiftImm;
1686   if (Imm < 0)
1687     return None;
1688   switch (SrcTy.getElementType().getSizeInBits()) {
1689   default:
1690     LLVM_DEBUG(dbgs() << "Unhandled element type for vector shift");
1691     return None;
1692   case 8:
1693     if (Imm > 7)
1694       return None;
1695     break;
1696   case 16:
1697     if (Imm > 15)
1698       return None;
1699     break;
1700   case 32:
1701     if (Imm > 31)
1702       return None;
1703     break;
1704   case 64:
1705     if (Imm > 63)
1706       return None;
1707     break;
1708   }
1709   return Imm;
1710 }
1711 
1712 bool AArch64InstructionSelector::selectVectorSHL(
1713     MachineInstr &I, MachineRegisterInfo &MRI) const {
1714   assert(I.getOpcode() == TargetOpcode::G_SHL);
1715   Register DstReg = I.getOperand(0).getReg();
1716   const LLT Ty = MRI.getType(DstReg);
1717   Register Src1Reg = I.getOperand(1).getReg();
1718   Register Src2Reg = I.getOperand(2).getReg();
1719 
1720   if (!Ty.isVector())
1721     return false;
1722 
1723   // Check if we have a vector of constants on RHS that we can select as the
1724   // immediate form.
1725   Optional<int64_t> ImmVal = getVectorSHLImm(Ty, Src2Reg, MRI);
1726 
1727   unsigned Opc = 0;
1728   if (Ty == LLT::vector(2, 64)) {
1729     Opc = ImmVal ? AArch64::SHLv2i64_shift : AArch64::USHLv2i64;
1730   } else if (Ty == LLT::vector(4, 32)) {
1731     Opc = ImmVal ? AArch64::SHLv4i32_shift : AArch64::USHLv4i32;
1732   } else if (Ty == LLT::vector(2, 32)) {
1733     Opc = ImmVal ? AArch64::SHLv2i32_shift : AArch64::USHLv2i32;
1734   } else if (Ty == LLT::vector(4, 16)) {
1735     Opc = ImmVal ? AArch64::SHLv4i16_shift : AArch64::USHLv4i16;
1736   } else if (Ty == LLT::vector(8, 16)) {
1737     Opc = ImmVal ? AArch64::SHLv8i16_shift : AArch64::USHLv8i16;
1738   } else if (Ty == LLT::vector(16, 8)) {
1739     Opc = ImmVal ? AArch64::SHLv16i8_shift : AArch64::USHLv16i8;
1740   } else if (Ty == LLT::vector(8, 8)) {
1741     Opc = ImmVal ? AArch64::SHLv8i8_shift : AArch64::USHLv8i8;
1742   } else {
1743     LLVM_DEBUG(dbgs() << "Unhandled G_SHL type");
1744     return false;
1745   }
1746 
1747   MachineIRBuilder MIB(I);
1748   auto Shl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg});
1749   if (ImmVal)
1750     Shl.addImm(*ImmVal);
1751   else
1752     Shl.addUse(Src2Reg);
1753   constrainSelectedInstRegOperands(*Shl, TII, TRI, RBI);
1754   I.eraseFromParent();
1755   return true;
1756 }
1757 
1758 bool AArch64InstructionSelector::selectVectorAshrLshr(
1759     MachineInstr &I, MachineRegisterInfo &MRI) const {
1760   assert(I.getOpcode() == TargetOpcode::G_ASHR ||
1761          I.getOpcode() == TargetOpcode::G_LSHR);
1762   Register DstReg = I.getOperand(0).getReg();
1763   const LLT Ty = MRI.getType(DstReg);
1764   Register Src1Reg = I.getOperand(1).getReg();
1765   Register Src2Reg = I.getOperand(2).getReg();
1766 
1767   if (!Ty.isVector())
1768     return false;
1769 
1770   bool IsASHR = I.getOpcode() == TargetOpcode::G_ASHR;
1771 
1772   // We expect the immediate case to be lowered in the PostLegalCombiner to
1773   // AArch64ISD::VASHR or AArch64ISD::VLSHR equivalents.
1774 
1775   // There is not a shift right register instruction, but the shift left
1776   // register instruction takes a signed value, where negative numbers specify a
1777   // right shift.
1778 
1779   unsigned Opc = 0;
1780   unsigned NegOpc = 0;
1781   const TargetRegisterClass *RC =
1782       getRegClassForTypeOnBank(Ty, RBI.getRegBank(AArch64::FPRRegBankID), RBI);
1783   if (Ty == LLT::vector(2, 64)) {
1784     Opc = IsASHR ? AArch64::SSHLv2i64 : AArch64::USHLv2i64;
1785     NegOpc = AArch64::NEGv2i64;
1786   } else if (Ty == LLT::vector(4, 32)) {
1787     Opc = IsASHR ? AArch64::SSHLv4i32 : AArch64::USHLv4i32;
1788     NegOpc = AArch64::NEGv4i32;
1789   } else if (Ty == LLT::vector(2, 32)) {
1790     Opc = IsASHR ? AArch64::SSHLv2i32 : AArch64::USHLv2i32;
1791     NegOpc = AArch64::NEGv2i32;
1792   } else if (Ty == LLT::vector(4, 16)) {
1793     Opc = IsASHR ? AArch64::SSHLv4i16 : AArch64::USHLv4i16;
1794     NegOpc = AArch64::NEGv4i16;
1795   } else if (Ty == LLT::vector(8, 16)) {
1796     Opc = IsASHR ? AArch64::SSHLv8i16 : AArch64::USHLv8i16;
1797     NegOpc = AArch64::NEGv8i16;
1798   } else if (Ty == LLT::vector(16, 8)) {
1799     Opc = IsASHR ? AArch64::SSHLv16i8 : AArch64::USHLv16i8;
1800     NegOpc = AArch64::NEGv16i8;
1801   } else if (Ty == LLT::vector(8, 8)) {
1802     Opc = IsASHR ? AArch64::SSHLv8i8 : AArch64::USHLv8i8;
1803     NegOpc = AArch64::NEGv8i8;
1804   } else {
1805     LLVM_DEBUG(dbgs() << "Unhandled G_ASHR type");
1806     return false;
1807   }
1808 
1809   MachineIRBuilder MIB(I);
1810   auto Neg = MIB.buildInstr(NegOpc, {RC}, {Src2Reg});
1811   constrainSelectedInstRegOperands(*Neg, TII, TRI, RBI);
1812   auto SShl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg, Neg});
1813   constrainSelectedInstRegOperands(*SShl, TII, TRI, RBI);
1814   I.eraseFromParent();
1815   return true;
1816 }
1817 
1818 bool AArch64InstructionSelector::selectVaStartAAPCS(
1819     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1820   return false;
1821 }
1822 
1823 bool AArch64InstructionSelector::selectVaStartDarwin(
1824     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1825   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1826   Register ListReg = I.getOperand(0).getReg();
1827 
1828   Register ArgsAddrReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1829 
1830   auto MIB =
1831       BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::ADDXri))
1832           .addDef(ArgsAddrReg)
1833           .addFrameIndex(FuncInfo->getVarArgsStackIndex())
1834           .addImm(0)
1835           .addImm(0);
1836 
1837   constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1838 
1839   MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::STRXui))
1840             .addUse(ArgsAddrReg)
1841             .addUse(ListReg)
1842             .addImm(0)
1843             .addMemOperand(*I.memoperands_begin());
1844 
1845   constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1846   I.eraseFromParent();
1847   return true;
1848 }
1849 
1850 void AArch64InstructionSelector::materializeLargeCMVal(
1851     MachineInstr &I, const Value *V, unsigned OpFlags) const {
1852   MachineBasicBlock &MBB = *I.getParent();
1853   MachineFunction &MF = *MBB.getParent();
1854   MachineRegisterInfo &MRI = MF.getRegInfo();
1855   MachineIRBuilder MIB(I);
1856 
1857   auto MovZ = MIB.buildInstr(AArch64::MOVZXi, {&AArch64::GPR64RegClass}, {});
1858   MovZ->addOperand(MF, I.getOperand(1));
1859   MovZ->getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_G0 |
1860                                      AArch64II::MO_NC);
1861   MovZ->addOperand(MF, MachineOperand::CreateImm(0));
1862   constrainSelectedInstRegOperands(*MovZ, TII, TRI, RBI);
1863 
1864   auto BuildMovK = [&](Register SrcReg, unsigned char Flags, unsigned Offset,
1865                        Register ForceDstReg) {
1866     Register DstReg = ForceDstReg
1867                           ? ForceDstReg
1868                           : MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1869     auto MovI = MIB.buildInstr(AArch64::MOVKXi).addDef(DstReg).addUse(SrcReg);
1870     if (auto *GV = dyn_cast<GlobalValue>(V)) {
1871       MovI->addOperand(MF, MachineOperand::CreateGA(
1872                                GV, MovZ->getOperand(1).getOffset(), Flags));
1873     } else {
1874       MovI->addOperand(
1875           MF, MachineOperand::CreateBA(cast<BlockAddress>(V),
1876                                        MovZ->getOperand(1).getOffset(), Flags));
1877     }
1878     MovI->addOperand(MF, MachineOperand::CreateImm(Offset));
1879     constrainSelectedInstRegOperands(*MovI, TII, TRI, RBI);
1880     return DstReg;
1881   };
1882   Register DstReg = BuildMovK(MovZ.getReg(0),
1883                               AArch64II::MO_G1 | AArch64II::MO_NC, 16, 0);
1884   DstReg = BuildMovK(DstReg, AArch64II::MO_G2 | AArch64II::MO_NC, 32, 0);
1885   BuildMovK(DstReg, AArch64II::MO_G3, 48, I.getOperand(0).getReg());
1886 }
1887 
1888 bool AArch64InstructionSelector::preISelLower(MachineInstr &I) {
1889   MachineBasicBlock &MBB = *I.getParent();
1890   MachineFunction &MF = *MBB.getParent();
1891   MachineRegisterInfo &MRI = MF.getRegInfo();
1892 
1893   switch (I.getOpcode()) {
1894   case TargetOpcode::G_SHL:
1895   case TargetOpcode::G_ASHR:
1896   case TargetOpcode::G_LSHR: {
1897     // These shifts are legalized to have 64 bit shift amounts because we want
1898     // to take advantage of the existing imported selection patterns that assume
1899     // the immediates are s64s. However, if the shifted type is 32 bits and for
1900     // some reason we receive input GMIR that has an s64 shift amount that's not
1901     // a G_CONSTANT, insert a truncate so that we can still select the s32
1902     // register-register variant.
1903     Register SrcReg = I.getOperand(1).getReg();
1904     Register ShiftReg = I.getOperand(2).getReg();
1905     const LLT ShiftTy = MRI.getType(ShiftReg);
1906     const LLT SrcTy = MRI.getType(SrcReg);
1907     if (SrcTy.isVector())
1908       return false;
1909     assert(!ShiftTy.isVector() && "unexpected vector shift ty");
1910     if (SrcTy.getSizeInBits() != 32 || ShiftTy.getSizeInBits() != 64)
1911       return false;
1912     auto *AmtMI = MRI.getVRegDef(ShiftReg);
1913     assert(AmtMI && "could not find a vreg definition for shift amount");
1914     if (AmtMI->getOpcode() != TargetOpcode::G_CONSTANT) {
1915       // Insert a subregister copy to implement a 64->32 trunc
1916       MachineIRBuilder MIB(I);
1917       auto Trunc = MIB.buildInstr(TargetOpcode::COPY, {SrcTy}, {})
1918                        .addReg(ShiftReg, 0, AArch64::sub_32);
1919       MRI.setRegBank(Trunc.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
1920       I.getOperand(2).setReg(Trunc.getReg(0));
1921     }
1922     return true;
1923   }
1924   case TargetOpcode::G_STORE: {
1925     bool Changed = contractCrossBankCopyIntoStore(I, MRI);
1926     MachineOperand &SrcOp = I.getOperand(0);
1927     if (MRI.getType(SrcOp.getReg()).isPointer()) {
1928       // Allow matching with imported patterns for stores of pointers. Unlike
1929       // G_LOAD/G_PTR_ADD, we may not have selected all users. So, emit a copy
1930       // and constrain.
1931       MachineIRBuilder MIB(I);
1932       auto Copy = MIB.buildCopy(LLT::scalar(64), SrcOp);
1933       Register NewSrc = Copy.getReg(0);
1934       SrcOp.setReg(NewSrc);
1935       RBI.constrainGenericRegister(NewSrc, AArch64::GPR64RegClass, MRI);
1936       Changed = true;
1937     }
1938     return Changed;
1939   }
1940   case TargetOpcode::G_PTR_ADD:
1941     return convertPtrAddToAdd(I, MRI);
1942   case TargetOpcode::G_LOAD: {
1943     // For scalar loads of pointers, we try to convert the dest type from p0
1944     // to s64 so that our imported patterns can match. Like with the G_PTR_ADD
1945     // conversion, this should be ok because all users should have been
1946     // selected already, so the type doesn't matter for them.
1947     Register DstReg = I.getOperand(0).getReg();
1948     const LLT DstTy = MRI.getType(DstReg);
1949     if (!DstTy.isPointer())
1950       return false;
1951     MRI.setType(DstReg, LLT::scalar(64));
1952     return true;
1953   }
1954   case AArch64::G_DUP: {
1955     // Convert the type from p0 to s64 to help selection.
1956     LLT DstTy = MRI.getType(I.getOperand(0).getReg());
1957     if (!DstTy.getElementType().isPointer())
1958       return false;
1959     MachineIRBuilder MIB(I);
1960     auto NewSrc = MIB.buildCopy(LLT::scalar(64), I.getOperand(1).getReg());
1961     MRI.setType(I.getOperand(0).getReg(),
1962                 DstTy.changeElementType(LLT::scalar(64)));
1963     MRI.setRegClass(NewSrc.getReg(0), &AArch64::GPR64RegClass);
1964     I.getOperand(1).setReg(NewSrc.getReg(0));
1965     return true;
1966   }
1967   case TargetOpcode::G_UITOFP:
1968   case TargetOpcode::G_SITOFP: {
1969     // If both source and destination regbanks are FPR, then convert the opcode
1970     // to G_SITOF so that the importer can select it to an fpr variant.
1971     // Otherwise, it ends up matching an fpr/gpr variant and adding a cross-bank
1972     // copy.
1973     Register SrcReg = I.getOperand(1).getReg();
1974     LLT SrcTy = MRI.getType(SrcReg);
1975     LLT DstTy = MRI.getType(I.getOperand(0).getReg());
1976     if (SrcTy.isVector() || SrcTy.getSizeInBits() != DstTy.getSizeInBits())
1977       return false;
1978 
1979     if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() == AArch64::FPRRegBankID) {
1980       if (I.getOpcode() == TargetOpcode::G_SITOFP)
1981         I.setDesc(TII.get(AArch64::G_SITOF));
1982       else
1983         I.setDesc(TII.get(AArch64::G_UITOF));
1984       return true;
1985     }
1986     return false;
1987   }
1988   default:
1989     return false;
1990   }
1991 }
1992 
1993 /// This lowering tries to look for G_PTR_ADD instructions and then converts
1994 /// them to a standard G_ADD with a COPY on the source.
1995 ///
1996 /// The motivation behind this is to expose the add semantics to the imported
1997 /// tablegen patterns. We shouldn't need to check for uses being loads/stores,
1998 /// because the selector works bottom up, uses before defs. By the time we
1999 /// end up trying to select a G_PTR_ADD, we should have already attempted to
2000 /// fold this into addressing modes and were therefore unsuccessful.
2001 bool AArch64InstructionSelector::convertPtrAddToAdd(
2002     MachineInstr &I, MachineRegisterInfo &MRI) {
2003   assert(I.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
2004   Register DstReg = I.getOperand(0).getReg();
2005   Register AddOp1Reg = I.getOperand(1).getReg();
2006   const LLT PtrTy = MRI.getType(DstReg);
2007   if (PtrTy.getAddressSpace() != 0)
2008     return false;
2009 
2010   MachineIRBuilder MIB(I);
2011   const LLT CastPtrTy = PtrTy.isVector() ? LLT::vector(2, 64) : LLT::scalar(64);
2012   auto PtrToInt = MIB.buildPtrToInt(CastPtrTy, AddOp1Reg);
2013   // Set regbanks on the registers.
2014   if (PtrTy.isVector())
2015     MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::FPRRegBankID));
2016   else
2017     MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
2018 
2019   // Now turn the %dst(p0) = G_PTR_ADD %base, off into:
2020   // %dst(intty) = G_ADD %intbase, off
2021   I.setDesc(TII.get(TargetOpcode::G_ADD));
2022   MRI.setType(DstReg, CastPtrTy);
2023   I.getOperand(1).setReg(PtrToInt.getReg(0));
2024   if (!select(*PtrToInt)) {
2025     LLVM_DEBUG(dbgs() << "Failed to select G_PTRTOINT in convertPtrAddToAdd");
2026     return false;
2027   }
2028 
2029   // Also take the opportunity here to try to do some optimization.
2030   // Try to convert this into a G_SUB if the offset is a 0-x negate idiom.
2031   Register NegatedReg;
2032   if (!mi_match(I.getOperand(2).getReg(), MRI, m_Neg(m_Reg(NegatedReg))))
2033     return true;
2034   I.getOperand(2).setReg(NegatedReg);
2035   I.setDesc(TII.get(TargetOpcode::G_SUB));
2036   return true;
2037 }
2038 
2039 bool AArch64InstructionSelector::earlySelectSHL(
2040     MachineInstr &I, MachineRegisterInfo &MRI) const {
2041   // We try to match the immediate variant of LSL, which is actually an alias
2042   // for a special case of UBFM. Otherwise, we fall back to the imported
2043   // selector which will match the register variant.
2044   assert(I.getOpcode() == TargetOpcode::G_SHL && "unexpected op");
2045   const auto &MO = I.getOperand(2);
2046   auto VRegAndVal = getConstantVRegVal(MO.getReg(), MRI);
2047   if (!VRegAndVal)
2048     return false;
2049 
2050   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2051   if (DstTy.isVector())
2052     return false;
2053   bool Is64Bit = DstTy.getSizeInBits() == 64;
2054   auto Imm1Fn = Is64Bit ? selectShiftA_64(MO) : selectShiftA_32(MO);
2055   auto Imm2Fn = Is64Bit ? selectShiftB_64(MO) : selectShiftB_32(MO);
2056   MachineIRBuilder MIB(I);
2057 
2058   if (!Imm1Fn || !Imm2Fn)
2059     return false;
2060 
2061   auto NewI =
2062       MIB.buildInstr(Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri,
2063                      {I.getOperand(0).getReg()}, {I.getOperand(1).getReg()});
2064 
2065   for (auto &RenderFn : *Imm1Fn)
2066     RenderFn(NewI);
2067   for (auto &RenderFn : *Imm2Fn)
2068     RenderFn(NewI);
2069 
2070   I.eraseFromParent();
2071   return constrainSelectedInstRegOperands(*NewI, TII, TRI, RBI);
2072 }
2073 
2074 bool AArch64InstructionSelector::contractCrossBankCopyIntoStore(
2075     MachineInstr &I, MachineRegisterInfo &MRI) {
2076   assert(I.getOpcode() == TargetOpcode::G_STORE && "Expected G_STORE");
2077   // If we're storing a scalar, it doesn't matter what register bank that
2078   // scalar is on. All that matters is the size.
2079   //
2080   // So, if we see something like this (with a 32-bit scalar as an example):
2081   //
2082   // %x:gpr(s32) = ... something ...
2083   // %y:fpr(s32) = COPY %x:gpr(s32)
2084   // G_STORE %y:fpr(s32)
2085   //
2086   // We can fix this up into something like this:
2087   //
2088   // G_STORE %x:gpr(s32)
2089   //
2090   // And then continue the selection process normally.
2091   Register DefDstReg = getSrcRegIgnoringCopies(I.getOperand(0).getReg(), MRI);
2092   if (!DefDstReg.isValid())
2093     return false;
2094   LLT DefDstTy = MRI.getType(DefDstReg);
2095   Register StoreSrcReg = I.getOperand(0).getReg();
2096   LLT StoreSrcTy = MRI.getType(StoreSrcReg);
2097 
2098   // If we get something strange like a physical register, then we shouldn't
2099   // go any further.
2100   if (!DefDstTy.isValid())
2101     return false;
2102 
2103   // Are the source and dst types the same size?
2104   if (DefDstTy.getSizeInBits() != StoreSrcTy.getSizeInBits())
2105     return false;
2106 
2107   if (RBI.getRegBank(StoreSrcReg, MRI, TRI) ==
2108       RBI.getRegBank(DefDstReg, MRI, TRI))
2109     return false;
2110 
2111   // We have a cross-bank copy, which is entering a store. Let's fold it.
2112   I.getOperand(0).setReg(DefDstReg);
2113   return true;
2114 }
2115 
2116 bool AArch64InstructionSelector::earlySelect(MachineInstr &I) const {
2117   assert(I.getParent() && "Instruction should be in a basic block!");
2118   assert(I.getParent()->getParent() && "Instruction should be in a function!");
2119 
2120   MachineBasicBlock &MBB = *I.getParent();
2121   MachineFunction &MF = *MBB.getParent();
2122   MachineRegisterInfo &MRI = MF.getRegInfo();
2123 
2124   switch (I.getOpcode()) {
2125   case AArch64::G_DUP: {
2126     // Before selecting a DUP instruction, check if it is better selected as a
2127     // MOV or load from a constant pool.
2128     Register Src = I.getOperand(1).getReg();
2129     auto ValAndVReg = getConstantVRegValWithLookThrough(Src, MRI);
2130     if (!ValAndVReg)
2131       return false;
2132     LLVMContext &Ctx = MF.getFunction().getContext();
2133     Register Dst = I.getOperand(0).getReg();
2134     auto *CV = ConstantDataVector::getSplat(
2135         MRI.getType(Dst).getNumElements(),
2136         ConstantInt::get(Type::getIntNTy(Ctx, MRI.getType(Src).getSizeInBits()),
2137                          ValAndVReg->Value));
2138     MachineIRBuilder MIRBuilder(I);
2139     if (!emitConstantVector(Dst, CV, MIRBuilder, MRI))
2140       return false;
2141     I.eraseFromParent();
2142     return true;
2143   }
2144   case TargetOpcode::G_BR: {
2145     // If the branch jumps to the fallthrough block, don't bother emitting it.
2146     // Only do this for -O0 for a good code size improvement, because when
2147     // optimizations are enabled we want to leave this choice to
2148     // MachineBlockPlacement.
2149     bool EnableOpt = MF.getTarget().getOptLevel() != CodeGenOpt::None;
2150     if (EnableOpt || !MBB.isLayoutSuccessor(I.getOperand(0).getMBB()))
2151       return false;
2152     I.eraseFromParent();
2153     return true;
2154   }
2155   case TargetOpcode::G_SHL:
2156     return earlySelectSHL(I, MRI);
2157   case TargetOpcode::G_CONSTANT: {
2158     bool IsZero = false;
2159     if (I.getOperand(1).isCImm())
2160       IsZero = I.getOperand(1).getCImm()->getZExtValue() == 0;
2161     else if (I.getOperand(1).isImm())
2162       IsZero = I.getOperand(1).getImm() == 0;
2163 
2164     if (!IsZero)
2165       return false;
2166 
2167     Register DefReg = I.getOperand(0).getReg();
2168     LLT Ty = MRI.getType(DefReg);
2169     if (Ty.getSizeInBits() == 64) {
2170       I.getOperand(1).ChangeToRegister(AArch64::XZR, false);
2171       RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass, MRI);
2172     } else if (Ty.getSizeInBits() == 32) {
2173       I.getOperand(1).ChangeToRegister(AArch64::WZR, false);
2174       RBI.constrainGenericRegister(DefReg, AArch64::GPR32RegClass, MRI);
2175     } else
2176       return false;
2177 
2178     I.setDesc(TII.get(TargetOpcode::COPY));
2179     return true;
2180   }
2181 
2182   case TargetOpcode::G_ADD: {
2183     // Check if this is being fed by a G_ICMP on either side.
2184     //
2185     // (cmp pred, x, y) + z
2186     //
2187     // In the above case, when the cmp is true, we increment z by 1. So, we can
2188     // fold the add into the cset for the cmp by using cinc.
2189     //
2190     // FIXME: This would probably be a lot nicer in PostLegalizerLowering.
2191     Register X = I.getOperand(1).getReg();
2192 
2193     // Only handle scalars. Scalar G_ICMP is only legal for s32, so bail out
2194     // early if we see it.
2195     LLT Ty = MRI.getType(X);
2196     if (Ty.isVector() || Ty.getSizeInBits() != 32)
2197       return false;
2198 
2199     Register CmpReg = I.getOperand(2).getReg();
2200     MachineInstr *Cmp = getOpcodeDef(TargetOpcode::G_ICMP, CmpReg, MRI);
2201     if (!Cmp) {
2202       std::swap(X, CmpReg);
2203       Cmp = getOpcodeDef(TargetOpcode::G_ICMP, CmpReg, MRI);
2204       if (!Cmp)
2205         return false;
2206     }
2207     MachineIRBuilder MIRBuilder(I);
2208     auto Pred =
2209         static_cast<CmpInst::Predicate>(Cmp->getOperand(1).getPredicate());
2210     emitIntegerCompare(Cmp->getOperand(2), Cmp->getOperand(3),
2211                        Cmp->getOperand(1), MIRBuilder);
2212     emitCSetForICMP(I.getOperand(0).getReg(), Pred, MIRBuilder, X);
2213     I.eraseFromParent();
2214     return true;
2215   }
2216   default:
2217     return false;
2218   }
2219 }
2220 
2221 bool AArch64InstructionSelector::select(MachineInstr &I) {
2222   assert(I.getParent() && "Instruction should be in a basic block!");
2223   assert(I.getParent()->getParent() && "Instruction should be in a function!");
2224 
2225   MachineBasicBlock &MBB = *I.getParent();
2226   MachineFunction &MF = *MBB.getParent();
2227   MachineRegisterInfo &MRI = MF.getRegInfo();
2228 
2229   const AArch64Subtarget *Subtarget =
2230       &static_cast<const AArch64Subtarget &>(MF.getSubtarget());
2231   if (Subtarget->requiresStrictAlign()) {
2232     // We don't support this feature yet.
2233     LLVM_DEBUG(dbgs() << "AArch64 GISel does not support strict-align yet\n");
2234     return false;
2235   }
2236 
2237   unsigned Opcode = I.getOpcode();
2238   // G_PHI requires same handling as PHI
2239   if (!I.isPreISelOpcode() || Opcode == TargetOpcode::G_PHI) {
2240     // Certain non-generic instructions also need some special handling.
2241 
2242     if (Opcode ==  TargetOpcode::LOAD_STACK_GUARD)
2243       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2244 
2245     if (Opcode == TargetOpcode::PHI || Opcode == TargetOpcode::G_PHI) {
2246       const Register DefReg = I.getOperand(0).getReg();
2247       const LLT DefTy = MRI.getType(DefReg);
2248 
2249       const RegClassOrRegBank &RegClassOrBank =
2250         MRI.getRegClassOrRegBank(DefReg);
2251 
2252       const TargetRegisterClass *DefRC
2253         = RegClassOrBank.dyn_cast<const TargetRegisterClass *>();
2254       if (!DefRC) {
2255         if (!DefTy.isValid()) {
2256           LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
2257           return false;
2258         }
2259         const RegisterBank &RB = *RegClassOrBank.get<const RegisterBank *>();
2260         DefRC = getRegClassForTypeOnBank(DefTy, RB, RBI);
2261         if (!DefRC) {
2262           LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
2263           return false;
2264         }
2265       }
2266 
2267       I.setDesc(TII.get(TargetOpcode::PHI));
2268 
2269       return RBI.constrainGenericRegister(DefReg, *DefRC, MRI);
2270     }
2271 
2272     if (I.isCopy())
2273       return selectCopy(I, TII, MRI, TRI, RBI);
2274 
2275     return true;
2276   }
2277 
2278 
2279   if (I.getNumOperands() != I.getNumExplicitOperands()) {
2280     LLVM_DEBUG(
2281         dbgs() << "Generic instruction has unexpected implicit operands\n");
2282     return false;
2283   }
2284 
2285   // Try to do some lowering before we start instruction selecting. These
2286   // lowerings are purely transformations on the input G_MIR and so selection
2287   // must continue after any modification of the instruction.
2288   if (preISelLower(I)) {
2289     Opcode = I.getOpcode(); // The opcode may have been modified, refresh it.
2290   }
2291 
2292   // There may be patterns where the importer can't deal with them optimally,
2293   // but does select it to a suboptimal sequence so our custom C++ selection
2294   // code later never has a chance to work on it. Therefore, we have an early
2295   // selection attempt here to give priority to certain selection routines
2296   // over the imported ones.
2297   if (earlySelect(I))
2298     return true;
2299 
2300   if (selectImpl(I, *CoverageInfo))
2301     return true;
2302 
2303   LLT Ty =
2304       I.getOperand(0).isReg() ? MRI.getType(I.getOperand(0).getReg()) : LLT{};
2305 
2306   MachineIRBuilder MIB(I);
2307 
2308   switch (Opcode) {
2309   case TargetOpcode::G_SBFX:
2310   case TargetOpcode::G_UBFX: {
2311     static const unsigned OpcTable[2][2] = {
2312         {AArch64::UBFMWri, AArch64::UBFMXri},
2313         {AArch64::SBFMWri, AArch64::SBFMXri}};
2314     bool IsSigned = Opcode == TargetOpcode::G_SBFX;
2315     unsigned Size = Ty.getSizeInBits();
2316     unsigned Opc = OpcTable[IsSigned][Size == 64];
2317     auto Cst1 =
2318         getConstantVRegValWithLookThrough(I.getOperand(2).getReg(), MRI);
2319     assert(Cst1 && "Should have gotten a constant for src 1?");
2320     auto Cst2 =
2321         getConstantVRegValWithLookThrough(I.getOperand(3).getReg(), MRI);
2322     assert(Cst2 && "Should have gotten a constant for src 2?");
2323     auto LSB = Cst1->Value.getZExtValue();
2324     auto Width = Cst2->Value.getZExtValue();
2325     MachineIRBuilder MIB(I);
2326     auto BitfieldInst =
2327         MIB.buildInstr(Opc, {I.getOperand(0)}, {I.getOperand(1)})
2328             .addImm(LSB)
2329             .addImm(LSB + Width - 1);
2330     I.eraseFromParent();
2331     return constrainSelectedInstRegOperands(*BitfieldInst, TII, TRI, RBI);
2332   }
2333   case TargetOpcode::G_BRCOND:
2334     return selectCompareBranch(I, MF, MRI);
2335 
2336   case TargetOpcode::G_BRINDIRECT: {
2337     I.setDesc(TII.get(AArch64::BR));
2338     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2339   }
2340 
2341   case TargetOpcode::G_BRJT:
2342     return selectBrJT(I, MRI);
2343 
2344   case AArch64::G_ADD_LOW: {
2345     // This op may have been separated from it's ADRP companion by the localizer
2346     // or some other code motion pass. Given that many CPUs will try to
2347     // macro fuse these operations anyway, select this into a MOVaddr pseudo
2348     // which will later be expanded into an ADRP+ADD pair after scheduling.
2349     MachineInstr *BaseMI = MRI.getVRegDef(I.getOperand(1).getReg());
2350     if (BaseMI->getOpcode() != AArch64::ADRP) {
2351       I.setDesc(TII.get(AArch64::ADDXri));
2352       I.addOperand(MachineOperand::CreateImm(0));
2353       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2354     }
2355     assert(TM.getCodeModel() == CodeModel::Small &&
2356            "Expected small code model");
2357     MachineIRBuilder MIB(I);
2358     auto Op1 = BaseMI->getOperand(1);
2359     auto Op2 = I.getOperand(2);
2360     auto MovAddr = MIB.buildInstr(AArch64::MOVaddr, {I.getOperand(0)}, {})
2361                        .addGlobalAddress(Op1.getGlobal(), Op1.getOffset(),
2362                                          Op1.getTargetFlags())
2363                        .addGlobalAddress(Op2.getGlobal(), Op2.getOffset(),
2364                                          Op2.getTargetFlags());
2365     I.eraseFromParent();
2366     return constrainSelectedInstRegOperands(*MovAddr, TII, TRI, RBI);
2367   }
2368 
2369   case TargetOpcode::G_BSWAP: {
2370     // Handle vector types for G_BSWAP directly.
2371     Register DstReg = I.getOperand(0).getReg();
2372     LLT DstTy = MRI.getType(DstReg);
2373 
2374     // We should only get vector types here; everything else is handled by the
2375     // importer right now.
2376     if (!DstTy.isVector() || DstTy.getSizeInBits() > 128) {
2377       LLVM_DEBUG(dbgs() << "Dst type for G_BSWAP currently unsupported.\n");
2378       return false;
2379     }
2380 
2381     // Only handle 4 and 2 element vectors for now.
2382     // TODO: 16-bit elements.
2383     unsigned NumElts = DstTy.getNumElements();
2384     if (NumElts != 4 && NumElts != 2) {
2385       LLVM_DEBUG(dbgs() << "Unsupported number of elements for G_BSWAP.\n");
2386       return false;
2387     }
2388 
2389     // Choose the correct opcode for the supported types. Right now, that's
2390     // v2s32, v4s32, and v2s64.
2391     unsigned Opc = 0;
2392     unsigned EltSize = DstTy.getElementType().getSizeInBits();
2393     if (EltSize == 32)
2394       Opc = (DstTy.getNumElements() == 2) ? AArch64::REV32v8i8
2395                                           : AArch64::REV32v16i8;
2396     else if (EltSize == 64)
2397       Opc = AArch64::REV64v16i8;
2398 
2399     // We should always get something by the time we get here...
2400     assert(Opc != 0 && "Didn't get an opcode for G_BSWAP?");
2401 
2402     I.setDesc(TII.get(Opc));
2403     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2404   }
2405 
2406   case TargetOpcode::G_FCONSTANT:
2407   case TargetOpcode::G_CONSTANT: {
2408     const bool isFP = Opcode == TargetOpcode::G_FCONSTANT;
2409 
2410     const LLT s8 = LLT::scalar(8);
2411     const LLT s16 = LLT::scalar(16);
2412     const LLT s32 = LLT::scalar(32);
2413     const LLT s64 = LLT::scalar(64);
2414     const LLT s128 = LLT::scalar(128);
2415     const LLT p0 = LLT::pointer(0, 64);
2416 
2417     const Register DefReg = I.getOperand(0).getReg();
2418     const LLT DefTy = MRI.getType(DefReg);
2419     const unsigned DefSize = DefTy.getSizeInBits();
2420     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2421 
2422     // FIXME: Redundant check, but even less readable when factored out.
2423     if (isFP) {
2424       if (Ty != s32 && Ty != s64 && Ty != s128) {
2425         LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
2426                           << " constant, expected: " << s32 << " or " << s64
2427                           << " or " << s128 << '\n');
2428         return false;
2429       }
2430 
2431       if (RB.getID() != AArch64::FPRRegBankID) {
2432         LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
2433                           << " constant on bank: " << RB
2434                           << ", expected: FPR\n");
2435         return false;
2436       }
2437 
2438       // The case when we have 0.0 is covered by tablegen. Reject it here so we
2439       // can be sure tablegen works correctly and isn't rescued by this code.
2440       // 0.0 is not covered by tablegen for FP128. So we will handle this
2441       // scenario in the code here.
2442       if (DefSize != 128 && I.getOperand(1).getFPImm()->isExactlyValue(0.0))
2443         return false;
2444     } else {
2445       // s32 and s64 are covered by tablegen.
2446       if (Ty != p0 && Ty != s8 && Ty != s16) {
2447         LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
2448                           << " constant, expected: " << s32 << ", " << s64
2449                           << ", or " << p0 << '\n');
2450         return false;
2451       }
2452 
2453       if (RB.getID() != AArch64::GPRRegBankID) {
2454         LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
2455                           << " constant on bank: " << RB
2456                           << ", expected: GPR\n");
2457         return false;
2458       }
2459     }
2460 
2461     // We allow G_CONSTANT of types < 32b.
2462     const unsigned MovOpc =
2463         DefSize == 64 ? AArch64::MOVi64imm : AArch64::MOVi32imm;
2464 
2465     if (isFP) {
2466       // Either emit a FMOV, or emit a copy to emit a normal mov.
2467       const TargetRegisterClass &GPRRC =
2468           DefSize == 32 ? AArch64::GPR32RegClass : AArch64::GPR64RegClass;
2469       const TargetRegisterClass &FPRRC =
2470           DefSize == 32 ? AArch64::FPR32RegClass
2471                         : (DefSize == 64 ? AArch64::FPR64RegClass
2472                                          : AArch64::FPR128RegClass);
2473 
2474       // For 64b values, emit a constant pool load instead.
2475       // For s32, use a cp load if we have optsize/minsize.
2476       if (DefSize == 64 || DefSize == 128 ||
2477           (DefSize == 32 && shouldOptForSize(&MF))) {
2478         auto *FPImm = I.getOperand(1).getFPImm();
2479         MachineIRBuilder MIB(I);
2480         auto *LoadMI = emitLoadFromConstantPool(FPImm, MIB);
2481         if (!LoadMI) {
2482           LLVM_DEBUG(dbgs() << "Failed to load double constant pool entry\n");
2483           return false;
2484         }
2485         MIB.buildCopy({DefReg}, {LoadMI->getOperand(0).getReg()});
2486         I.eraseFromParent();
2487         return RBI.constrainGenericRegister(DefReg, FPRRC, MRI);
2488       }
2489 
2490       // Nope. Emit a copy and use a normal mov instead.
2491       const Register DefGPRReg = MRI.createVirtualRegister(&GPRRC);
2492       MachineOperand &RegOp = I.getOperand(0);
2493       RegOp.setReg(DefGPRReg);
2494       MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
2495       MIB.buildCopy({DefReg}, {DefGPRReg});
2496 
2497       if (!RBI.constrainGenericRegister(DefReg, FPRRC, MRI)) {
2498         LLVM_DEBUG(dbgs() << "Failed to constrain G_FCONSTANT def operand\n");
2499         return false;
2500       }
2501 
2502       MachineOperand &ImmOp = I.getOperand(1);
2503       // FIXME: Is going through int64_t always correct?
2504       ImmOp.ChangeToImmediate(
2505           ImmOp.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
2506     } else if (I.getOperand(1).isCImm()) {
2507       uint64_t Val = I.getOperand(1).getCImm()->getZExtValue();
2508       I.getOperand(1).ChangeToImmediate(Val);
2509     } else if (I.getOperand(1).isImm()) {
2510       uint64_t Val = I.getOperand(1).getImm();
2511       I.getOperand(1).ChangeToImmediate(Val);
2512     }
2513 
2514     I.setDesc(TII.get(MovOpc));
2515     constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2516     return true;
2517   }
2518   case TargetOpcode::G_EXTRACT: {
2519     Register DstReg = I.getOperand(0).getReg();
2520     Register SrcReg = I.getOperand(1).getReg();
2521     LLT SrcTy = MRI.getType(SrcReg);
2522     LLT DstTy = MRI.getType(DstReg);
2523     (void)DstTy;
2524     unsigned SrcSize = SrcTy.getSizeInBits();
2525 
2526     if (SrcTy.getSizeInBits() > 64) {
2527       // This should be an extract of an s128, which is like a vector extract.
2528       if (SrcTy.getSizeInBits() != 128)
2529         return false;
2530       // Only support extracting 64 bits from an s128 at the moment.
2531       if (DstTy.getSizeInBits() != 64)
2532         return false;
2533 
2534       const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
2535       const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
2536       // Check we have the right regbank always.
2537       assert(SrcRB.getID() == AArch64::FPRRegBankID &&
2538              DstRB.getID() == AArch64::FPRRegBankID &&
2539              "Wrong extract regbank!");
2540       (void)SrcRB;
2541 
2542       // Emit the same code as a vector extract.
2543       // Offset must be a multiple of 64.
2544       unsigned Offset = I.getOperand(2).getImm();
2545       if (Offset % 64 != 0)
2546         return false;
2547       unsigned LaneIdx = Offset / 64;
2548       MachineIRBuilder MIB(I);
2549       MachineInstr *Extract = emitExtractVectorElt(
2550           DstReg, DstRB, LLT::scalar(64), SrcReg, LaneIdx, MIB);
2551       if (!Extract)
2552         return false;
2553       I.eraseFromParent();
2554       return true;
2555     }
2556 
2557     I.setDesc(TII.get(SrcSize == 64 ? AArch64::UBFMXri : AArch64::UBFMWri));
2558     MachineInstrBuilder(MF, I).addImm(I.getOperand(2).getImm() +
2559                                       Ty.getSizeInBits() - 1);
2560 
2561     if (SrcSize < 64) {
2562       assert(SrcSize == 32 && DstTy.getSizeInBits() == 16 &&
2563              "unexpected G_EXTRACT types");
2564       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2565     }
2566 
2567     DstReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
2568     MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
2569     MIB.buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
2570         .addReg(DstReg, 0, AArch64::sub_32);
2571     RBI.constrainGenericRegister(I.getOperand(0).getReg(),
2572                                  AArch64::GPR32RegClass, MRI);
2573     I.getOperand(0).setReg(DstReg);
2574 
2575     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2576   }
2577 
2578   case TargetOpcode::G_INSERT: {
2579     LLT SrcTy = MRI.getType(I.getOperand(2).getReg());
2580     LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2581     unsigned DstSize = DstTy.getSizeInBits();
2582     // Larger inserts are vectors, same-size ones should be something else by
2583     // now (split up or turned into COPYs).
2584     if (Ty.getSizeInBits() > 64 || SrcTy.getSizeInBits() > 32)
2585       return false;
2586 
2587     I.setDesc(TII.get(DstSize == 64 ? AArch64::BFMXri : AArch64::BFMWri));
2588     unsigned LSB = I.getOperand(3).getImm();
2589     unsigned Width = MRI.getType(I.getOperand(2).getReg()).getSizeInBits();
2590     I.getOperand(3).setImm((DstSize - LSB) % DstSize);
2591     MachineInstrBuilder(MF, I).addImm(Width - 1);
2592 
2593     if (DstSize < 64) {
2594       assert(DstSize == 32 && SrcTy.getSizeInBits() == 16 &&
2595              "unexpected G_INSERT types");
2596       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2597     }
2598 
2599     Register SrcReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
2600     BuildMI(MBB, I.getIterator(), I.getDebugLoc(),
2601             TII.get(AArch64::SUBREG_TO_REG))
2602         .addDef(SrcReg)
2603         .addImm(0)
2604         .addUse(I.getOperand(2).getReg())
2605         .addImm(AArch64::sub_32);
2606     RBI.constrainGenericRegister(I.getOperand(2).getReg(),
2607                                  AArch64::GPR32RegClass, MRI);
2608     I.getOperand(2).setReg(SrcReg);
2609 
2610     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2611   }
2612   case TargetOpcode::G_FRAME_INDEX: {
2613     // allocas and G_FRAME_INDEX are only supported in addrspace(0).
2614     if (Ty != LLT::pointer(0, 64)) {
2615       LLVM_DEBUG(dbgs() << "G_FRAME_INDEX pointer has type: " << Ty
2616                         << ", expected: " << LLT::pointer(0, 64) << '\n');
2617       return false;
2618     }
2619     I.setDesc(TII.get(AArch64::ADDXri));
2620 
2621     // MOs for a #0 shifted immediate.
2622     I.addOperand(MachineOperand::CreateImm(0));
2623     I.addOperand(MachineOperand::CreateImm(0));
2624 
2625     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2626   }
2627 
2628   case TargetOpcode::G_GLOBAL_VALUE: {
2629     auto GV = I.getOperand(1).getGlobal();
2630     if (GV->isThreadLocal())
2631       return selectTLSGlobalValue(I, MRI);
2632 
2633     unsigned OpFlags = STI.ClassifyGlobalReference(GV, TM);
2634     if (OpFlags & AArch64II::MO_GOT) {
2635       I.setDesc(TII.get(AArch64::LOADgot));
2636       I.getOperand(1).setTargetFlags(OpFlags);
2637     } else if (TM.getCodeModel() == CodeModel::Large) {
2638       // Materialize the global using movz/movk instructions.
2639       materializeLargeCMVal(I, GV, OpFlags);
2640       I.eraseFromParent();
2641       return true;
2642     } else if (TM.getCodeModel() == CodeModel::Tiny) {
2643       I.setDesc(TII.get(AArch64::ADR));
2644       I.getOperand(1).setTargetFlags(OpFlags);
2645     } else {
2646       I.setDesc(TII.get(AArch64::MOVaddr));
2647       I.getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_PAGE);
2648       MachineInstrBuilder MIB(MF, I);
2649       MIB.addGlobalAddress(GV, I.getOperand(1).getOffset(),
2650                            OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2651     }
2652     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2653   }
2654 
2655   case TargetOpcode::G_ZEXTLOAD:
2656   case TargetOpcode::G_LOAD:
2657   case TargetOpcode::G_STORE: {
2658     bool IsZExtLoad = I.getOpcode() == TargetOpcode::G_ZEXTLOAD;
2659     MachineIRBuilder MIB(I);
2660 
2661     LLT PtrTy = MRI.getType(I.getOperand(1).getReg());
2662 
2663     if (PtrTy != LLT::pointer(0, 64)) {
2664       LLVM_DEBUG(dbgs() << "Load/Store pointer has type: " << PtrTy
2665                         << ", expected: " << LLT::pointer(0, 64) << '\n');
2666       return false;
2667     }
2668 
2669     auto &MemOp = **I.memoperands_begin();
2670     uint64_t MemSizeInBytes = MemOp.getSize();
2671     unsigned MemSizeInBits = MemSizeInBytes * 8;
2672     AtomicOrdering Order = MemOp.getOrdering();
2673 
2674     // Need special instructions for atomics that affect ordering.
2675     if (Order != AtomicOrdering::NotAtomic &&
2676         Order != AtomicOrdering::Unordered &&
2677         Order != AtomicOrdering::Monotonic)
2678       return false;
2679 
2680 #ifndef NDEBUG
2681     const Register PtrReg = I.getOperand(1).getReg();
2682     const RegisterBank &PtrRB = *RBI.getRegBank(PtrReg, MRI, TRI);
2683     // Sanity-check the pointer register.
2684     assert(PtrRB.getID() == AArch64::GPRRegBankID &&
2685            "Load/Store pointer operand isn't a GPR");
2686     assert(MRI.getType(PtrReg).isPointer() &&
2687            "Load/Store pointer operand isn't a pointer");
2688 #endif
2689 
2690     const Register ValReg = I.getOperand(0).getReg();
2691     const RegisterBank &RB = *RBI.getRegBank(ValReg, MRI, TRI);
2692 
2693     // Helper lambda for partially selecting I. Either returns the original
2694     // instruction with an updated opcode, or a new instruction.
2695     auto SelectLoadStoreAddressingMode = [&]() -> MachineInstr * {
2696       bool IsStore = I.getOpcode() == TargetOpcode::G_STORE;
2697       const unsigned NewOpc =
2698           selectLoadStoreUIOp(I.getOpcode(), RB.getID(), MemSizeInBits);
2699       if (NewOpc == I.getOpcode())
2700         return nullptr;
2701       // Check if we can fold anything into the addressing mode.
2702       auto AddrModeFns =
2703           selectAddrModeIndexed(I.getOperand(1), MemSizeInBytes);
2704       if (!AddrModeFns) {
2705         // Can't fold anything. Use the original instruction.
2706         I.setDesc(TII.get(NewOpc));
2707         I.addOperand(MachineOperand::CreateImm(0));
2708         return &I;
2709       }
2710 
2711       // Folded something. Create a new instruction and return it.
2712       auto NewInst = MIB.buildInstr(NewOpc, {}, {}, I.getFlags());
2713       IsStore ? NewInst.addUse(ValReg) : NewInst.addDef(ValReg);
2714       NewInst.cloneMemRefs(I);
2715       for (auto &Fn : *AddrModeFns)
2716         Fn(NewInst);
2717       I.eraseFromParent();
2718       return &*NewInst;
2719     };
2720 
2721     MachineInstr *LoadStore = SelectLoadStoreAddressingMode();
2722     if (!LoadStore)
2723       return false;
2724 
2725     // If we're storing a 0, use WZR/XZR.
2726     if (Opcode == TargetOpcode::G_STORE) {
2727       auto CVal = getConstantVRegValWithLookThrough(
2728           LoadStore->getOperand(0).getReg(), MRI, /*LookThroughInstrs = */ true,
2729           /*HandleFConstants = */ false);
2730       if (CVal && CVal->Value == 0) {
2731         switch (LoadStore->getOpcode()) {
2732         case AArch64::STRWui:
2733         case AArch64::STRHHui:
2734         case AArch64::STRBBui:
2735           LoadStore->getOperand(0).setReg(AArch64::WZR);
2736           break;
2737         case AArch64::STRXui:
2738           LoadStore->getOperand(0).setReg(AArch64::XZR);
2739           break;
2740         }
2741       }
2742     }
2743 
2744     if (IsZExtLoad) {
2745       // The zextload from a smaller type to i32 should be handled by the
2746       // importer.
2747       if (MRI.getType(LoadStore->getOperand(0).getReg()).getSizeInBits() != 64)
2748         return false;
2749       // If we have a ZEXTLOAD then change the load's type to be a narrower reg
2750       // and zero_extend with SUBREG_TO_REG.
2751       Register LdReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
2752       Register DstReg = LoadStore->getOperand(0).getReg();
2753       LoadStore->getOperand(0).setReg(LdReg);
2754 
2755       MIB.setInsertPt(MIB.getMBB(), std::next(LoadStore->getIterator()));
2756       MIB.buildInstr(AArch64::SUBREG_TO_REG, {DstReg}, {})
2757           .addImm(0)
2758           .addUse(LdReg)
2759           .addImm(AArch64::sub_32);
2760       constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
2761       return RBI.constrainGenericRegister(DstReg, AArch64::GPR64allRegClass,
2762                                           MRI);
2763     }
2764     return constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
2765   }
2766 
2767   case TargetOpcode::G_SMULH:
2768   case TargetOpcode::G_UMULH: {
2769     // Reject the various things we don't support yet.
2770     if (unsupportedBinOp(I, RBI, MRI, TRI))
2771       return false;
2772 
2773     const Register DefReg = I.getOperand(0).getReg();
2774     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2775 
2776     if (RB.getID() != AArch64::GPRRegBankID) {
2777       LLVM_DEBUG(dbgs() << "G_[SU]MULH on bank: " << RB << ", expected: GPR\n");
2778       return false;
2779     }
2780 
2781     if (Ty != LLT::scalar(64)) {
2782       LLVM_DEBUG(dbgs() << "G_[SU]MULH has type: " << Ty
2783                         << ", expected: " << LLT::scalar(64) << '\n');
2784       return false;
2785     }
2786 
2787     unsigned NewOpc = I.getOpcode() == TargetOpcode::G_SMULH ? AArch64::SMULHrr
2788                                                              : AArch64::UMULHrr;
2789     I.setDesc(TII.get(NewOpc));
2790 
2791     // Now that we selected an opcode, we need to constrain the register
2792     // operands to use appropriate classes.
2793     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2794   }
2795   case TargetOpcode::G_LSHR:
2796   case TargetOpcode::G_ASHR:
2797     if (MRI.getType(I.getOperand(0).getReg()).isVector())
2798       return selectVectorAshrLshr(I, MRI);
2799     LLVM_FALLTHROUGH;
2800   case TargetOpcode::G_SHL:
2801     if (Opcode == TargetOpcode::G_SHL &&
2802         MRI.getType(I.getOperand(0).getReg()).isVector())
2803       return selectVectorSHL(I, MRI);
2804     LLVM_FALLTHROUGH;
2805   case TargetOpcode::G_FADD:
2806   case TargetOpcode::G_FSUB:
2807   case TargetOpcode::G_FMUL:
2808   case TargetOpcode::G_FDIV:
2809   case TargetOpcode::G_OR: {
2810     // Reject the various things we don't support yet.
2811     if (unsupportedBinOp(I, RBI, MRI, TRI))
2812       return false;
2813 
2814     const unsigned OpSize = Ty.getSizeInBits();
2815 
2816     const Register DefReg = I.getOperand(0).getReg();
2817     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2818 
2819     const unsigned NewOpc = selectBinaryOp(I.getOpcode(), RB.getID(), OpSize);
2820     if (NewOpc == I.getOpcode())
2821       return false;
2822 
2823     I.setDesc(TII.get(NewOpc));
2824     // FIXME: Should the type be always reset in setDesc?
2825 
2826     // Now that we selected an opcode, we need to constrain the register
2827     // operands to use appropriate classes.
2828     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2829   }
2830 
2831   case TargetOpcode::G_PTR_ADD: {
2832     MachineIRBuilder MIRBuilder(I);
2833     emitADD(I.getOperand(0).getReg(), I.getOperand(1), I.getOperand(2),
2834             MIRBuilder);
2835     I.eraseFromParent();
2836     return true;
2837   }
2838   case TargetOpcode::G_SADDO:
2839   case TargetOpcode::G_UADDO:
2840   case TargetOpcode::G_SSUBO:
2841   case TargetOpcode::G_USUBO: {
2842     // Emit the operation and get the correct condition code.
2843     MachineIRBuilder MIRBuilder(I);
2844     auto OpAndCC = emitOverflowOp(Opcode, I.getOperand(0).getReg(),
2845                                   I.getOperand(2), I.getOperand(3), MIRBuilder);
2846 
2847     // Now, put the overflow result in the register given by the first operand
2848     // to the overflow op. CSINC increments the result when the predicate is
2849     // false, so to get the increment when it's true, we need to use the
2850     // inverse. In this case, we want to increment when carry is set.
2851     Register ZReg = AArch64::WZR;
2852     auto CsetMI = MIRBuilder
2853                       .buildInstr(AArch64::CSINCWr, {I.getOperand(1).getReg()},
2854                                   {ZReg, ZReg})
2855                       .addImm(getInvertedCondCode(OpAndCC.second));
2856     constrainSelectedInstRegOperands(*CsetMI, TII, TRI, RBI);
2857     I.eraseFromParent();
2858     return true;
2859   }
2860 
2861   case TargetOpcode::G_PTRMASK: {
2862     Register MaskReg = I.getOperand(2).getReg();
2863     Optional<int64_t> MaskVal = getConstantVRegSExtVal(MaskReg, MRI);
2864     // TODO: Implement arbitrary cases
2865     if (!MaskVal || !isShiftedMask_64(*MaskVal))
2866       return false;
2867 
2868     uint64_t Mask = *MaskVal;
2869     I.setDesc(TII.get(AArch64::ANDXri));
2870     I.getOperand(2).ChangeToImmediate(
2871         AArch64_AM::encodeLogicalImmediate(Mask, 64));
2872 
2873     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2874   }
2875   case TargetOpcode::G_PTRTOINT:
2876   case TargetOpcode::G_TRUNC: {
2877     const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2878     const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
2879 
2880     const Register DstReg = I.getOperand(0).getReg();
2881     const Register SrcReg = I.getOperand(1).getReg();
2882 
2883     const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
2884     const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
2885 
2886     if (DstRB.getID() != SrcRB.getID()) {
2887       LLVM_DEBUG(
2888           dbgs() << "G_TRUNC/G_PTRTOINT input/output on different banks\n");
2889       return false;
2890     }
2891 
2892     if (DstRB.getID() == AArch64::GPRRegBankID) {
2893       const TargetRegisterClass *DstRC =
2894           getRegClassForTypeOnBank(DstTy, DstRB, RBI);
2895       if (!DstRC)
2896         return false;
2897 
2898       const TargetRegisterClass *SrcRC =
2899           getRegClassForTypeOnBank(SrcTy, SrcRB, RBI);
2900       if (!SrcRC)
2901         return false;
2902 
2903       if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, MRI) ||
2904           !RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
2905         LLVM_DEBUG(dbgs() << "Failed to constrain G_TRUNC/G_PTRTOINT\n");
2906         return false;
2907       }
2908 
2909       if (DstRC == SrcRC) {
2910         // Nothing to be done
2911       } else if (Opcode == TargetOpcode::G_TRUNC && DstTy == LLT::scalar(32) &&
2912                  SrcTy == LLT::scalar(64)) {
2913         llvm_unreachable("TableGen can import this case");
2914         return false;
2915       } else if (DstRC == &AArch64::GPR32RegClass &&
2916                  SrcRC == &AArch64::GPR64RegClass) {
2917         I.getOperand(1).setSubReg(AArch64::sub_32);
2918       } else {
2919         LLVM_DEBUG(
2920             dbgs() << "Unhandled mismatched classes in G_TRUNC/G_PTRTOINT\n");
2921         return false;
2922       }
2923 
2924       I.setDesc(TII.get(TargetOpcode::COPY));
2925       return true;
2926     } else if (DstRB.getID() == AArch64::FPRRegBankID) {
2927       if (DstTy == LLT::vector(4, 16) && SrcTy == LLT::vector(4, 32)) {
2928         I.setDesc(TII.get(AArch64::XTNv4i16));
2929         constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2930         return true;
2931       }
2932 
2933       if (!SrcTy.isVector() && SrcTy.getSizeInBits() == 128) {
2934         MachineIRBuilder MIB(I);
2935         MachineInstr *Extract = emitExtractVectorElt(
2936             DstReg, DstRB, LLT::scalar(DstTy.getSizeInBits()), SrcReg, 0, MIB);
2937         if (!Extract)
2938           return false;
2939         I.eraseFromParent();
2940         return true;
2941       }
2942 
2943       // We might have a vector G_PTRTOINT, in which case just emit a COPY.
2944       if (Opcode == TargetOpcode::G_PTRTOINT) {
2945         assert(DstTy.isVector() && "Expected an FPR ptrtoint to be a vector");
2946         I.setDesc(TII.get(TargetOpcode::COPY));
2947         return true;
2948       }
2949     }
2950 
2951     return false;
2952   }
2953 
2954   case TargetOpcode::G_ANYEXT: {
2955     const Register DstReg = I.getOperand(0).getReg();
2956     const Register SrcReg = I.getOperand(1).getReg();
2957 
2958     const RegisterBank &RBDst = *RBI.getRegBank(DstReg, MRI, TRI);
2959     if (RBDst.getID() != AArch64::GPRRegBankID) {
2960       LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBDst
2961                         << ", expected: GPR\n");
2962       return false;
2963     }
2964 
2965     const RegisterBank &RBSrc = *RBI.getRegBank(SrcReg, MRI, TRI);
2966     if (RBSrc.getID() != AArch64::GPRRegBankID) {
2967       LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBSrc
2968                         << ", expected: GPR\n");
2969       return false;
2970     }
2971 
2972     const unsigned DstSize = MRI.getType(DstReg).getSizeInBits();
2973 
2974     if (DstSize == 0) {
2975       LLVM_DEBUG(dbgs() << "G_ANYEXT operand has no size, not a gvreg?\n");
2976       return false;
2977     }
2978 
2979     if (DstSize != 64 && DstSize > 32) {
2980       LLVM_DEBUG(dbgs() << "G_ANYEXT to size: " << DstSize
2981                         << ", expected: 32 or 64\n");
2982       return false;
2983     }
2984     // At this point G_ANYEXT is just like a plain COPY, but we need
2985     // to explicitly form the 64-bit value if any.
2986     if (DstSize > 32) {
2987       Register ExtSrc = MRI.createVirtualRegister(&AArch64::GPR64allRegClass);
2988       BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::SUBREG_TO_REG))
2989           .addDef(ExtSrc)
2990           .addImm(0)
2991           .addUse(SrcReg)
2992           .addImm(AArch64::sub_32);
2993       I.getOperand(1).setReg(ExtSrc);
2994     }
2995     return selectCopy(I, TII, MRI, TRI, RBI);
2996   }
2997 
2998   case TargetOpcode::G_ZEXT:
2999   case TargetOpcode::G_SEXT_INREG:
3000   case TargetOpcode::G_SEXT: {
3001     unsigned Opcode = I.getOpcode();
3002     const bool IsSigned = Opcode != TargetOpcode::G_ZEXT;
3003     const Register DefReg = I.getOperand(0).getReg();
3004     Register SrcReg = I.getOperand(1).getReg();
3005     const LLT DstTy = MRI.getType(DefReg);
3006     const LLT SrcTy = MRI.getType(SrcReg);
3007     unsigned DstSize = DstTy.getSizeInBits();
3008     unsigned SrcSize = SrcTy.getSizeInBits();
3009 
3010     // SEXT_INREG has the same src reg size as dst, the size of the value to be
3011     // extended is encoded in the imm.
3012     if (Opcode == TargetOpcode::G_SEXT_INREG)
3013       SrcSize = I.getOperand(2).getImm();
3014 
3015     if (DstTy.isVector())
3016       return false; // Should be handled by imported patterns.
3017 
3018     assert((*RBI.getRegBank(DefReg, MRI, TRI)).getID() ==
3019                AArch64::GPRRegBankID &&
3020            "Unexpected ext regbank");
3021 
3022     MachineIRBuilder MIB(I);
3023     MachineInstr *ExtI;
3024 
3025     // First check if we're extending the result of a load which has a dest type
3026     // smaller than 32 bits, then this zext is redundant. GPR32 is the smallest
3027     // GPR register on AArch64 and all loads which are smaller automatically
3028     // zero-extend the upper bits. E.g.
3029     // %v(s8) = G_LOAD %p, :: (load 1)
3030     // %v2(s32) = G_ZEXT %v(s8)
3031     if (!IsSigned) {
3032       auto *LoadMI = getOpcodeDef(TargetOpcode::G_LOAD, SrcReg, MRI);
3033       bool IsGPR =
3034           RBI.getRegBank(SrcReg, MRI, TRI)->getID() == AArch64::GPRRegBankID;
3035       if (LoadMI && IsGPR) {
3036         const MachineMemOperand *MemOp = *LoadMI->memoperands_begin();
3037         unsigned BytesLoaded = MemOp->getSize();
3038         if (BytesLoaded < 4 && SrcTy.getSizeInBytes() == BytesLoaded)
3039           return selectCopy(I, TII, MRI, TRI, RBI);
3040       }
3041 
3042       // If we are zero extending from 32 bits to 64 bits, it's possible that
3043       // the instruction implicitly does the zero extend for us. In that case,
3044       // we can just emit a SUBREG_TO_REG.
3045       if (IsGPR && SrcSize == 32 && DstSize == 64) {
3046         // Unlike with the G_LOAD case, we don't want to look through copies
3047         // here.
3048         MachineInstr *Def = MRI.getVRegDef(SrcReg);
3049         if (Def && isDef32(*Def)) {
3050           MIB.buildInstr(AArch64::SUBREG_TO_REG, {DefReg}, {})
3051               .addImm(0)
3052               .addUse(SrcReg)
3053               .addImm(AArch64::sub_32);
3054 
3055           if (!RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass,
3056                                             MRI)) {
3057             LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT destination\n");
3058             return false;
3059           }
3060 
3061           if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
3062                                             MRI)) {
3063             LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT source\n");
3064             return false;
3065           }
3066 
3067           I.eraseFromParent();
3068           return true;
3069         }
3070       }
3071     }
3072 
3073     if (DstSize == 64) {
3074       if (Opcode != TargetOpcode::G_SEXT_INREG) {
3075         // FIXME: Can we avoid manually doing this?
3076         if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
3077                                           MRI)) {
3078           LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(Opcode)
3079                             << " operand\n");
3080           return false;
3081         }
3082         SrcReg = MIB.buildInstr(AArch64::SUBREG_TO_REG,
3083                                 {&AArch64::GPR64RegClass}, {})
3084                      .addImm(0)
3085                      .addUse(SrcReg)
3086                      .addImm(AArch64::sub_32)
3087                      .getReg(0);
3088       }
3089 
3090       ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMXri : AArch64::UBFMXri,
3091                              {DefReg}, {SrcReg})
3092                   .addImm(0)
3093                   .addImm(SrcSize - 1);
3094     } else if (DstSize <= 32) {
3095       ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMWri : AArch64::UBFMWri,
3096                              {DefReg}, {SrcReg})
3097                   .addImm(0)
3098                   .addImm(SrcSize - 1);
3099     } else {
3100       return false;
3101     }
3102 
3103     constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
3104     I.eraseFromParent();
3105     return true;
3106   }
3107 
3108   case TargetOpcode::G_SITOFP:
3109   case TargetOpcode::G_UITOFP:
3110   case TargetOpcode::G_FPTOSI:
3111   case TargetOpcode::G_FPTOUI: {
3112     const LLT DstTy = MRI.getType(I.getOperand(0).getReg()),
3113               SrcTy = MRI.getType(I.getOperand(1).getReg());
3114     const unsigned NewOpc = selectFPConvOpc(Opcode, DstTy, SrcTy);
3115     if (NewOpc == Opcode)
3116       return false;
3117 
3118     I.setDesc(TII.get(NewOpc));
3119     constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3120 
3121     return true;
3122   }
3123 
3124   case TargetOpcode::G_FREEZE:
3125     return selectCopy(I, TII, MRI, TRI, RBI);
3126 
3127   case TargetOpcode::G_INTTOPTR:
3128     // The importer is currently unable to import pointer types since they
3129     // didn't exist in SelectionDAG.
3130     return selectCopy(I, TII, MRI, TRI, RBI);
3131 
3132   case TargetOpcode::G_BITCAST:
3133     // Imported SelectionDAG rules can handle every bitcast except those that
3134     // bitcast from a type to the same type. Ideally, these shouldn't occur
3135     // but we might not run an optimizer that deletes them. The other exception
3136     // is bitcasts involving pointer types, as SelectionDAG has no knowledge
3137     // of them.
3138     return selectCopy(I, TII, MRI, TRI, RBI);
3139 
3140   case TargetOpcode::G_SELECT: {
3141     if (MRI.getType(I.getOperand(1).getReg()) != LLT::scalar(1)) {
3142       LLVM_DEBUG(dbgs() << "G_SELECT cond has type: " << Ty
3143                         << ", expected: " << LLT::scalar(1) << '\n');
3144       return false;
3145     }
3146 
3147     const Register CondReg = I.getOperand(1).getReg();
3148     const Register TReg = I.getOperand(2).getReg();
3149     const Register FReg = I.getOperand(3).getReg();
3150 
3151     if (tryOptSelect(I))
3152       return true;
3153 
3154     // Make sure to use an unused vreg instead of wzr, so that the peephole
3155     // optimizations will be able to optimize these.
3156     MachineIRBuilder MIB(I);
3157     Register DeadVReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
3158     auto TstMI = MIB.buildInstr(AArch64::ANDSWri, {DeadVReg}, {CondReg})
3159                      .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
3160     constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
3161     if (!emitSelect(I.getOperand(0).getReg(), TReg, FReg, AArch64CC::NE, MIB))
3162       return false;
3163     I.eraseFromParent();
3164     return true;
3165   }
3166   case TargetOpcode::G_ICMP: {
3167     if (Ty.isVector())
3168       return selectVectorICmp(I, MRI);
3169 
3170     if (Ty != LLT::scalar(32)) {
3171       LLVM_DEBUG(dbgs() << "G_ICMP result has type: " << Ty
3172                         << ", expected: " << LLT::scalar(32) << '\n');
3173       return false;
3174     }
3175 
3176     MachineIRBuilder MIRBuilder(I);
3177     auto Pred = static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
3178     emitIntegerCompare(I.getOperand(2), I.getOperand(3), I.getOperand(1),
3179                        MIRBuilder);
3180     emitCSetForICMP(I.getOperand(0).getReg(), Pred, MIRBuilder);
3181     I.eraseFromParent();
3182     return true;
3183   }
3184 
3185   case TargetOpcode::G_FCMP: {
3186     MachineIRBuilder MIRBuilder(I);
3187     CmpInst::Predicate Pred =
3188         static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
3189     if (!emitFPCompare(I.getOperand(2).getReg(), I.getOperand(3).getReg(),
3190                        MIRBuilder, Pred) ||
3191         !emitCSetForFCmp(I.getOperand(0).getReg(), Pred, MIRBuilder))
3192       return false;
3193     I.eraseFromParent();
3194     return true;
3195   }
3196   case TargetOpcode::G_VASTART:
3197     return STI.isTargetDarwin() ? selectVaStartDarwin(I, MF, MRI)
3198                                 : selectVaStartAAPCS(I, MF, MRI);
3199   case TargetOpcode::G_INTRINSIC:
3200     return selectIntrinsic(I, MRI);
3201   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
3202     return selectIntrinsicWithSideEffects(I, MRI);
3203   case TargetOpcode::G_IMPLICIT_DEF: {
3204     I.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
3205     const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
3206     const Register DstReg = I.getOperand(0).getReg();
3207     const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
3208     const TargetRegisterClass *DstRC =
3209         getRegClassForTypeOnBank(DstTy, DstRB, RBI);
3210     RBI.constrainGenericRegister(DstReg, *DstRC, MRI);
3211     return true;
3212   }
3213   case TargetOpcode::G_BLOCK_ADDR: {
3214     if (TM.getCodeModel() == CodeModel::Large) {
3215       materializeLargeCMVal(I, I.getOperand(1).getBlockAddress(), 0);
3216       I.eraseFromParent();
3217       return true;
3218     } else {
3219       I.setDesc(TII.get(AArch64::MOVaddrBA));
3220       auto MovMI = BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::MOVaddrBA),
3221                            I.getOperand(0).getReg())
3222                        .addBlockAddress(I.getOperand(1).getBlockAddress(),
3223                                         /* Offset */ 0, AArch64II::MO_PAGE)
3224                        .addBlockAddress(
3225                            I.getOperand(1).getBlockAddress(), /* Offset */ 0,
3226                            AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
3227       I.eraseFromParent();
3228       return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
3229     }
3230   }
3231   case AArch64::G_DUP: {
3232     // When the scalar of G_DUP is an s8/s16 gpr, they can't be selected by
3233     // imported patterns. Do it manually here. Avoiding generating s16 gpr is
3234     // difficult because at RBS we may end up pessimizing the fpr case if we
3235     // decided to add an anyextend to fix this. Manual selection is the most
3236     // robust solution for now.
3237     if (RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI)->getID() !=
3238         AArch64::GPRRegBankID)
3239       return false; // We expect the fpr regbank case to be imported.
3240     LLT VecTy = MRI.getType(I.getOperand(0).getReg());
3241     if (VecTy == LLT::vector(8, 8))
3242       I.setDesc(TII.get(AArch64::DUPv8i8gpr));
3243     else if (VecTy == LLT::vector(16, 8))
3244       I.setDesc(TII.get(AArch64::DUPv16i8gpr));
3245     else if (VecTy == LLT::vector(4, 16))
3246       I.setDesc(TII.get(AArch64::DUPv4i16gpr));
3247     else if (VecTy == LLT::vector(8, 16))
3248       I.setDesc(TII.get(AArch64::DUPv8i16gpr));
3249     else
3250       return false;
3251     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3252   }
3253   case TargetOpcode::G_INTRINSIC_TRUNC:
3254     return selectIntrinsicTrunc(I, MRI);
3255   case TargetOpcode::G_INTRINSIC_ROUND:
3256     return selectIntrinsicRound(I, MRI);
3257   case TargetOpcode::G_BUILD_VECTOR:
3258     return selectBuildVector(I, MRI);
3259   case TargetOpcode::G_MERGE_VALUES:
3260     return selectMergeValues(I, MRI);
3261   case TargetOpcode::G_UNMERGE_VALUES:
3262     return selectUnmergeValues(I, MRI);
3263   case TargetOpcode::G_SHUFFLE_VECTOR:
3264     return selectShuffleVector(I, MRI);
3265   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
3266     return selectExtractElt(I, MRI);
3267   case TargetOpcode::G_INSERT_VECTOR_ELT:
3268     return selectInsertElt(I, MRI);
3269   case TargetOpcode::G_CONCAT_VECTORS:
3270     return selectConcatVectors(I, MRI);
3271   case TargetOpcode::G_JUMP_TABLE:
3272     return selectJumpTable(I, MRI);
3273   case TargetOpcode::G_VECREDUCE_FADD:
3274   case TargetOpcode::G_VECREDUCE_ADD:
3275     return selectReduction(I, MRI);
3276   }
3277 
3278   return false;
3279 }
3280 
3281 bool AArch64InstructionSelector::selectReduction(
3282     MachineInstr &I, MachineRegisterInfo &MRI) const {
3283   Register VecReg = I.getOperand(1).getReg();
3284   LLT VecTy = MRI.getType(VecReg);
3285   if (I.getOpcode() == TargetOpcode::G_VECREDUCE_ADD) {
3286     // For <2 x i32> ADDPv2i32 generates an FPR64 value, so we need to emit
3287     // a subregister copy afterwards.
3288     if (VecTy == LLT::vector(2, 32)) {
3289       MachineIRBuilder MIB(I);
3290       Register DstReg = I.getOperand(0).getReg();
3291       auto AddP = MIB.buildInstr(AArch64::ADDPv2i32, {&AArch64::FPR64RegClass},
3292                                  {VecReg, VecReg});
3293       auto Copy = MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {})
3294                       .addReg(AddP.getReg(0), 0, AArch64::ssub)
3295                       .getReg(0);
3296       RBI.constrainGenericRegister(Copy, AArch64::FPR32RegClass, MRI);
3297       I.eraseFromParent();
3298       return constrainSelectedInstRegOperands(*AddP, TII, TRI, RBI);
3299     }
3300 
3301     unsigned Opc = 0;
3302     if (VecTy == LLT::vector(16, 8))
3303       Opc = AArch64::ADDVv16i8v;
3304     else if (VecTy == LLT::vector(8, 16))
3305       Opc = AArch64::ADDVv8i16v;
3306     else if (VecTy == LLT::vector(4, 32))
3307       Opc = AArch64::ADDVv4i32v;
3308     else if (VecTy == LLT::vector(2, 64))
3309       Opc = AArch64::ADDPv2i64p;
3310     else {
3311       LLVM_DEBUG(dbgs() << "Unhandled type for add reduction");
3312       return false;
3313     }
3314     I.setDesc(TII.get(Opc));
3315     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3316   }
3317 
3318   if (I.getOpcode() == TargetOpcode::G_VECREDUCE_FADD) {
3319     unsigned Opc = 0;
3320     if (VecTy == LLT::vector(2, 32))
3321       Opc = AArch64::FADDPv2i32p;
3322     else if (VecTy == LLT::vector(2, 64))
3323       Opc = AArch64::FADDPv2i64p;
3324     else {
3325       LLVM_DEBUG(dbgs() << "Unhandled type for fadd reduction");
3326       return false;
3327     }
3328     I.setDesc(TII.get(Opc));
3329     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3330   }
3331   return false;
3332 }
3333 
3334 bool AArch64InstructionSelector::selectBrJT(MachineInstr &I,
3335                                             MachineRegisterInfo &MRI) const {
3336   assert(I.getOpcode() == TargetOpcode::G_BRJT && "Expected G_BRJT");
3337   Register JTAddr = I.getOperand(0).getReg();
3338   unsigned JTI = I.getOperand(1).getIndex();
3339   Register Index = I.getOperand(2).getReg();
3340   MachineIRBuilder MIB(I);
3341 
3342   Register TargetReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3343   Register ScratchReg = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
3344 
3345   MF->getInfo<AArch64FunctionInfo>()->setJumpTableEntryInfo(JTI, 4, nullptr);
3346   auto JumpTableInst = MIB.buildInstr(AArch64::JumpTableDest32,
3347                                       {TargetReg, ScratchReg}, {JTAddr, Index})
3348                            .addJumpTableIndex(JTI);
3349   // Build the indirect branch.
3350   MIB.buildInstr(AArch64::BR, {}, {TargetReg});
3351   I.eraseFromParent();
3352   return constrainSelectedInstRegOperands(*JumpTableInst, TII, TRI, RBI);
3353 }
3354 
3355 bool AArch64InstructionSelector::selectJumpTable(
3356     MachineInstr &I, MachineRegisterInfo &MRI) const {
3357   assert(I.getOpcode() == TargetOpcode::G_JUMP_TABLE && "Expected jump table");
3358   assert(I.getOperand(1).isJTI() && "Jump table op should have a JTI!");
3359 
3360   Register DstReg = I.getOperand(0).getReg();
3361   unsigned JTI = I.getOperand(1).getIndex();
3362   // We generate a MOVaddrJT which will get expanded to an ADRP + ADD later.
3363   MachineIRBuilder MIB(I);
3364   auto MovMI =
3365     MIB.buildInstr(AArch64::MOVaddrJT, {DstReg}, {})
3366           .addJumpTableIndex(JTI, AArch64II::MO_PAGE)
3367           .addJumpTableIndex(JTI, AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
3368   I.eraseFromParent();
3369   return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
3370 }
3371 
3372 bool AArch64InstructionSelector::selectTLSGlobalValue(
3373     MachineInstr &I, MachineRegisterInfo &MRI) const {
3374   if (!STI.isTargetMachO())
3375     return false;
3376   MachineFunction &MF = *I.getParent()->getParent();
3377   MF.getFrameInfo().setAdjustsStack(true);
3378 
3379   const auto &GlobalOp = I.getOperand(1);
3380   assert(GlobalOp.getOffset() == 0 &&
3381          "Shouldn't have an offset on TLS globals!");
3382   const GlobalValue &GV = *GlobalOp.getGlobal();
3383   MachineIRBuilder MIB(I);
3384 
3385   auto LoadGOT =
3386       MIB.buildInstr(AArch64::LOADgot, {&AArch64::GPR64commonRegClass}, {})
3387           .addGlobalAddress(&GV, 0, AArch64II::MO_TLS);
3388 
3389   auto Load = MIB.buildInstr(AArch64::LDRXui, {&AArch64::GPR64commonRegClass},
3390                              {LoadGOT.getReg(0)})
3391                   .addImm(0);
3392 
3393   MIB.buildCopy(Register(AArch64::X0), LoadGOT.getReg(0));
3394   // TLS calls preserve all registers except those that absolutely must be
3395   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3396   // silly).
3397   MIB.buildInstr(getBLRCallOpcode(MF), {}, {Load})
3398       .addUse(AArch64::X0, RegState::Implicit)
3399       .addDef(AArch64::X0, RegState::Implicit)
3400       .addRegMask(TRI.getTLSCallPreservedMask());
3401 
3402   MIB.buildCopy(I.getOperand(0).getReg(), Register(AArch64::X0));
3403   RBI.constrainGenericRegister(I.getOperand(0).getReg(), AArch64::GPR64RegClass,
3404                                MRI);
3405   I.eraseFromParent();
3406   return true;
3407 }
3408 
3409 bool AArch64InstructionSelector::selectIntrinsicTrunc(
3410     MachineInstr &I, MachineRegisterInfo &MRI) const {
3411   const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
3412 
3413   // Select the correct opcode.
3414   unsigned Opc = 0;
3415   if (!SrcTy.isVector()) {
3416     switch (SrcTy.getSizeInBits()) {
3417     default:
3418     case 16:
3419       Opc = AArch64::FRINTZHr;
3420       break;
3421     case 32:
3422       Opc = AArch64::FRINTZSr;
3423       break;
3424     case 64:
3425       Opc = AArch64::FRINTZDr;
3426       break;
3427     }
3428   } else {
3429     unsigned NumElts = SrcTy.getNumElements();
3430     switch (SrcTy.getElementType().getSizeInBits()) {
3431     default:
3432       break;
3433     case 16:
3434       if (NumElts == 4)
3435         Opc = AArch64::FRINTZv4f16;
3436       else if (NumElts == 8)
3437         Opc = AArch64::FRINTZv8f16;
3438       break;
3439     case 32:
3440       if (NumElts == 2)
3441         Opc = AArch64::FRINTZv2f32;
3442       else if (NumElts == 4)
3443         Opc = AArch64::FRINTZv4f32;
3444       break;
3445     case 64:
3446       if (NumElts == 2)
3447         Opc = AArch64::FRINTZv2f64;
3448       break;
3449     }
3450   }
3451 
3452   if (!Opc) {
3453     // Didn't get an opcode above, bail.
3454     LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_TRUNC!\n");
3455     return false;
3456   }
3457 
3458   // Legalization would have set us up perfectly for this; we just need to
3459   // set the opcode and move on.
3460   I.setDesc(TII.get(Opc));
3461   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3462 }
3463 
3464 bool AArch64InstructionSelector::selectIntrinsicRound(
3465     MachineInstr &I, MachineRegisterInfo &MRI) const {
3466   const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
3467 
3468   // Select the correct opcode.
3469   unsigned Opc = 0;
3470   if (!SrcTy.isVector()) {
3471     switch (SrcTy.getSizeInBits()) {
3472     default:
3473     case 16:
3474       Opc = AArch64::FRINTAHr;
3475       break;
3476     case 32:
3477       Opc = AArch64::FRINTASr;
3478       break;
3479     case 64:
3480       Opc = AArch64::FRINTADr;
3481       break;
3482     }
3483   } else {
3484     unsigned NumElts = SrcTy.getNumElements();
3485     switch (SrcTy.getElementType().getSizeInBits()) {
3486     default:
3487       break;
3488     case 16:
3489       if (NumElts == 4)
3490         Opc = AArch64::FRINTAv4f16;
3491       else if (NumElts == 8)
3492         Opc = AArch64::FRINTAv8f16;
3493       break;
3494     case 32:
3495       if (NumElts == 2)
3496         Opc = AArch64::FRINTAv2f32;
3497       else if (NumElts == 4)
3498         Opc = AArch64::FRINTAv4f32;
3499       break;
3500     case 64:
3501       if (NumElts == 2)
3502         Opc = AArch64::FRINTAv2f64;
3503       break;
3504     }
3505   }
3506 
3507   if (!Opc) {
3508     // Didn't get an opcode above, bail.
3509     LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_ROUND!\n");
3510     return false;
3511   }
3512 
3513   // Legalization would have set us up perfectly for this; we just need to
3514   // set the opcode and move on.
3515   I.setDesc(TII.get(Opc));
3516   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3517 }
3518 
3519 bool AArch64InstructionSelector::selectVectorICmp(
3520     MachineInstr &I, MachineRegisterInfo &MRI) const {
3521   Register DstReg = I.getOperand(0).getReg();
3522   LLT DstTy = MRI.getType(DstReg);
3523   Register SrcReg = I.getOperand(2).getReg();
3524   Register Src2Reg = I.getOperand(3).getReg();
3525   LLT SrcTy = MRI.getType(SrcReg);
3526 
3527   unsigned SrcEltSize = SrcTy.getElementType().getSizeInBits();
3528   unsigned NumElts = DstTy.getNumElements();
3529 
3530   // First index is element size, 0 == 8b, 1 == 16b, 2 == 32b, 3 == 64b
3531   // Second index is num elts, 0 == v2, 1 == v4, 2 == v8, 3 == v16
3532   // Third index is cc opcode:
3533   // 0 == eq
3534   // 1 == ugt
3535   // 2 == uge
3536   // 3 == ult
3537   // 4 == ule
3538   // 5 == sgt
3539   // 6 == sge
3540   // 7 == slt
3541   // 8 == sle
3542   // ne is done by negating 'eq' result.
3543 
3544   // This table below assumes that for some comparisons the operands will be
3545   // commuted.
3546   // ult op == commute + ugt op
3547   // ule op == commute + uge op
3548   // slt op == commute + sgt op
3549   // sle op == commute + sge op
3550   unsigned PredIdx = 0;
3551   bool SwapOperands = false;
3552   CmpInst::Predicate Pred = (CmpInst::Predicate)I.getOperand(1).getPredicate();
3553   switch (Pred) {
3554   case CmpInst::ICMP_NE:
3555   case CmpInst::ICMP_EQ:
3556     PredIdx = 0;
3557     break;
3558   case CmpInst::ICMP_UGT:
3559     PredIdx = 1;
3560     break;
3561   case CmpInst::ICMP_UGE:
3562     PredIdx = 2;
3563     break;
3564   case CmpInst::ICMP_ULT:
3565     PredIdx = 3;
3566     SwapOperands = true;
3567     break;
3568   case CmpInst::ICMP_ULE:
3569     PredIdx = 4;
3570     SwapOperands = true;
3571     break;
3572   case CmpInst::ICMP_SGT:
3573     PredIdx = 5;
3574     break;
3575   case CmpInst::ICMP_SGE:
3576     PredIdx = 6;
3577     break;
3578   case CmpInst::ICMP_SLT:
3579     PredIdx = 7;
3580     SwapOperands = true;
3581     break;
3582   case CmpInst::ICMP_SLE:
3583     PredIdx = 8;
3584     SwapOperands = true;
3585     break;
3586   default:
3587     llvm_unreachable("Unhandled icmp predicate");
3588     return false;
3589   }
3590 
3591   // This table obviously should be tablegen'd when we have our GISel native
3592   // tablegen selector.
3593 
3594   static const unsigned OpcTable[4][4][9] = {
3595       {
3596           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3597            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3598            0 /* invalid */},
3599           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3600            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3601            0 /* invalid */},
3602           {AArch64::CMEQv8i8, AArch64::CMHIv8i8, AArch64::CMHSv8i8,
3603            AArch64::CMHIv8i8, AArch64::CMHSv8i8, AArch64::CMGTv8i8,
3604            AArch64::CMGEv8i8, AArch64::CMGTv8i8, AArch64::CMGEv8i8},
3605           {AArch64::CMEQv16i8, AArch64::CMHIv16i8, AArch64::CMHSv16i8,
3606            AArch64::CMHIv16i8, AArch64::CMHSv16i8, AArch64::CMGTv16i8,
3607            AArch64::CMGEv16i8, AArch64::CMGTv16i8, AArch64::CMGEv16i8}
3608       },
3609       {
3610           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3611            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3612            0 /* invalid */},
3613           {AArch64::CMEQv4i16, AArch64::CMHIv4i16, AArch64::CMHSv4i16,
3614            AArch64::CMHIv4i16, AArch64::CMHSv4i16, AArch64::CMGTv4i16,
3615            AArch64::CMGEv4i16, AArch64::CMGTv4i16, AArch64::CMGEv4i16},
3616           {AArch64::CMEQv8i16, AArch64::CMHIv8i16, AArch64::CMHSv8i16,
3617            AArch64::CMHIv8i16, AArch64::CMHSv8i16, AArch64::CMGTv8i16,
3618            AArch64::CMGEv8i16, AArch64::CMGTv8i16, AArch64::CMGEv8i16},
3619           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3620            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3621            0 /* invalid */}
3622       },
3623       {
3624           {AArch64::CMEQv2i32, AArch64::CMHIv2i32, AArch64::CMHSv2i32,
3625            AArch64::CMHIv2i32, AArch64::CMHSv2i32, AArch64::CMGTv2i32,
3626            AArch64::CMGEv2i32, AArch64::CMGTv2i32, AArch64::CMGEv2i32},
3627           {AArch64::CMEQv4i32, AArch64::CMHIv4i32, AArch64::CMHSv4i32,
3628            AArch64::CMHIv4i32, AArch64::CMHSv4i32, AArch64::CMGTv4i32,
3629            AArch64::CMGEv4i32, AArch64::CMGTv4i32, AArch64::CMGEv4i32},
3630           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3631            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3632            0 /* invalid */},
3633           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3634            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3635            0 /* invalid */}
3636       },
3637       {
3638           {AArch64::CMEQv2i64, AArch64::CMHIv2i64, AArch64::CMHSv2i64,
3639            AArch64::CMHIv2i64, AArch64::CMHSv2i64, AArch64::CMGTv2i64,
3640            AArch64::CMGEv2i64, AArch64::CMGTv2i64, AArch64::CMGEv2i64},
3641           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3642            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3643            0 /* invalid */},
3644           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3645            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3646            0 /* invalid */},
3647           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3648            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3649            0 /* invalid */}
3650       },
3651   };
3652   unsigned EltIdx = Log2_32(SrcEltSize / 8);
3653   unsigned NumEltsIdx = Log2_32(NumElts / 2);
3654   unsigned Opc = OpcTable[EltIdx][NumEltsIdx][PredIdx];
3655   if (!Opc) {
3656     LLVM_DEBUG(dbgs() << "Could not map G_ICMP to cmp opcode");
3657     return false;
3658   }
3659 
3660   const RegisterBank &VecRB = *RBI.getRegBank(SrcReg, MRI, TRI);
3661   const TargetRegisterClass *SrcRC =
3662       getRegClassForTypeOnBank(SrcTy, VecRB, RBI, true);
3663   if (!SrcRC) {
3664     LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
3665     return false;
3666   }
3667 
3668   unsigned NotOpc = Pred == ICmpInst::ICMP_NE ? AArch64::NOTv8i8 : 0;
3669   if (SrcTy.getSizeInBits() == 128)
3670     NotOpc = NotOpc ? AArch64::NOTv16i8 : 0;
3671 
3672   if (SwapOperands)
3673     std::swap(SrcReg, Src2Reg);
3674 
3675   MachineIRBuilder MIB(I);
3676   auto Cmp = MIB.buildInstr(Opc, {SrcRC}, {SrcReg, Src2Reg});
3677   constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
3678 
3679   // Invert if we had a 'ne' cc.
3680   if (NotOpc) {
3681     Cmp = MIB.buildInstr(NotOpc, {DstReg}, {Cmp});
3682     constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
3683   } else {
3684     MIB.buildCopy(DstReg, Cmp.getReg(0));
3685   }
3686   RBI.constrainGenericRegister(DstReg, *SrcRC, MRI);
3687   I.eraseFromParent();
3688   return true;
3689 }
3690 
3691 MachineInstr *AArch64InstructionSelector::emitScalarToVector(
3692     unsigned EltSize, const TargetRegisterClass *DstRC, Register Scalar,
3693     MachineIRBuilder &MIRBuilder) const {
3694   auto Undef = MIRBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstRC}, {});
3695 
3696   auto BuildFn = [&](unsigned SubregIndex) {
3697     auto Ins =
3698         MIRBuilder
3699             .buildInstr(TargetOpcode::INSERT_SUBREG, {DstRC}, {Undef, Scalar})
3700             .addImm(SubregIndex);
3701     constrainSelectedInstRegOperands(*Undef, TII, TRI, RBI);
3702     constrainSelectedInstRegOperands(*Ins, TII, TRI, RBI);
3703     return &*Ins;
3704   };
3705 
3706   switch (EltSize) {
3707   case 16:
3708     return BuildFn(AArch64::hsub);
3709   case 32:
3710     return BuildFn(AArch64::ssub);
3711   case 64:
3712     return BuildFn(AArch64::dsub);
3713   default:
3714     return nullptr;
3715   }
3716 }
3717 
3718 bool AArch64InstructionSelector::selectMergeValues(
3719     MachineInstr &I, MachineRegisterInfo &MRI) const {
3720   assert(I.getOpcode() == TargetOpcode::G_MERGE_VALUES && "unexpected opcode");
3721   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
3722   const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
3723   assert(!DstTy.isVector() && !SrcTy.isVector() && "invalid merge operation");
3724   const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
3725 
3726   if (I.getNumOperands() != 3)
3727     return false;
3728 
3729   // Merging 2 s64s into an s128.
3730   if (DstTy == LLT::scalar(128)) {
3731     if (SrcTy.getSizeInBits() != 64)
3732       return false;
3733     MachineIRBuilder MIB(I);
3734     Register DstReg = I.getOperand(0).getReg();
3735     Register Src1Reg = I.getOperand(1).getReg();
3736     Register Src2Reg = I.getOperand(2).getReg();
3737     auto Tmp = MIB.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstTy}, {});
3738     MachineInstr *InsMI =
3739         emitLaneInsert(None, Tmp.getReg(0), Src1Reg, /* LaneIdx */ 0, RB, MIB);
3740     if (!InsMI)
3741       return false;
3742     MachineInstr *Ins2MI = emitLaneInsert(DstReg, InsMI->getOperand(0).getReg(),
3743                                           Src2Reg, /* LaneIdx */ 1, RB, MIB);
3744     if (!Ins2MI)
3745       return false;
3746     constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
3747     constrainSelectedInstRegOperands(*Ins2MI, TII, TRI, RBI);
3748     I.eraseFromParent();
3749     return true;
3750   }
3751 
3752   if (RB.getID() != AArch64::GPRRegBankID)
3753     return false;
3754 
3755   if (DstTy.getSizeInBits() != 64 || SrcTy.getSizeInBits() != 32)
3756     return false;
3757 
3758   auto *DstRC = &AArch64::GPR64RegClass;
3759   Register SubToRegDef = MRI.createVirtualRegister(DstRC);
3760   MachineInstr &SubRegMI = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
3761                                     TII.get(TargetOpcode::SUBREG_TO_REG))
3762                                 .addDef(SubToRegDef)
3763                                 .addImm(0)
3764                                 .addUse(I.getOperand(1).getReg())
3765                                 .addImm(AArch64::sub_32);
3766   Register SubToRegDef2 = MRI.createVirtualRegister(DstRC);
3767   // Need to anyext the second scalar before we can use bfm
3768   MachineInstr &SubRegMI2 = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
3769                                     TII.get(TargetOpcode::SUBREG_TO_REG))
3770                                 .addDef(SubToRegDef2)
3771                                 .addImm(0)
3772                                 .addUse(I.getOperand(2).getReg())
3773                                 .addImm(AArch64::sub_32);
3774   MachineInstr &BFM =
3775       *BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::BFMXri))
3776            .addDef(I.getOperand(0).getReg())
3777            .addUse(SubToRegDef)
3778            .addUse(SubToRegDef2)
3779            .addImm(32)
3780            .addImm(31);
3781   constrainSelectedInstRegOperands(SubRegMI, TII, TRI, RBI);
3782   constrainSelectedInstRegOperands(SubRegMI2, TII, TRI, RBI);
3783   constrainSelectedInstRegOperands(BFM, TII, TRI, RBI);
3784   I.eraseFromParent();
3785   return true;
3786 }
3787 
3788 static bool getLaneCopyOpcode(unsigned &CopyOpc, unsigned &ExtractSubReg,
3789                               const unsigned EltSize) {
3790   // Choose a lane copy opcode and subregister based off of the size of the
3791   // vector's elements.
3792   switch (EltSize) {
3793   case 16:
3794     CopyOpc = AArch64::CPYi16;
3795     ExtractSubReg = AArch64::hsub;
3796     break;
3797   case 32:
3798     CopyOpc = AArch64::CPYi32;
3799     ExtractSubReg = AArch64::ssub;
3800     break;
3801   case 64:
3802     CopyOpc = AArch64::CPYi64;
3803     ExtractSubReg = AArch64::dsub;
3804     break;
3805   default:
3806     // Unknown size, bail out.
3807     LLVM_DEBUG(dbgs() << "Elt size '" << EltSize << "' unsupported.\n");
3808     return false;
3809   }
3810   return true;
3811 }
3812 
3813 MachineInstr *AArch64InstructionSelector::emitExtractVectorElt(
3814     Optional<Register> DstReg, const RegisterBank &DstRB, LLT ScalarTy,
3815     Register VecReg, unsigned LaneIdx, MachineIRBuilder &MIRBuilder) const {
3816   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
3817   unsigned CopyOpc = 0;
3818   unsigned ExtractSubReg = 0;
3819   if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, ScalarTy.getSizeInBits())) {
3820     LLVM_DEBUG(
3821         dbgs() << "Couldn't determine lane copy opcode for instruction.\n");
3822     return nullptr;
3823   }
3824 
3825   const TargetRegisterClass *DstRC =
3826       getRegClassForTypeOnBank(ScalarTy, DstRB, RBI, true);
3827   if (!DstRC) {
3828     LLVM_DEBUG(dbgs() << "Could not determine destination register class.\n");
3829     return nullptr;
3830   }
3831 
3832   const RegisterBank &VecRB = *RBI.getRegBank(VecReg, MRI, TRI);
3833   const LLT &VecTy = MRI.getType(VecReg);
3834   const TargetRegisterClass *VecRC =
3835       getRegClassForTypeOnBank(VecTy, VecRB, RBI, true);
3836   if (!VecRC) {
3837     LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
3838     return nullptr;
3839   }
3840 
3841   // The register that we're going to copy into.
3842   Register InsertReg = VecReg;
3843   if (!DstReg)
3844     DstReg = MRI.createVirtualRegister(DstRC);
3845   // If the lane index is 0, we just use a subregister COPY.
3846   if (LaneIdx == 0) {
3847     auto Copy = MIRBuilder.buildInstr(TargetOpcode::COPY, {*DstReg}, {})
3848                     .addReg(VecReg, 0, ExtractSubReg);
3849     RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
3850     return &*Copy;
3851   }
3852 
3853   // Lane copies require 128-bit wide registers. If we're dealing with an
3854   // unpacked vector, then we need to move up to that width. Insert an implicit
3855   // def and a subregister insert to get us there.
3856   if (VecTy.getSizeInBits() != 128) {
3857     MachineInstr *ScalarToVector = emitScalarToVector(
3858         VecTy.getSizeInBits(), &AArch64::FPR128RegClass, VecReg, MIRBuilder);
3859     if (!ScalarToVector)
3860       return nullptr;
3861     InsertReg = ScalarToVector->getOperand(0).getReg();
3862   }
3863 
3864   MachineInstr *LaneCopyMI =
3865       MIRBuilder.buildInstr(CopyOpc, {*DstReg}, {InsertReg}).addImm(LaneIdx);
3866   constrainSelectedInstRegOperands(*LaneCopyMI, TII, TRI, RBI);
3867 
3868   // Make sure that we actually constrain the initial copy.
3869   RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
3870   return LaneCopyMI;
3871 }
3872 
3873 bool AArch64InstructionSelector::selectExtractElt(
3874     MachineInstr &I, MachineRegisterInfo &MRI) const {
3875   assert(I.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT &&
3876          "unexpected opcode!");
3877   Register DstReg = I.getOperand(0).getReg();
3878   const LLT NarrowTy = MRI.getType(DstReg);
3879   const Register SrcReg = I.getOperand(1).getReg();
3880   const LLT WideTy = MRI.getType(SrcReg);
3881   (void)WideTy;
3882   assert(WideTy.getSizeInBits() >= NarrowTy.getSizeInBits() &&
3883          "source register size too small!");
3884   assert(!NarrowTy.isVector() && "cannot extract vector into vector!");
3885 
3886   // Need the lane index to determine the correct copy opcode.
3887   MachineOperand &LaneIdxOp = I.getOperand(2);
3888   assert(LaneIdxOp.isReg() && "Lane index operand was not a register?");
3889 
3890   if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
3891     LLVM_DEBUG(dbgs() << "Cannot extract into GPR.\n");
3892     return false;
3893   }
3894 
3895   // Find the index to extract from.
3896   auto VRegAndVal = getConstantVRegValWithLookThrough(LaneIdxOp.getReg(), MRI);
3897   if (!VRegAndVal)
3898     return false;
3899   unsigned LaneIdx = VRegAndVal->Value.getSExtValue();
3900 
3901   MachineIRBuilder MIRBuilder(I);
3902 
3903   const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
3904   MachineInstr *Extract = emitExtractVectorElt(DstReg, DstRB, NarrowTy, SrcReg,
3905                                                LaneIdx, MIRBuilder);
3906   if (!Extract)
3907     return false;
3908 
3909   I.eraseFromParent();
3910   return true;
3911 }
3912 
3913 bool AArch64InstructionSelector::selectSplitVectorUnmerge(
3914     MachineInstr &I, MachineRegisterInfo &MRI) const {
3915   unsigned NumElts = I.getNumOperands() - 1;
3916   Register SrcReg = I.getOperand(NumElts).getReg();
3917   const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
3918   const LLT SrcTy = MRI.getType(SrcReg);
3919 
3920   assert(NarrowTy.isVector() && "Expected an unmerge into vectors");
3921   if (SrcTy.getSizeInBits() > 128) {
3922     LLVM_DEBUG(dbgs() << "Unexpected vector type for vec split unmerge");
3923     return false;
3924   }
3925 
3926   MachineIRBuilder MIB(I);
3927 
3928   // We implement a split vector operation by treating the sub-vectors as
3929   // scalars and extracting them.
3930   const RegisterBank &DstRB =
3931       *RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI);
3932   for (unsigned OpIdx = 0; OpIdx < NumElts; ++OpIdx) {
3933     Register Dst = I.getOperand(OpIdx).getReg();
3934     MachineInstr *Extract =
3935         emitExtractVectorElt(Dst, DstRB, NarrowTy, SrcReg, OpIdx, MIB);
3936     if (!Extract)
3937       return false;
3938   }
3939   I.eraseFromParent();
3940   return true;
3941 }
3942 
3943 bool AArch64InstructionSelector::selectUnmergeValues(
3944     MachineInstr &I, MachineRegisterInfo &MRI) const {
3945   assert(I.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
3946          "unexpected opcode");
3947 
3948   // TODO: Handle unmerging into GPRs and from scalars to scalars.
3949   if (RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI)->getID() !=
3950           AArch64::FPRRegBankID ||
3951       RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI)->getID() !=
3952           AArch64::FPRRegBankID) {
3953     LLVM_DEBUG(dbgs() << "Unmerging vector-to-gpr and scalar-to-scalar "
3954                          "currently unsupported.\n");
3955     return false;
3956   }
3957 
3958   // The last operand is the vector source register, and every other operand is
3959   // a register to unpack into.
3960   unsigned NumElts = I.getNumOperands() - 1;
3961   Register SrcReg = I.getOperand(NumElts).getReg();
3962   const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
3963   const LLT WideTy = MRI.getType(SrcReg);
3964   (void)WideTy;
3965   assert((WideTy.isVector() || WideTy.getSizeInBits() == 128) &&
3966          "can only unmerge from vector or s128 types!");
3967   assert(WideTy.getSizeInBits() > NarrowTy.getSizeInBits() &&
3968          "source register size too small!");
3969 
3970   if (!NarrowTy.isScalar())
3971     return selectSplitVectorUnmerge(I, MRI);
3972 
3973   MachineIRBuilder MIB(I);
3974 
3975   // Choose a lane copy opcode and subregister based off of the size of the
3976   // vector's elements.
3977   unsigned CopyOpc = 0;
3978   unsigned ExtractSubReg = 0;
3979   if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, NarrowTy.getSizeInBits()))
3980     return false;
3981 
3982   // Set up for the lane copies.
3983   MachineBasicBlock &MBB = *I.getParent();
3984 
3985   // Stores the registers we'll be copying from.
3986   SmallVector<Register, 4> InsertRegs;
3987 
3988   // We'll use the first register twice, so we only need NumElts-1 registers.
3989   unsigned NumInsertRegs = NumElts - 1;
3990 
3991   // If our elements fit into exactly 128 bits, then we can copy from the source
3992   // directly. Otherwise, we need to do a bit of setup with some subregister
3993   // inserts.
3994   if (NarrowTy.getSizeInBits() * NumElts == 128) {
3995     InsertRegs = SmallVector<Register, 4>(NumInsertRegs, SrcReg);
3996   } else {
3997     // No. We have to perform subregister inserts. For each insert, create an
3998     // implicit def and a subregister insert, and save the register we create.
3999     for (unsigned Idx = 0; Idx < NumInsertRegs; ++Idx) {
4000       Register ImpDefReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
4001       MachineInstr &ImpDefMI =
4002           *BuildMI(MBB, I, I.getDebugLoc(), TII.get(TargetOpcode::IMPLICIT_DEF),
4003                    ImpDefReg);
4004 
4005       // Now, create the subregister insert from SrcReg.
4006       Register InsertReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
4007       MachineInstr &InsMI =
4008           *BuildMI(MBB, I, I.getDebugLoc(),
4009                    TII.get(TargetOpcode::INSERT_SUBREG), InsertReg)
4010                .addUse(ImpDefReg)
4011                .addUse(SrcReg)
4012                .addImm(AArch64::dsub);
4013 
4014       constrainSelectedInstRegOperands(ImpDefMI, TII, TRI, RBI);
4015       constrainSelectedInstRegOperands(InsMI, TII, TRI, RBI);
4016 
4017       // Save the register so that we can copy from it after.
4018       InsertRegs.push_back(InsertReg);
4019     }
4020   }
4021 
4022   // Now that we've created any necessary subregister inserts, we can
4023   // create the copies.
4024   //
4025   // Perform the first copy separately as a subregister copy.
4026   Register CopyTo = I.getOperand(0).getReg();
4027   auto FirstCopy = MIB.buildInstr(TargetOpcode::COPY, {CopyTo}, {})
4028                        .addReg(InsertRegs[0], 0, ExtractSubReg);
4029   constrainSelectedInstRegOperands(*FirstCopy, TII, TRI, RBI);
4030 
4031   // Now, perform the remaining copies as vector lane copies.
4032   unsigned LaneIdx = 1;
4033   for (Register InsReg : InsertRegs) {
4034     Register CopyTo = I.getOperand(LaneIdx).getReg();
4035     MachineInstr &CopyInst =
4036         *BuildMI(MBB, I, I.getDebugLoc(), TII.get(CopyOpc), CopyTo)
4037              .addUse(InsReg)
4038              .addImm(LaneIdx);
4039     constrainSelectedInstRegOperands(CopyInst, TII, TRI, RBI);
4040     ++LaneIdx;
4041   }
4042 
4043   // Separately constrain the first copy's destination. Because of the
4044   // limitation in constrainOperandRegClass, we can't guarantee that this will
4045   // actually be constrained. So, do it ourselves using the second operand.
4046   const TargetRegisterClass *RC =
4047       MRI.getRegClassOrNull(I.getOperand(1).getReg());
4048   if (!RC) {
4049     LLVM_DEBUG(dbgs() << "Couldn't constrain copy destination.\n");
4050     return false;
4051   }
4052 
4053   RBI.constrainGenericRegister(CopyTo, *RC, MRI);
4054   I.eraseFromParent();
4055   return true;
4056 }
4057 
4058 bool AArch64InstructionSelector::selectConcatVectors(
4059     MachineInstr &I, MachineRegisterInfo &MRI) const {
4060   assert(I.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
4061          "Unexpected opcode");
4062   Register Dst = I.getOperand(0).getReg();
4063   Register Op1 = I.getOperand(1).getReg();
4064   Register Op2 = I.getOperand(2).getReg();
4065   MachineIRBuilder MIRBuilder(I);
4066   MachineInstr *ConcatMI = emitVectorConcat(Dst, Op1, Op2, MIRBuilder);
4067   if (!ConcatMI)
4068     return false;
4069   I.eraseFromParent();
4070   return true;
4071 }
4072 
4073 unsigned
4074 AArch64InstructionSelector::emitConstantPoolEntry(const Constant *CPVal,
4075                                                   MachineFunction &MF) const {
4076   Type *CPTy = CPVal->getType();
4077   Align Alignment = MF.getDataLayout().getPrefTypeAlign(CPTy);
4078 
4079   MachineConstantPool *MCP = MF.getConstantPool();
4080   return MCP->getConstantPoolIndex(CPVal, Alignment);
4081 }
4082 
4083 MachineInstr *AArch64InstructionSelector::emitLoadFromConstantPool(
4084     const Constant *CPVal, MachineIRBuilder &MIRBuilder) const {
4085   unsigned CPIdx = emitConstantPoolEntry(CPVal, MIRBuilder.getMF());
4086 
4087   auto Adrp =
4088       MIRBuilder.buildInstr(AArch64::ADRP, {&AArch64::GPR64RegClass}, {})
4089           .addConstantPoolIndex(CPIdx, 0, AArch64II::MO_PAGE);
4090 
4091   MachineInstr *LoadMI = nullptr;
4092   switch (MIRBuilder.getDataLayout().getTypeStoreSize(CPVal->getType())) {
4093   case 16:
4094     LoadMI =
4095         &*MIRBuilder
4096               .buildInstr(AArch64::LDRQui, {&AArch64::FPR128RegClass}, {Adrp})
4097               .addConstantPoolIndex(CPIdx, 0,
4098                                     AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4099     break;
4100   case 8:
4101     LoadMI =
4102         &*MIRBuilder
4103               .buildInstr(AArch64::LDRDui, {&AArch64::FPR64RegClass}, {Adrp})
4104               .addConstantPoolIndex(CPIdx, 0,
4105                                     AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4106     break;
4107   case 4:
4108     LoadMI =
4109         &*MIRBuilder
4110               .buildInstr(AArch64::LDRSui, {&AArch64::FPR32RegClass}, {Adrp})
4111               .addConstantPoolIndex(CPIdx, 0,
4112                                     AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4113     break;
4114   default:
4115     LLVM_DEBUG(dbgs() << "Could not load from constant pool of type "
4116                       << *CPVal->getType());
4117     return nullptr;
4118   }
4119   constrainSelectedInstRegOperands(*Adrp, TII, TRI, RBI);
4120   constrainSelectedInstRegOperands(*LoadMI, TII, TRI, RBI);
4121   return LoadMI;
4122 }
4123 
4124 /// Return an <Opcode, SubregIndex> pair to do an vector elt insert of a given
4125 /// size and RB.
4126 static std::pair<unsigned, unsigned>
4127 getInsertVecEltOpInfo(const RegisterBank &RB, unsigned EltSize) {
4128   unsigned Opc, SubregIdx;
4129   if (RB.getID() == AArch64::GPRRegBankID) {
4130     if (EltSize == 16) {
4131       Opc = AArch64::INSvi16gpr;
4132       SubregIdx = AArch64::ssub;
4133     } else if (EltSize == 32) {
4134       Opc = AArch64::INSvi32gpr;
4135       SubregIdx = AArch64::ssub;
4136     } else if (EltSize == 64) {
4137       Opc = AArch64::INSvi64gpr;
4138       SubregIdx = AArch64::dsub;
4139     } else {
4140       llvm_unreachable("invalid elt size!");
4141     }
4142   } else {
4143     if (EltSize == 8) {
4144       Opc = AArch64::INSvi8lane;
4145       SubregIdx = AArch64::bsub;
4146     } else if (EltSize == 16) {
4147       Opc = AArch64::INSvi16lane;
4148       SubregIdx = AArch64::hsub;
4149     } else if (EltSize == 32) {
4150       Opc = AArch64::INSvi32lane;
4151       SubregIdx = AArch64::ssub;
4152     } else if (EltSize == 64) {
4153       Opc = AArch64::INSvi64lane;
4154       SubregIdx = AArch64::dsub;
4155     } else {
4156       llvm_unreachable("invalid elt size!");
4157     }
4158   }
4159   return std::make_pair(Opc, SubregIdx);
4160 }
4161 
4162 MachineInstr *AArch64InstructionSelector::emitInstr(
4163     unsigned Opcode, std::initializer_list<llvm::DstOp> DstOps,
4164     std::initializer_list<llvm::SrcOp> SrcOps, MachineIRBuilder &MIRBuilder,
4165     const ComplexRendererFns &RenderFns) const {
4166   assert(Opcode && "Expected an opcode?");
4167   assert(!isPreISelGenericOpcode(Opcode) &&
4168          "Function should only be used to produce selected instructions!");
4169   auto MI = MIRBuilder.buildInstr(Opcode, DstOps, SrcOps);
4170   if (RenderFns)
4171     for (auto &Fn : *RenderFns)
4172       Fn(MI);
4173   constrainSelectedInstRegOperands(*MI, TII, TRI, RBI);
4174   return &*MI;
4175 }
4176 
4177 MachineInstr *AArch64InstructionSelector::emitAddSub(
4178     const std::array<std::array<unsigned, 2>, 5> &AddrModeAndSizeToOpcode,
4179     Register Dst, MachineOperand &LHS, MachineOperand &RHS,
4180     MachineIRBuilder &MIRBuilder) const {
4181   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4182   assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
4183   auto Ty = MRI.getType(LHS.getReg());
4184   assert(!Ty.isVector() && "Expected a scalar or pointer?");
4185   unsigned Size = Ty.getSizeInBits();
4186   assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit type only");
4187   bool Is32Bit = Size == 32;
4188 
4189   // INSTRri form with positive arithmetic immediate.
4190   if (auto Fns = selectArithImmed(RHS))
4191     return emitInstr(AddrModeAndSizeToOpcode[0][Is32Bit], {Dst}, {LHS},
4192                      MIRBuilder, Fns);
4193 
4194   // INSTRri form with negative arithmetic immediate.
4195   if (auto Fns = selectNegArithImmed(RHS))
4196     return emitInstr(AddrModeAndSizeToOpcode[3][Is32Bit], {Dst}, {LHS},
4197                      MIRBuilder, Fns);
4198 
4199   // INSTRrx form.
4200   if (auto Fns = selectArithExtendedRegister(RHS))
4201     return emitInstr(AddrModeAndSizeToOpcode[4][Is32Bit], {Dst}, {LHS},
4202                      MIRBuilder, Fns);
4203 
4204   // INSTRrs form.
4205   if (auto Fns = selectShiftedRegister(RHS))
4206     return emitInstr(AddrModeAndSizeToOpcode[1][Is32Bit], {Dst}, {LHS},
4207                      MIRBuilder, Fns);
4208   return emitInstr(AddrModeAndSizeToOpcode[2][Is32Bit], {Dst}, {LHS, RHS},
4209                    MIRBuilder);
4210 }
4211 
4212 MachineInstr *
4213 AArch64InstructionSelector::emitADD(Register DefReg, MachineOperand &LHS,
4214                                     MachineOperand &RHS,
4215                                     MachineIRBuilder &MIRBuilder) const {
4216   const std::array<std::array<unsigned, 2>, 5> OpcTable{
4217       {{AArch64::ADDXri, AArch64::ADDWri},
4218        {AArch64::ADDXrs, AArch64::ADDWrs},
4219        {AArch64::ADDXrr, AArch64::ADDWrr},
4220        {AArch64::SUBXri, AArch64::SUBWri},
4221        {AArch64::ADDXrx, AArch64::ADDWrx}}};
4222   return emitAddSub(OpcTable, DefReg, LHS, RHS, MIRBuilder);
4223 }
4224 
4225 MachineInstr *
4226 AArch64InstructionSelector::emitADDS(Register Dst, MachineOperand &LHS,
4227                                      MachineOperand &RHS,
4228                                      MachineIRBuilder &MIRBuilder) const {
4229   const std::array<std::array<unsigned, 2>, 5> OpcTable{
4230       {{AArch64::ADDSXri, AArch64::ADDSWri},
4231        {AArch64::ADDSXrs, AArch64::ADDSWrs},
4232        {AArch64::ADDSXrr, AArch64::ADDSWrr},
4233        {AArch64::SUBSXri, AArch64::SUBSWri},
4234        {AArch64::ADDSXrx, AArch64::ADDSWrx}}};
4235   return emitAddSub(OpcTable, Dst, LHS, RHS, MIRBuilder);
4236 }
4237 
4238 MachineInstr *
4239 AArch64InstructionSelector::emitSUBS(Register Dst, MachineOperand &LHS,
4240                                      MachineOperand &RHS,
4241                                      MachineIRBuilder &MIRBuilder) const {
4242   const std::array<std::array<unsigned, 2>, 5> OpcTable{
4243       {{AArch64::SUBSXri, AArch64::SUBSWri},
4244        {AArch64::SUBSXrs, AArch64::SUBSWrs},
4245        {AArch64::SUBSXrr, AArch64::SUBSWrr},
4246        {AArch64::ADDSXri, AArch64::ADDSWri},
4247        {AArch64::SUBSXrx, AArch64::SUBSWrx}}};
4248   return emitAddSub(OpcTable, Dst, LHS, RHS, MIRBuilder);
4249 }
4250 
4251 MachineInstr *
4252 AArch64InstructionSelector::emitCMN(MachineOperand &LHS, MachineOperand &RHS,
4253                                     MachineIRBuilder &MIRBuilder) const {
4254   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4255   bool Is32Bit = (MRI.getType(LHS.getReg()).getSizeInBits() == 32);
4256   auto RC = Is32Bit ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass;
4257   return emitADDS(MRI.createVirtualRegister(RC), LHS, RHS, MIRBuilder);
4258 }
4259 
4260 MachineInstr *
4261 AArch64InstructionSelector::emitTST(MachineOperand &LHS, MachineOperand &RHS,
4262                                     MachineIRBuilder &MIRBuilder) const {
4263   assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
4264   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4265   LLT Ty = MRI.getType(LHS.getReg());
4266   unsigned RegSize = Ty.getSizeInBits();
4267   bool Is32Bit = (RegSize == 32);
4268   const unsigned OpcTable[3][2] = {{AArch64::ANDSXri, AArch64::ANDSWri},
4269                                    {AArch64::ANDSXrs, AArch64::ANDSWrs},
4270                                    {AArch64::ANDSXrr, AArch64::ANDSWrr}};
4271   // ANDS needs a logical immediate for its immediate form. Check if we can
4272   // fold one in.
4273   if (auto ValAndVReg = getConstantVRegValWithLookThrough(RHS.getReg(), MRI)) {
4274     int64_t Imm = ValAndVReg->Value.getSExtValue();
4275 
4276     if (AArch64_AM::isLogicalImmediate(Imm, RegSize)) {
4277       auto TstMI = MIRBuilder.buildInstr(OpcTable[0][Is32Bit], {Ty}, {LHS});
4278       TstMI.addImm(AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
4279       constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
4280       return &*TstMI;
4281     }
4282   }
4283 
4284   if (auto Fns = selectLogicalShiftedRegister(RHS))
4285     return emitInstr(OpcTable[1][Is32Bit], {Ty}, {LHS}, MIRBuilder, Fns);
4286   return emitInstr(OpcTable[2][Is32Bit], {Ty}, {LHS, RHS}, MIRBuilder);
4287 }
4288 
4289 MachineInstr *AArch64InstructionSelector::emitIntegerCompare(
4290     MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
4291     MachineIRBuilder &MIRBuilder) const {
4292   assert(LHS.isReg() && RHS.isReg() && "Expected LHS and RHS to be registers!");
4293   assert(Predicate.isPredicate() && "Expected predicate?");
4294   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4295   LLT CmpTy = MRI.getType(LHS.getReg());
4296   assert(!CmpTy.isVector() && "Expected scalar or pointer");
4297   unsigned Size = CmpTy.getSizeInBits();
4298   (void)Size;
4299   assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit LHS/RHS?");
4300   // Fold the compare into a cmn or tst if possible.
4301   if (auto FoldCmp = tryFoldIntegerCompare(LHS, RHS, Predicate, MIRBuilder))
4302     return FoldCmp;
4303   auto Dst = MRI.cloneVirtualRegister(LHS.getReg());
4304   return emitSUBS(Dst, LHS, RHS, MIRBuilder);
4305 }
4306 
4307 MachineInstr *AArch64InstructionSelector::emitCSetForFCmp(
4308     Register Dst, CmpInst::Predicate Pred, MachineIRBuilder &MIRBuilder) const {
4309   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4310 #ifndef NDEBUG
4311   LLT Ty = MRI.getType(Dst);
4312   assert(!Ty.isVector() && Ty.getSizeInBits() == 32 &&
4313          "Expected a 32-bit scalar register?");
4314 #endif
4315   const Register ZeroReg = AArch64::WZR;
4316   auto EmitCSet = [&](Register CsetDst, AArch64CC::CondCode CC) {
4317     auto CSet =
4318         MIRBuilder.buildInstr(AArch64::CSINCWr, {CsetDst}, {ZeroReg, ZeroReg})
4319             .addImm(getInvertedCondCode(CC));
4320     constrainSelectedInstRegOperands(*CSet, TII, TRI, RBI);
4321     return &*CSet;
4322   };
4323 
4324   AArch64CC::CondCode CC1, CC2;
4325   changeFCMPPredToAArch64CC(Pred, CC1, CC2);
4326   if (CC2 == AArch64CC::AL)
4327     return EmitCSet(Dst, CC1);
4328 
4329   const TargetRegisterClass *RC = &AArch64::GPR32RegClass;
4330   Register Def1Reg = MRI.createVirtualRegister(RC);
4331   Register Def2Reg = MRI.createVirtualRegister(RC);
4332   EmitCSet(Def1Reg, CC1);
4333   EmitCSet(Def2Reg, CC2);
4334   auto OrMI = MIRBuilder.buildInstr(AArch64::ORRWrr, {Dst}, {Def1Reg, Def2Reg});
4335   constrainSelectedInstRegOperands(*OrMI, TII, TRI, RBI);
4336   return &*OrMI;
4337 }
4338 
4339 MachineInstr *
4340 AArch64InstructionSelector::emitFPCompare(Register LHS, Register RHS,
4341                                           MachineIRBuilder &MIRBuilder,
4342                                           Optional<CmpInst::Predicate> Pred) const {
4343   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4344   LLT Ty = MRI.getType(LHS);
4345   if (Ty.isVector())
4346     return nullptr;
4347   unsigned OpSize = Ty.getSizeInBits();
4348   if (OpSize != 32 && OpSize != 64)
4349     return nullptr;
4350 
4351   // If this is a compare against +0.0, then we don't have
4352   // to explicitly materialize a constant.
4353   const ConstantFP *FPImm = getConstantFPVRegVal(RHS, MRI);
4354   bool ShouldUseImm = FPImm && (FPImm->isZero() && !FPImm->isNegative());
4355 
4356   auto IsEqualityPred = [](CmpInst::Predicate P) {
4357     return P == CmpInst::FCMP_OEQ || P == CmpInst::FCMP_ONE ||
4358            P == CmpInst::FCMP_UEQ || P == CmpInst::FCMP_UNE;
4359   };
4360   if (!ShouldUseImm && Pred && IsEqualityPred(*Pred)) {
4361     // Try commutating the operands.
4362     const ConstantFP *LHSImm = getConstantFPVRegVal(LHS, MRI);
4363     if (LHSImm && (LHSImm->isZero() && !LHSImm->isNegative())) {
4364       ShouldUseImm = true;
4365       std::swap(LHS, RHS);
4366     }
4367   }
4368   unsigned CmpOpcTbl[2][2] = {{AArch64::FCMPSrr, AArch64::FCMPDrr},
4369                               {AArch64::FCMPSri, AArch64::FCMPDri}};
4370   unsigned CmpOpc = CmpOpcTbl[ShouldUseImm][OpSize == 64];
4371 
4372   // Partially build the compare. Decide if we need to add a use for the
4373   // third operand based off whether or not we're comparing against 0.0.
4374   auto CmpMI = MIRBuilder.buildInstr(CmpOpc).addUse(LHS);
4375   if (!ShouldUseImm)
4376     CmpMI.addUse(RHS);
4377   constrainSelectedInstRegOperands(*CmpMI, TII, TRI, RBI);
4378   return &*CmpMI;
4379 }
4380 
4381 MachineInstr *AArch64InstructionSelector::emitVectorConcat(
4382     Optional<Register> Dst, Register Op1, Register Op2,
4383     MachineIRBuilder &MIRBuilder) const {
4384   // We implement a vector concat by:
4385   // 1. Use scalar_to_vector to insert the lower vector into the larger dest
4386   // 2. Insert the upper vector into the destination's upper element
4387   // TODO: some of this code is common with G_BUILD_VECTOR handling.
4388   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4389 
4390   const LLT Op1Ty = MRI.getType(Op1);
4391   const LLT Op2Ty = MRI.getType(Op2);
4392 
4393   if (Op1Ty != Op2Ty) {
4394     LLVM_DEBUG(dbgs() << "Could not do vector concat of differing vector tys");
4395     return nullptr;
4396   }
4397   assert(Op1Ty.isVector() && "Expected a vector for vector concat");
4398 
4399   if (Op1Ty.getSizeInBits() >= 128) {
4400     LLVM_DEBUG(dbgs() << "Vector concat not supported for full size vectors");
4401     return nullptr;
4402   }
4403 
4404   // At the moment we just support 64 bit vector concats.
4405   if (Op1Ty.getSizeInBits() != 64) {
4406     LLVM_DEBUG(dbgs() << "Vector concat supported for 64b vectors");
4407     return nullptr;
4408   }
4409 
4410   const LLT ScalarTy = LLT::scalar(Op1Ty.getSizeInBits());
4411   const RegisterBank &FPRBank = *RBI.getRegBank(Op1, MRI, TRI);
4412   const TargetRegisterClass *DstRC =
4413       getMinClassForRegBank(FPRBank, Op1Ty.getSizeInBits() * 2);
4414 
4415   MachineInstr *WidenedOp1 =
4416       emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op1, MIRBuilder);
4417   MachineInstr *WidenedOp2 =
4418       emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op2, MIRBuilder);
4419   if (!WidenedOp1 || !WidenedOp2) {
4420     LLVM_DEBUG(dbgs() << "Could not emit a vector from scalar value");
4421     return nullptr;
4422   }
4423 
4424   // Now do the insert of the upper element.
4425   unsigned InsertOpc, InsSubRegIdx;
4426   std::tie(InsertOpc, InsSubRegIdx) =
4427       getInsertVecEltOpInfo(FPRBank, ScalarTy.getSizeInBits());
4428 
4429   if (!Dst)
4430     Dst = MRI.createVirtualRegister(DstRC);
4431   auto InsElt =
4432       MIRBuilder
4433           .buildInstr(InsertOpc, {*Dst}, {WidenedOp1->getOperand(0).getReg()})
4434           .addImm(1) /* Lane index */
4435           .addUse(WidenedOp2->getOperand(0).getReg())
4436           .addImm(0);
4437   constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
4438   return &*InsElt;
4439 }
4440 
4441 MachineInstr *
4442 AArch64InstructionSelector::emitCSetForICMP(Register DefReg, unsigned Pred,
4443                                             MachineIRBuilder &MIRBuilder,
4444                                             Register SrcReg) const {
4445   // CSINC increments the result when the predicate is false. Invert it.
4446   const AArch64CC::CondCode InvCC = changeICMPPredToAArch64CC(
4447       CmpInst::getInversePredicate((CmpInst::Predicate)Pred));
4448   auto I = MIRBuilder.buildInstr(AArch64::CSINCWr, {DefReg}, {SrcReg, SrcReg})
4449                .addImm(InvCC);
4450   constrainSelectedInstRegOperands(*I, TII, TRI, RBI);
4451   return &*I;
4452 }
4453 
4454 std::pair<MachineInstr *, AArch64CC::CondCode>
4455 AArch64InstructionSelector::emitOverflowOp(unsigned Opcode, Register Dst,
4456                                            MachineOperand &LHS,
4457                                            MachineOperand &RHS,
4458                                            MachineIRBuilder &MIRBuilder) const {
4459   switch (Opcode) {
4460   default:
4461     llvm_unreachable("Unexpected opcode!");
4462   case TargetOpcode::G_SADDO:
4463     return std::make_pair(emitADDS(Dst, LHS, RHS, MIRBuilder), AArch64CC::VS);
4464   case TargetOpcode::G_UADDO:
4465     return std::make_pair(emitADDS(Dst, LHS, RHS, MIRBuilder), AArch64CC::HS);
4466   case TargetOpcode::G_SSUBO:
4467     return std::make_pair(emitSUBS(Dst, LHS, RHS, MIRBuilder), AArch64CC::VS);
4468   case TargetOpcode::G_USUBO:
4469     return std::make_pair(emitSUBS(Dst, LHS, RHS, MIRBuilder), AArch64CC::LO);
4470   }
4471 }
4472 
4473 bool AArch64InstructionSelector::tryOptSelect(MachineInstr &I) const {
4474   MachineIRBuilder MIB(I);
4475   MachineRegisterInfo &MRI = *MIB.getMRI();
4476   // We want to recognize this pattern:
4477   //
4478   // $z = G_FCMP pred, $x, $y
4479   // ...
4480   // $w = G_SELECT $z, $a, $b
4481   //
4482   // Where the value of $z is *only* ever used by the G_SELECT (possibly with
4483   // some copies/truncs in between.)
4484   //
4485   // If we see this, then we can emit something like this:
4486   //
4487   // fcmp $x, $y
4488   // fcsel $w, $a, $b, pred
4489   //
4490   // Rather than emitting both of the rather long sequences in the standard
4491   // G_FCMP/G_SELECT select methods.
4492 
4493   // First, check if the condition is defined by a compare.
4494   MachineInstr *CondDef = MRI.getVRegDef(I.getOperand(1).getReg());
4495   while (CondDef) {
4496     // We can only fold if all of the defs have one use.
4497     Register CondDefReg = CondDef->getOperand(0).getReg();
4498     if (!MRI.hasOneNonDBGUse(CondDefReg)) {
4499       // Unless it's another select.
4500       for (const MachineInstr &UI : MRI.use_nodbg_instructions(CondDefReg)) {
4501         if (CondDef == &UI)
4502           continue;
4503         if (UI.getOpcode() != TargetOpcode::G_SELECT)
4504           return false;
4505       }
4506     }
4507 
4508     // We can skip over G_TRUNC since the condition is 1-bit.
4509     // Truncating/extending can have no impact on the value.
4510     unsigned Opc = CondDef->getOpcode();
4511     if (Opc != TargetOpcode::COPY && Opc != TargetOpcode::G_TRUNC)
4512       break;
4513 
4514     // Can't see past copies from physregs.
4515     if (Opc == TargetOpcode::COPY &&
4516         Register::isPhysicalRegister(CondDef->getOperand(1).getReg()))
4517       return false;
4518 
4519     CondDef = MRI.getVRegDef(CondDef->getOperand(1).getReg());
4520   }
4521 
4522   // Is the condition defined by a compare?
4523   if (!CondDef)
4524     return false;
4525 
4526   unsigned CondOpc = CondDef->getOpcode();
4527   if (CondOpc != TargetOpcode::G_ICMP && CondOpc != TargetOpcode::G_FCMP)
4528     return false;
4529 
4530   AArch64CC::CondCode CondCode;
4531   if (CondOpc == TargetOpcode::G_ICMP) {
4532     auto Pred =
4533         static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
4534     CondCode = changeICMPPredToAArch64CC(Pred);
4535     emitIntegerCompare(CondDef->getOperand(2), CondDef->getOperand(3),
4536                        CondDef->getOperand(1), MIB);
4537   } else {
4538     // Get the condition code for the select.
4539     auto Pred =
4540         static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
4541     AArch64CC::CondCode CondCode2;
4542     changeFCMPPredToAArch64CC(Pred, CondCode, CondCode2);
4543 
4544     // changeFCMPPredToAArch64CC sets CondCode2 to AL when we require two
4545     // instructions to emit the comparison.
4546     // TODO: Handle FCMP_UEQ and FCMP_ONE. After that, this check will be
4547     // unnecessary.
4548     if (CondCode2 != AArch64CC::AL)
4549       return false;
4550 
4551     if (!emitFPCompare(CondDef->getOperand(2).getReg(),
4552                        CondDef->getOperand(3).getReg(), MIB)) {
4553       LLVM_DEBUG(dbgs() << "Couldn't emit compare for select!\n");
4554       return false;
4555     }
4556   }
4557 
4558   // Emit the select.
4559   emitSelect(I.getOperand(0).getReg(), I.getOperand(2).getReg(),
4560              I.getOperand(3).getReg(), CondCode, MIB);
4561   I.eraseFromParent();
4562   return true;
4563 }
4564 
4565 MachineInstr *AArch64InstructionSelector::tryFoldIntegerCompare(
4566     MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
4567     MachineIRBuilder &MIRBuilder) const {
4568   assert(LHS.isReg() && RHS.isReg() && Predicate.isPredicate() &&
4569          "Unexpected MachineOperand");
4570   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4571   // We want to find this sort of thing:
4572   // x = G_SUB 0, y
4573   // G_ICMP z, x
4574   //
4575   // In this case, we can fold the G_SUB into the G_ICMP using a CMN instead.
4576   // e.g:
4577   //
4578   // cmn z, y
4579 
4580   // Check if the RHS or LHS of the G_ICMP is defined by a SUB
4581   MachineInstr *LHSDef = getDefIgnoringCopies(LHS.getReg(), MRI);
4582   MachineInstr *RHSDef = getDefIgnoringCopies(RHS.getReg(), MRI);
4583   auto P = static_cast<CmpInst::Predicate>(Predicate.getPredicate());
4584   // Given this:
4585   //
4586   // x = G_SUB 0, y
4587   // G_ICMP x, z
4588   //
4589   // Produce this:
4590   //
4591   // cmn y, z
4592   if (isCMN(LHSDef, P, MRI))
4593     return emitCMN(LHSDef->getOperand(2), RHS, MIRBuilder);
4594 
4595   // Same idea here, but with the RHS of the compare instead:
4596   //
4597   // Given this:
4598   //
4599   // x = G_SUB 0, y
4600   // G_ICMP z, x
4601   //
4602   // Produce this:
4603   //
4604   // cmn z, y
4605   if (isCMN(RHSDef, P, MRI))
4606     return emitCMN(LHS, RHSDef->getOperand(2), MIRBuilder);
4607 
4608   // Given this:
4609   //
4610   // z = G_AND x, y
4611   // G_ICMP z, 0
4612   //
4613   // Produce this if the compare is signed:
4614   //
4615   // tst x, y
4616   if (!CmpInst::isUnsigned(P) && LHSDef &&
4617       LHSDef->getOpcode() == TargetOpcode::G_AND) {
4618     // Make sure that the RHS is 0.
4619     auto ValAndVReg = getConstantVRegValWithLookThrough(RHS.getReg(), MRI);
4620     if (!ValAndVReg || ValAndVReg->Value != 0)
4621       return nullptr;
4622 
4623     return emitTST(LHSDef->getOperand(1),
4624                    LHSDef->getOperand(2), MIRBuilder);
4625   }
4626 
4627   return nullptr;
4628 }
4629 
4630 bool AArch64InstructionSelector::selectShuffleVector(
4631     MachineInstr &I, MachineRegisterInfo &MRI) const {
4632   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
4633   Register Src1Reg = I.getOperand(1).getReg();
4634   const LLT Src1Ty = MRI.getType(Src1Reg);
4635   Register Src2Reg = I.getOperand(2).getReg();
4636   const LLT Src2Ty = MRI.getType(Src2Reg);
4637   ArrayRef<int> Mask = I.getOperand(3).getShuffleMask();
4638 
4639   MachineBasicBlock &MBB = *I.getParent();
4640   MachineFunction &MF = *MBB.getParent();
4641   LLVMContext &Ctx = MF.getFunction().getContext();
4642 
4643   // G_SHUFFLE_VECTOR is weird in that the source operands can be scalars, if
4644   // it's originated from a <1 x T> type. Those should have been lowered into
4645   // G_BUILD_VECTOR earlier.
4646   if (!Src1Ty.isVector() || !Src2Ty.isVector()) {
4647     LLVM_DEBUG(dbgs() << "Could not select a \"scalar\" G_SHUFFLE_VECTOR\n");
4648     return false;
4649   }
4650 
4651   unsigned BytesPerElt = DstTy.getElementType().getSizeInBits() / 8;
4652 
4653   SmallVector<Constant *, 64> CstIdxs;
4654   for (int Val : Mask) {
4655     // For now, any undef indexes we'll just assume to be 0. This should be
4656     // optimized in future, e.g. to select DUP etc.
4657     Val = Val < 0 ? 0 : Val;
4658     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4659       unsigned Offset = Byte + Val * BytesPerElt;
4660       CstIdxs.emplace_back(ConstantInt::get(Type::getInt8Ty(Ctx), Offset));
4661     }
4662   }
4663 
4664   MachineIRBuilder MIRBuilder(I);
4665 
4666   // Use a constant pool to load the index vector for TBL.
4667   Constant *CPVal = ConstantVector::get(CstIdxs);
4668   MachineInstr *IndexLoad = emitLoadFromConstantPool(CPVal, MIRBuilder);
4669   if (!IndexLoad) {
4670     LLVM_DEBUG(dbgs() << "Could not load from a constant pool");
4671     return false;
4672   }
4673 
4674   if (DstTy.getSizeInBits() != 128) {
4675     assert(DstTy.getSizeInBits() == 64 && "Unexpected shuffle result ty");
4676     // This case can be done with TBL1.
4677     MachineInstr *Concat = emitVectorConcat(None, Src1Reg, Src2Reg, MIRBuilder);
4678     if (!Concat) {
4679       LLVM_DEBUG(dbgs() << "Could not do vector concat for tbl1");
4680       return false;
4681     }
4682 
4683     // The constant pool load will be 64 bits, so need to convert to FPR128 reg.
4684     IndexLoad =
4685         emitScalarToVector(64, &AArch64::FPR128RegClass,
4686                            IndexLoad->getOperand(0).getReg(), MIRBuilder);
4687 
4688     auto TBL1 = MIRBuilder.buildInstr(
4689         AArch64::TBLv16i8One, {&AArch64::FPR128RegClass},
4690         {Concat->getOperand(0).getReg(), IndexLoad->getOperand(0).getReg()});
4691     constrainSelectedInstRegOperands(*TBL1, TII, TRI, RBI);
4692 
4693     auto Copy =
4694         MIRBuilder
4695             .buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
4696             .addReg(TBL1.getReg(0), 0, AArch64::dsub);
4697     RBI.constrainGenericRegister(Copy.getReg(0), AArch64::FPR64RegClass, MRI);
4698     I.eraseFromParent();
4699     return true;
4700   }
4701 
4702   // For TBL2 we need to emit a REG_SEQUENCE to tie together two consecutive
4703   // Q registers for regalloc.
4704   auto RegSeq = MIRBuilder
4705                     .buildInstr(TargetOpcode::REG_SEQUENCE,
4706                                 {&AArch64::QQRegClass}, {Src1Reg})
4707                     .addImm(AArch64::qsub0)
4708                     .addUse(Src2Reg)
4709                     .addImm(AArch64::qsub1);
4710 
4711   auto TBL2 = MIRBuilder.buildInstr(AArch64::TBLv16i8Two, {I.getOperand(0)},
4712                                     {RegSeq, IndexLoad->getOperand(0)});
4713   constrainSelectedInstRegOperands(*RegSeq, TII, TRI, RBI);
4714   constrainSelectedInstRegOperands(*TBL2, TII, TRI, RBI);
4715   I.eraseFromParent();
4716   return true;
4717 }
4718 
4719 MachineInstr *AArch64InstructionSelector::emitLaneInsert(
4720     Optional<Register> DstReg, Register SrcReg, Register EltReg,
4721     unsigned LaneIdx, const RegisterBank &RB,
4722     MachineIRBuilder &MIRBuilder) const {
4723   MachineInstr *InsElt = nullptr;
4724   const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
4725   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4726 
4727   // Create a register to define with the insert if one wasn't passed in.
4728   if (!DstReg)
4729     DstReg = MRI.createVirtualRegister(DstRC);
4730 
4731   unsigned EltSize = MRI.getType(EltReg).getSizeInBits();
4732   unsigned Opc = getInsertVecEltOpInfo(RB, EltSize).first;
4733 
4734   if (RB.getID() == AArch64::FPRRegBankID) {
4735     auto InsSub = emitScalarToVector(EltSize, DstRC, EltReg, MIRBuilder);
4736     InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
4737                  .addImm(LaneIdx)
4738                  .addUse(InsSub->getOperand(0).getReg())
4739                  .addImm(0);
4740   } else {
4741     InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
4742                  .addImm(LaneIdx)
4743                  .addUse(EltReg);
4744   }
4745 
4746   constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
4747   return InsElt;
4748 }
4749 
4750 bool AArch64InstructionSelector::selectInsertElt(
4751     MachineInstr &I, MachineRegisterInfo &MRI) const {
4752   assert(I.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT);
4753 
4754   // Get information on the destination.
4755   Register DstReg = I.getOperand(0).getReg();
4756   const LLT DstTy = MRI.getType(DstReg);
4757   unsigned VecSize = DstTy.getSizeInBits();
4758 
4759   // Get information on the element we want to insert into the destination.
4760   Register EltReg = I.getOperand(2).getReg();
4761   const LLT EltTy = MRI.getType(EltReg);
4762   unsigned EltSize = EltTy.getSizeInBits();
4763   if (EltSize < 16 || EltSize > 64)
4764     return false; // Don't support all element types yet.
4765 
4766   // Find the definition of the index. Bail out if it's not defined by a
4767   // G_CONSTANT.
4768   Register IdxReg = I.getOperand(3).getReg();
4769   auto VRegAndVal = getConstantVRegValWithLookThrough(IdxReg, MRI);
4770   if (!VRegAndVal)
4771     return false;
4772   unsigned LaneIdx = VRegAndVal->Value.getSExtValue();
4773 
4774   // Perform the lane insert.
4775   Register SrcReg = I.getOperand(1).getReg();
4776   const RegisterBank &EltRB = *RBI.getRegBank(EltReg, MRI, TRI);
4777   MachineIRBuilder MIRBuilder(I);
4778 
4779   if (VecSize < 128) {
4780     // If the vector we're inserting into is smaller than 128 bits, widen it
4781     // to 128 to do the insert.
4782     MachineInstr *ScalarToVec = emitScalarToVector(
4783         VecSize, &AArch64::FPR128RegClass, SrcReg, MIRBuilder);
4784     if (!ScalarToVec)
4785       return false;
4786     SrcReg = ScalarToVec->getOperand(0).getReg();
4787   }
4788 
4789   // Create an insert into a new FPR128 register.
4790   // Note that if our vector is already 128 bits, we end up emitting an extra
4791   // register.
4792   MachineInstr *InsMI =
4793       emitLaneInsert(None, SrcReg, EltReg, LaneIdx, EltRB, MIRBuilder);
4794 
4795   if (VecSize < 128) {
4796     // If we had to widen to perform the insert, then we have to demote back to
4797     // the original size to get the result we want.
4798     Register DemoteVec = InsMI->getOperand(0).getReg();
4799     const TargetRegisterClass *RC =
4800         getMinClassForRegBank(*RBI.getRegBank(DemoteVec, MRI, TRI), VecSize);
4801     if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
4802       LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
4803       return false;
4804     }
4805     unsigned SubReg = 0;
4806     if (!getSubRegForClass(RC, TRI, SubReg))
4807       return false;
4808     if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
4809       LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << VecSize
4810                         << "\n");
4811       return false;
4812     }
4813     MIRBuilder.buildInstr(TargetOpcode::COPY, {DstReg}, {})
4814         .addReg(DemoteVec, 0, SubReg);
4815     RBI.constrainGenericRegister(DstReg, *RC, MRI);
4816   } else {
4817     // No widening needed.
4818     InsMI->getOperand(0).setReg(DstReg);
4819     constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
4820   }
4821 
4822   I.eraseFromParent();
4823   return true;
4824 }
4825 
4826 MachineInstr *
4827 AArch64InstructionSelector::emitConstantVector(Register Dst, Constant *CV,
4828                                                MachineIRBuilder &MIRBuilder,
4829                                                MachineRegisterInfo &MRI) const {
4830   LLT DstTy = MRI.getType(Dst);
4831   unsigned DstSize = DstTy.getSizeInBits();
4832   if (CV->isNullValue()) {
4833     if (DstSize == 128) {
4834       auto Mov =
4835           MIRBuilder.buildInstr(AArch64::MOVIv2d_ns, {Dst}, {}).addImm(0);
4836       constrainSelectedInstRegOperands(*Mov, TII, TRI, RBI);
4837       return &*Mov;
4838     }
4839 
4840     if (DstSize == 64) {
4841       auto Mov =
4842           MIRBuilder
4843               .buildInstr(AArch64::MOVIv2d_ns, {&AArch64::FPR128RegClass}, {})
4844               .addImm(0);
4845       auto Copy = MIRBuilder.buildInstr(TargetOpcode::COPY, {Dst}, {})
4846                       .addReg(Mov.getReg(0), 0, AArch64::dsub);
4847       RBI.constrainGenericRegister(Dst, AArch64::FPR64RegClass, MRI);
4848       return &*Copy;
4849     }
4850   }
4851 
4852   auto *CPLoad = emitLoadFromConstantPool(CV, MIRBuilder);
4853   if (!CPLoad) {
4854     LLVM_DEBUG(dbgs() << "Could not generate cp load for constant vector!");
4855     return nullptr;
4856   }
4857 
4858   auto Copy = MIRBuilder.buildCopy(Dst, CPLoad->getOperand(0));
4859   RBI.constrainGenericRegister(
4860       Dst, *MRI.getRegClass(CPLoad->getOperand(0).getReg()), MRI);
4861   return &*Copy;
4862 }
4863 
4864 bool AArch64InstructionSelector::tryOptConstantBuildVec(
4865     MachineInstr &I, LLT DstTy, MachineRegisterInfo &MRI) const {
4866   assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4867   unsigned DstSize = DstTy.getSizeInBits();
4868   assert(DstSize <= 128 && "Unexpected build_vec type!");
4869   if (DstSize < 32)
4870     return false;
4871   // Check if we're building a constant vector, in which case we want to
4872   // generate a constant pool load instead of a vector insert sequence.
4873   SmallVector<Constant *, 16> Csts;
4874   for (unsigned Idx = 1; Idx < I.getNumOperands(); ++Idx) {
4875     // Try to find G_CONSTANT or G_FCONSTANT
4876     auto *OpMI =
4877         getOpcodeDef(TargetOpcode::G_CONSTANT, I.getOperand(Idx).getReg(), MRI);
4878     if (OpMI)
4879       Csts.emplace_back(
4880           const_cast<ConstantInt *>(OpMI->getOperand(1).getCImm()));
4881     else if ((OpMI = getOpcodeDef(TargetOpcode::G_FCONSTANT,
4882                                   I.getOperand(Idx).getReg(), MRI)))
4883       Csts.emplace_back(
4884           const_cast<ConstantFP *>(OpMI->getOperand(1).getFPImm()));
4885     else
4886       return false;
4887   }
4888   Constant *CV = ConstantVector::get(Csts);
4889   MachineIRBuilder MIB(I);
4890   if (!emitConstantVector(I.getOperand(0).getReg(), CV, MIB, MRI))
4891     return false;
4892   I.eraseFromParent();
4893   return true;
4894 }
4895 
4896 bool AArch64InstructionSelector::selectBuildVector(
4897     MachineInstr &I, MachineRegisterInfo &MRI) const {
4898   assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4899   // Until we port more of the optimized selections, for now just use a vector
4900   // insert sequence.
4901   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
4902   const LLT EltTy = MRI.getType(I.getOperand(1).getReg());
4903   unsigned EltSize = EltTy.getSizeInBits();
4904 
4905   if (tryOptConstantBuildVec(I, DstTy, MRI))
4906     return true;
4907   if (EltSize < 16 || EltSize > 64)
4908     return false; // Don't support all element types yet.
4909   const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
4910   MachineIRBuilder MIRBuilder(I);
4911 
4912   const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
4913   MachineInstr *ScalarToVec =
4914       emitScalarToVector(DstTy.getElementType().getSizeInBits(), DstRC,
4915                          I.getOperand(1).getReg(), MIRBuilder);
4916   if (!ScalarToVec)
4917     return false;
4918 
4919   Register DstVec = ScalarToVec->getOperand(0).getReg();
4920   unsigned DstSize = DstTy.getSizeInBits();
4921 
4922   // Keep track of the last MI we inserted. Later on, we might be able to save
4923   // a copy using it.
4924   MachineInstr *PrevMI = nullptr;
4925   for (unsigned i = 2, e = DstSize / EltSize + 1; i < e; ++i) {
4926     // Note that if we don't do a subregister copy, we can end up making an
4927     // extra register.
4928     PrevMI = &*emitLaneInsert(None, DstVec, I.getOperand(i).getReg(), i - 1, RB,
4929                               MIRBuilder);
4930     DstVec = PrevMI->getOperand(0).getReg();
4931   }
4932 
4933   // If DstTy's size in bits is less than 128, then emit a subregister copy
4934   // from DstVec to the last register we've defined.
4935   if (DstSize < 128) {
4936     // Force this to be FPR using the destination vector.
4937     const TargetRegisterClass *RC =
4938         getMinClassForRegBank(*RBI.getRegBank(DstVec, MRI, TRI), DstSize);
4939     if (!RC)
4940       return false;
4941     if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
4942       LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
4943       return false;
4944     }
4945 
4946     unsigned SubReg = 0;
4947     if (!getSubRegForClass(RC, TRI, SubReg))
4948       return false;
4949     if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
4950       LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << DstSize
4951                         << "\n");
4952       return false;
4953     }
4954 
4955     Register Reg = MRI.createVirtualRegister(RC);
4956     Register DstReg = I.getOperand(0).getReg();
4957 
4958     MIRBuilder.buildInstr(TargetOpcode::COPY, {DstReg}, {})
4959         .addReg(DstVec, 0, SubReg);
4960     MachineOperand &RegOp = I.getOperand(1);
4961     RegOp.setReg(Reg);
4962     RBI.constrainGenericRegister(DstReg, *RC, MRI);
4963   } else {
4964     // We don't need a subregister copy. Save a copy by re-using the
4965     // destination register on the final insert.
4966     assert(PrevMI && "PrevMI was null?");
4967     PrevMI->getOperand(0).setReg(I.getOperand(0).getReg());
4968     constrainSelectedInstRegOperands(*PrevMI, TII, TRI, RBI);
4969   }
4970 
4971   I.eraseFromParent();
4972   return true;
4973 }
4974 
4975 /// Helper function to find an intrinsic ID on an a MachineInstr. Returns the
4976 /// ID if it exists, and 0 otherwise.
4977 static unsigned findIntrinsicID(MachineInstr &I) {
4978   auto IntrinOp = find_if(I.operands(), [&](const MachineOperand &Op) {
4979     return Op.isIntrinsicID();
4980   });
4981   if (IntrinOp == I.operands_end())
4982     return 0;
4983   return IntrinOp->getIntrinsicID();
4984 }
4985 
4986 bool AArch64InstructionSelector::selectIntrinsicWithSideEffects(
4987     MachineInstr &I, MachineRegisterInfo &MRI) const {
4988   // Find the intrinsic ID.
4989   unsigned IntrinID = findIntrinsicID(I);
4990   if (!IntrinID)
4991     return false;
4992   MachineIRBuilder MIRBuilder(I);
4993 
4994   // Select the instruction.
4995   switch (IntrinID) {
4996   default:
4997     return false;
4998   case Intrinsic::trap:
4999     MIRBuilder.buildInstr(AArch64::BRK, {}, {}).addImm(1);
5000     break;
5001   case Intrinsic::debugtrap:
5002     MIRBuilder.buildInstr(AArch64::BRK, {}, {}).addImm(0xF000);
5003     break;
5004   case Intrinsic::ubsantrap:
5005     MIRBuilder.buildInstr(AArch64::BRK, {}, {})
5006         .addImm(I.getOperand(1).getImm() | ('U' << 8));
5007     break;
5008   }
5009 
5010   I.eraseFromParent();
5011   return true;
5012 }
5013 
5014 bool AArch64InstructionSelector::selectIntrinsic(MachineInstr &I,
5015                                                  MachineRegisterInfo &MRI) {
5016   unsigned IntrinID = findIntrinsicID(I);
5017   if (!IntrinID)
5018     return false;
5019   MachineIRBuilder MIRBuilder(I);
5020 
5021   switch (IntrinID) {
5022   default:
5023     break;
5024   case Intrinsic::aarch64_crypto_sha1h: {
5025     Register DstReg = I.getOperand(0).getReg();
5026     Register SrcReg = I.getOperand(2).getReg();
5027 
5028     // FIXME: Should this be an assert?
5029     if (MRI.getType(DstReg).getSizeInBits() != 32 ||
5030         MRI.getType(SrcReg).getSizeInBits() != 32)
5031       return false;
5032 
5033     // The operation has to happen on FPRs. Set up some new FPR registers for
5034     // the source and destination if they are on GPRs.
5035     if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
5036       SrcReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
5037       MIRBuilder.buildCopy({SrcReg}, {I.getOperand(2)});
5038 
5039       // Make sure the copy ends up getting constrained properly.
5040       RBI.constrainGenericRegister(I.getOperand(2).getReg(),
5041                                    AArch64::GPR32RegClass, MRI);
5042     }
5043 
5044     if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID)
5045       DstReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
5046 
5047     // Actually insert the instruction.
5048     auto SHA1Inst = MIRBuilder.buildInstr(AArch64::SHA1Hrr, {DstReg}, {SrcReg});
5049     constrainSelectedInstRegOperands(*SHA1Inst, TII, TRI, RBI);
5050 
5051     // Did we create a new register for the destination?
5052     if (DstReg != I.getOperand(0).getReg()) {
5053       // Yep. Copy the result of the instruction back into the original
5054       // destination.
5055       MIRBuilder.buildCopy({I.getOperand(0)}, {DstReg});
5056       RBI.constrainGenericRegister(I.getOperand(0).getReg(),
5057                                    AArch64::GPR32RegClass, MRI);
5058     }
5059 
5060     I.eraseFromParent();
5061     return true;
5062   }
5063   case Intrinsic::frameaddress:
5064   case Intrinsic::returnaddress: {
5065     MachineFunction &MF = *I.getParent()->getParent();
5066     MachineFrameInfo &MFI = MF.getFrameInfo();
5067 
5068     unsigned Depth = I.getOperand(2).getImm();
5069     Register DstReg = I.getOperand(0).getReg();
5070     RBI.constrainGenericRegister(DstReg, AArch64::GPR64RegClass, MRI);
5071 
5072     if (Depth == 0 && IntrinID == Intrinsic::returnaddress) {
5073       if (!MFReturnAddr) {
5074         // Insert the copy from LR/X30 into the entry block, before it can be
5075         // clobbered by anything.
5076         MFI.setReturnAddressIsTaken(true);
5077         MFReturnAddr = getFunctionLiveInPhysReg(MF, TII, AArch64::LR,
5078                                                 AArch64::GPR64RegClass);
5079       }
5080 
5081       if (STI.hasPAuth()) {
5082         MIRBuilder.buildInstr(AArch64::XPACI, {DstReg}, {MFReturnAddr});
5083       } else {
5084         MIRBuilder.buildCopy({Register(AArch64::LR)}, {MFReturnAddr});
5085         MIRBuilder.buildInstr(AArch64::XPACLRI);
5086         MIRBuilder.buildCopy({DstReg}, {Register(AArch64::LR)});
5087       }
5088 
5089       I.eraseFromParent();
5090       return true;
5091     }
5092 
5093     MFI.setFrameAddressIsTaken(true);
5094     Register FrameAddr(AArch64::FP);
5095     while (Depth--) {
5096       Register NextFrame = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
5097       auto Ldr =
5098           MIRBuilder.buildInstr(AArch64::LDRXui, {NextFrame}, {FrameAddr})
5099               .addImm(0);
5100       constrainSelectedInstRegOperands(*Ldr, TII, TRI, RBI);
5101       FrameAddr = NextFrame;
5102     }
5103 
5104     if (IntrinID == Intrinsic::frameaddress)
5105       MIRBuilder.buildCopy({DstReg}, {FrameAddr});
5106     else {
5107       MFI.setReturnAddressIsTaken(true);
5108 
5109       if (STI.hasPAuth()) {
5110         Register TmpReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
5111         MIRBuilder.buildInstr(AArch64::LDRXui, {TmpReg}, {FrameAddr}).addImm(1);
5112         MIRBuilder.buildInstr(AArch64::XPACI, {DstReg}, {TmpReg});
5113       } else {
5114         MIRBuilder.buildInstr(AArch64::LDRXui, {Register(AArch64::LR)}, {FrameAddr}).addImm(1);
5115         MIRBuilder.buildInstr(AArch64::XPACLRI);
5116         MIRBuilder.buildCopy({DstReg}, {Register(AArch64::LR)});
5117       }
5118     }
5119 
5120     I.eraseFromParent();
5121     return true;
5122   }
5123   }
5124   return false;
5125 }
5126 
5127 InstructionSelector::ComplexRendererFns
5128 AArch64InstructionSelector::selectShiftA_32(const MachineOperand &Root) const {
5129   auto MaybeImmed = getImmedFromMO(Root);
5130   if (MaybeImmed == None || *MaybeImmed > 31)
5131     return None;
5132   uint64_t Enc = (32 - *MaybeImmed) & 0x1f;
5133   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
5134 }
5135 
5136 InstructionSelector::ComplexRendererFns
5137 AArch64InstructionSelector::selectShiftB_32(const MachineOperand &Root) const {
5138   auto MaybeImmed = getImmedFromMO(Root);
5139   if (MaybeImmed == None || *MaybeImmed > 31)
5140     return None;
5141   uint64_t Enc = 31 - *MaybeImmed;
5142   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
5143 }
5144 
5145 InstructionSelector::ComplexRendererFns
5146 AArch64InstructionSelector::selectShiftA_64(const MachineOperand &Root) const {
5147   auto MaybeImmed = getImmedFromMO(Root);
5148   if (MaybeImmed == None || *MaybeImmed > 63)
5149     return None;
5150   uint64_t Enc = (64 - *MaybeImmed) & 0x3f;
5151   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
5152 }
5153 
5154 InstructionSelector::ComplexRendererFns
5155 AArch64InstructionSelector::selectShiftB_64(const MachineOperand &Root) const {
5156   auto MaybeImmed = getImmedFromMO(Root);
5157   if (MaybeImmed == None || *MaybeImmed > 63)
5158     return None;
5159   uint64_t Enc = 63 - *MaybeImmed;
5160   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
5161 }
5162 
5163 /// Helper to select an immediate value that can be represented as a 12-bit
5164 /// value shifted left by either 0 or 12. If it is possible to do so, return
5165 /// the immediate and shift value. If not, return None.
5166 ///
5167 /// Used by selectArithImmed and selectNegArithImmed.
5168 InstructionSelector::ComplexRendererFns
5169 AArch64InstructionSelector::select12BitValueWithLeftShift(
5170     uint64_t Immed) const {
5171   unsigned ShiftAmt;
5172   if (Immed >> 12 == 0) {
5173     ShiftAmt = 0;
5174   } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
5175     ShiftAmt = 12;
5176     Immed = Immed >> 12;
5177   } else
5178     return None;
5179 
5180   unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
5181   return {{
5182       [=](MachineInstrBuilder &MIB) { MIB.addImm(Immed); },
5183       [=](MachineInstrBuilder &MIB) { MIB.addImm(ShVal); },
5184   }};
5185 }
5186 
5187 /// SelectArithImmed - Select an immediate value that can be represented as
5188 /// a 12-bit value shifted left by either 0 or 12.  If so, return true with
5189 /// Val set to the 12-bit value and Shift set to the shifter operand.
5190 InstructionSelector::ComplexRendererFns
5191 AArch64InstructionSelector::selectArithImmed(MachineOperand &Root) const {
5192   // This function is called from the addsub_shifted_imm ComplexPattern,
5193   // which lists [imm] as the list of opcode it's interested in, however
5194   // we still need to check whether the operand is actually an immediate
5195   // here because the ComplexPattern opcode list is only used in
5196   // root-level opcode matching.
5197   auto MaybeImmed = getImmedFromMO(Root);
5198   if (MaybeImmed == None)
5199     return None;
5200   return select12BitValueWithLeftShift(*MaybeImmed);
5201 }
5202 
5203 /// SelectNegArithImmed - As above, but negates the value before trying to
5204 /// select it.
5205 InstructionSelector::ComplexRendererFns
5206 AArch64InstructionSelector::selectNegArithImmed(MachineOperand &Root) const {
5207   // We need a register here, because we need to know if we have a 64 or 32
5208   // bit immediate.
5209   if (!Root.isReg())
5210     return None;
5211   auto MaybeImmed = getImmedFromMO(Root);
5212   if (MaybeImmed == None)
5213     return None;
5214   uint64_t Immed = *MaybeImmed;
5215 
5216   // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
5217   // have the opposite effect on the C flag, so this pattern mustn't match under
5218   // those circumstances.
5219   if (Immed == 0)
5220     return None;
5221 
5222   // Check if we're dealing with a 32-bit type on the root or a 64-bit type on
5223   // the root.
5224   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5225   if (MRI.getType(Root.getReg()).getSizeInBits() == 32)
5226     Immed = ~((uint32_t)Immed) + 1;
5227   else
5228     Immed = ~Immed + 1ULL;
5229 
5230   if (Immed & 0xFFFFFFFFFF000000ULL)
5231     return None;
5232 
5233   Immed &= 0xFFFFFFULL;
5234   return select12BitValueWithLeftShift(Immed);
5235 }
5236 
5237 /// Return true if it is worth folding MI into an extended register. That is,
5238 /// if it's safe to pull it into the addressing mode of a load or store as a
5239 /// shift.
5240 bool AArch64InstructionSelector::isWorthFoldingIntoExtendedReg(
5241     MachineInstr &MI, const MachineRegisterInfo &MRI) const {
5242   // Always fold if there is one use, or if we're optimizing for size.
5243   Register DefReg = MI.getOperand(0).getReg();
5244   if (MRI.hasOneNonDBGUse(DefReg) ||
5245       MI.getParent()->getParent()->getFunction().hasOptSize())
5246     return true;
5247 
5248   // It's better to avoid folding and recomputing shifts when we don't have a
5249   // fastpath.
5250   if (!STI.hasLSLFast())
5251     return false;
5252 
5253   // We have a fastpath, so folding a shift in and potentially computing it
5254   // many times may be beneficial. Check if this is only used in memory ops.
5255   // If it is, then we should fold.
5256   return all_of(MRI.use_nodbg_instructions(DefReg),
5257                 [](MachineInstr &Use) { return Use.mayLoadOrStore(); });
5258 }
5259 
5260 static bool isSignExtendShiftType(AArch64_AM::ShiftExtendType Type) {
5261   switch (Type) {
5262   case AArch64_AM::SXTB:
5263   case AArch64_AM::SXTH:
5264   case AArch64_AM::SXTW:
5265     return true;
5266   default:
5267     return false;
5268   }
5269 }
5270 
5271 InstructionSelector::ComplexRendererFns
5272 AArch64InstructionSelector::selectExtendedSHL(
5273     MachineOperand &Root, MachineOperand &Base, MachineOperand &Offset,
5274     unsigned SizeInBytes, bool WantsExt) const {
5275   assert(Base.isReg() && "Expected base to be a register operand");
5276   assert(Offset.isReg() && "Expected offset to be a register operand");
5277 
5278   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5279   MachineInstr *OffsetInst = MRI.getVRegDef(Offset.getReg());
5280   if (!OffsetInst)
5281     return None;
5282 
5283   unsigned OffsetOpc = OffsetInst->getOpcode();
5284   bool LookedThroughZExt = false;
5285   if (OffsetOpc != TargetOpcode::G_SHL && OffsetOpc != TargetOpcode::G_MUL) {
5286     // Try to look through a ZEXT.
5287     if (OffsetOpc != TargetOpcode::G_ZEXT || !WantsExt)
5288       return None;
5289 
5290     OffsetInst = MRI.getVRegDef(OffsetInst->getOperand(1).getReg());
5291     OffsetOpc = OffsetInst->getOpcode();
5292     LookedThroughZExt = true;
5293 
5294     if (OffsetOpc != TargetOpcode::G_SHL && OffsetOpc != TargetOpcode::G_MUL)
5295       return None;
5296   }
5297   // Make sure that the memory op is a valid size.
5298   int64_t LegalShiftVal = Log2_32(SizeInBytes);
5299   if (LegalShiftVal == 0)
5300     return None;
5301   if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
5302     return None;
5303 
5304   // Now, try to find the specific G_CONSTANT. Start by assuming that the
5305   // register we will offset is the LHS, and the register containing the
5306   // constant is the RHS.
5307   Register OffsetReg = OffsetInst->getOperand(1).getReg();
5308   Register ConstantReg = OffsetInst->getOperand(2).getReg();
5309   auto ValAndVReg = getConstantVRegValWithLookThrough(ConstantReg, MRI);
5310   if (!ValAndVReg) {
5311     // We didn't get a constant on the RHS. If the opcode is a shift, then
5312     // we're done.
5313     if (OffsetOpc == TargetOpcode::G_SHL)
5314       return None;
5315 
5316     // If we have a G_MUL, we can use either register. Try looking at the RHS.
5317     std::swap(OffsetReg, ConstantReg);
5318     ValAndVReg = getConstantVRegValWithLookThrough(ConstantReg, MRI);
5319     if (!ValAndVReg)
5320       return None;
5321   }
5322 
5323   // The value must fit into 3 bits, and must be positive. Make sure that is
5324   // true.
5325   int64_t ImmVal = ValAndVReg->Value.getSExtValue();
5326 
5327   // Since we're going to pull this into a shift, the constant value must be
5328   // a power of 2. If we got a multiply, then we need to check this.
5329   if (OffsetOpc == TargetOpcode::G_MUL) {
5330     if (!isPowerOf2_32(ImmVal))
5331       return None;
5332 
5333     // Got a power of 2. So, the amount we'll shift is the log base-2 of that.
5334     ImmVal = Log2_32(ImmVal);
5335   }
5336 
5337   if ((ImmVal & 0x7) != ImmVal)
5338     return None;
5339 
5340   // We are only allowed to shift by LegalShiftVal. This shift value is built
5341   // into the instruction, so we can't just use whatever we want.
5342   if (ImmVal != LegalShiftVal)
5343     return None;
5344 
5345   unsigned SignExtend = 0;
5346   if (WantsExt) {
5347     // Check if the offset is defined by an extend, unless we looked through a
5348     // G_ZEXT earlier.
5349     if (!LookedThroughZExt) {
5350       MachineInstr *ExtInst = getDefIgnoringCopies(OffsetReg, MRI);
5351       auto Ext = getExtendTypeForInst(*ExtInst, MRI, true);
5352       if (Ext == AArch64_AM::InvalidShiftExtend)
5353         return None;
5354 
5355       SignExtend = isSignExtendShiftType(Ext) ? 1 : 0;
5356       // We only support SXTW for signed extension here.
5357       if (SignExtend && Ext != AArch64_AM::SXTW)
5358         return None;
5359       OffsetReg = ExtInst->getOperand(1).getReg();
5360     }
5361 
5362     // Need a 32-bit wide register here.
5363     MachineIRBuilder MIB(*MRI.getVRegDef(Root.getReg()));
5364     OffsetReg = moveScalarRegClass(OffsetReg, AArch64::GPR32RegClass, MIB);
5365   }
5366 
5367   // We can use the LHS of the GEP as the base, and the LHS of the shift as an
5368   // offset. Signify that we are shifting by setting the shift flag to 1.
5369   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(Base.getReg()); },
5370            [=](MachineInstrBuilder &MIB) { MIB.addUse(OffsetReg); },
5371            [=](MachineInstrBuilder &MIB) {
5372              // Need to add both immediates here to make sure that they are both
5373              // added to the instruction.
5374              MIB.addImm(SignExtend);
5375              MIB.addImm(1);
5376            }}};
5377 }
5378 
5379 /// This is used for computing addresses like this:
5380 ///
5381 /// ldr x1, [x2, x3, lsl #3]
5382 ///
5383 /// Where x2 is the base register, and x3 is an offset register. The shift-left
5384 /// is a constant value specific to this load instruction. That is, we'll never
5385 /// see anything other than a 3 here (which corresponds to the size of the
5386 /// element being loaded.)
5387 InstructionSelector::ComplexRendererFns
5388 AArch64InstructionSelector::selectAddrModeShiftedExtendXReg(
5389     MachineOperand &Root, unsigned SizeInBytes) const {
5390   if (!Root.isReg())
5391     return None;
5392   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5393 
5394   // We want to find something like this:
5395   //
5396   // val = G_CONSTANT LegalShiftVal
5397   // shift = G_SHL off_reg val
5398   // ptr = G_PTR_ADD base_reg shift
5399   // x = G_LOAD ptr
5400   //
5401   // And fold it into this addressing mode:
5402   //
5403   // ldr x, [base_reg, off_reg, lsl #LegalShiftVal]
5404 
5405   // Check if we can find the G_PTR_ADD.
5406   MachineInstr *PtrAdd =
5407       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5408   if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
5409     return None;
5410 
5411   // Now, try to match an opcode which will match our specific offset.
5412   // We want a G_SHL or a G_MUL.
5413   MachineInstr *OffsetInst =
5414       getDefIgnoringCopies(PtrAdd->getOperand(2).getReg(), MRI);
5415   return selectExtendedSHL(Root, PtrAdd->getOperand(1),
5416                            OffsetInst->getOperand(0), SizeInBytes,
5417                            /*WantsExt=*/false);
5418 }
5419 
5420 /// This is used for computing addresses like this:
5421 ///
5422 /// ldr x1, [x2, x3]
5423 ///
5424 /// Where x2 is the base register, and x3 is an offset register.
5425 ///
5426 /// When possible (or profitable) to fold a G_PTR_ADD into the address calculation,
5427 /// this will do so. Otherwise, it will return None.
5428 InstructionSelector::ComplexRendererFns
5429 AArch64InstructionSelector::selectAddrModeRegisterOffset(
5430     MachineOperand &Root) const {
5431   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5432 
5433   // We need a GEP.
5434   MachineInstr *Gep = MRI.getVRegDef(Root.getReg());
5435   if (!Gep || Gep->getOpcode() != TargetOpcode::G_PTR_ADD)
5436     return None;
5437 
5438   // If this is used more than once, let's not bother folding.
5439   // TODO: Check if they are memory ops. If they are, then we can still fold
5440   // without having to recompute anything.
5441   if (!MRI.hasOneNonDBGUse(Gep->getOperand(0).getReg()))
5442     return None;
5443 
5444   // Base is the GEP's LHS, offset is its RHS.
5445   return {{[=](MachineInstrBuilder &MIB) {
5446              MIB.addUse(Gep->getOperand(1).getReg());
5447            },
5448            [=](MachineInstrBuilder &MIB) {
5449              MIB.addUse(Gep->getOperand(2).getReg());
5450            },
5451            [=](MachineInstrBuilder &MIB) {
5452              // Need to add both immediates here to make sure that they are both
5453              // added to the instruction.
5454              MIB.addImm(0);
5455              MIB.addImm(0);
5456            }}};
5457 }
5458 
5459 /// This is intended to be equivalent to selectAddrModeXRO in
5460 /// AArch64ISelDAGtoDAG. It's used for selecting X register offset loads.
5461 InstructionSelector::ComplexRendererFns
5462 AArch64InstructionSelector::selectAddrModeXRO(MachineOperand &Root,
5463                                               unsigned SizeInBytes) const {
5464   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5465   if (!Root.isReg())
5466     return None;
5467   MachineInstr *PtrAdd =
5468       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5469   if (!PtrAdd)
5470     return None;
5471 
5472   // Check for an immediates which cannot be encoded in the [base + imm]
5473   // addressing mode, and can't be encoded in an add/sub. If this happens, we'll
5474   // end up with code like:
5475   //
5476   // mov x0, wide
5477   // add x1 base, x0
5478   // ldr x2, [x1, x0]
5479   //
5480   // In this situation, we can use the [base, xreg] addressing mode to save an
5481   // add/sub:
5482   //
5483   // mov x0, wide
5484   // ldr x2, [base, x0]
5485   auto ValAndVReg =
5486       getConstantVRegValWithLookThrough(PtrAdd->getOperand(2).getReg(), MRI);
5487   if (ValAndVReg) {
5488     unsigned Scale = Log2_32(SizeInBytes);
5489     int64_t ImmOff = ValAndVReg->Value.getSExtValue();
5490 
5491     // Skip immediates that can be selected in the load/store addresing
5492     // mode.
5493     if (ImmOff % SizeInBytes == 0 && ImmOff >= 0 &&
5494         ImmOff < (0x1000 << Scale))
5495       return None;
5496 
5497     // Helper lambda to decide whether or not it is preferable to emit an add.
5498     auto isPreferredADD = [](int64_t ImmOff) {
5499       // Constants in [0x0, 0xfff] can be encoded in an add.
5500       if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
5501         return true;
5502 
5503       // Can it be encoded in an add lsl #12?
5504       if ((ImmOff & 0xffffffffff000fffLL) != 0x0LL)
5505         return false;
5506 
5507       // It can be encoded in an add lsl #12, but we may not want to. If it is
5508       // possible to select this as a single movz, then prefer that. A single
5509       // movz is faster than an add with a shift.
5510       return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
5511              (ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
5512     };
5513 
5514     // If the immediate can be encoded in a single add/sub, then bail out.
5515     if (isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
5516       return None;
5517   }
5518 
5519   // Try to fold shifts into the addressing mode.
5520   auto AddrModeFns = selectAddrModeShiftedExtendXReg(Root, SizeInBytes);
5521   if (AddrModeFns)
5522     return AddrModeFns;
5523 
5524   // If that doesn't work, see if it's possible to fold in registers from
5525   // a GEP.
5526   return selectAddrModeRegisterOffset(Root);
5527 }
5528 
5529 /// This is used for computing addresses like this:
5530 ///
5531 /// ldr x0, [xBase, wOffset, sxtw #LegalShiftVal]
5532 ///
5533 /// Where we have a 64-bit base register, a 32-bit offset register, and an
5534 /// extend (which may or may not be signed).
5535 InstructionSelector::ComplexRendererFns
5536 AArch64InstructionSelector::selectAddrModeWRO(MachineOperand &Root,
5537                                               unsigned SizeInBytes) const {
5538   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5539 
5540   MachineInstr *PtrAdd =
5541       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5542   if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
5543     return None;
5544 
5545   MachineOperand &LHS = PtrAdd->getOperand(1);
5546   MachineOperand &RHS = PtrAdd->getOperand(2);
5547   MachineInstr *OffsetInst = getDefIgnoringCopies(RHS.getReg(), MRI);
5548 
5549   // The first case is the same as selectAddrModeXRO, except we need an extend.
5550   // In this case, we try to find a shift and extend, and fold them into the
5551   // addressing mode.
5552   //
5553   // E.g.
5554   //
5555   // off_reg = G_Z/S/ANYEXT ext_reg
5556   // val = G_CONSTANT LegalShiftVal
5557   // shift = G_SHL off_reg val
5558   // ptr = G_PTR_ADD base_reg shift
5559   // x = G_LOAD ptr
5560   //
5561   // In this case we can get a load like this:
5562   //
5563   // ldr x0, [base_reg, ext_reg, sxtw #LegalShiftVal]
5564   auto ExtendedShl = selectExtendedSHL(Root, LHS, OffsetInst->getOperand(0),
5565                                        SizeInBytes, /*WantsExt=*/true);
5566   if (ExtendedShl)
5567     return ExtendedShl;
5568 
5569   // There was no shift. We can try and fold a G_Z/S/ANYEXT in alone though.
5570   //
5571   // e.g.
5572   // ldr something, [base_reg, ext_reg, sxtw]
5573   if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
5574     return None;
5575 
5576   // Check if this is an extend. We'll get an extend type if it is.
5577   AArch64_AM::ShiftExtendType Ext =
5578       getExtendTypeForInst(*OffsetInst, MRI, /*IsLoadStore=*/true);
5579   if (Ext == AArch64_AM::InvalidShiftExtend)
5580     return None;
5581 
5582   // Need a 32-bit wide register.
5583   MachineIRBuilder MIB(*PtrAdd);
5584   Register ExtReg = moveScalarRegClass(OffsetInst->getOperand(1).getReg(),
5585                                        AArch64::GPR32RegClass, MIB);
5586   unsigned SignExtend = Ext == AArch64_AM::SXTW;
5587 
5588   // Base is LHS, offset is ExtReg.
5589   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(LHS.getReg()); },
5590            [=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
5591            [=](MachineInstrBuilder &MIB) {
5592              MIB.addImm(SignExtend);
5593              MIB.addImm(0);
5594            }}};
5595 }
5596 
5597 /// Select a "register plus unscaled signed 9-bit immediate" address.  This
5598 /// should only match when there is an offset that is not valid for a scaled
5599 /// immediate addressing mode.  The "Size" argument is the size in bytes of the
5600 /// memory reference, which is needed here to know what is valid for a scaled
5601 /// immediate.
5602 InstructionSelector::ComplexRendererFns
5603 AArch64InstructionSelector::selectAddrModeUnscaled(MachineOperand &Root,
5604                                                    unsigned Size) const {
5605   MachineRegisterInfo &MRI =
5606       Root.getParent()->getParent()->getParent()->getRegInfo();
5607 
5608   if (!Root.isReg())
5609     return None;
5610 
5611   if (!isBaseWithConstantOffset(Root, MRI))
5612     return None;
5613 
5614   MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
5615   if (!RootDef)
5616     return None;
5617 
5618   MachineOperand &OffImm = RootDef->getOperand(2);
5619   if (!OffImm.isReg())
5620     return None;
5621   MachineInstr *RHS = MRI.getVRegDef(OffImm.getReg());
5622   if (!RHS || RHS->getOpcode() != TargetOpcode::G_CONSTANT)
5623     return None;
5624   int64_t RHSC;
5625   MachineOperand &RHSOp1 = RHS->getOperand(1);
5626   if (!RHSOp1.isCImm() || RHSOp1.getCImm()->getBitWidth() > 64)
5627     return None;
5628   RHSC = RHSOp1.getCImm()->getSExtValue();
5629 
5630   // If the offset is valid as a scaled immediate, don't match here.
5631   if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Log2_32(Size)))
5632     return None;
5633   if (RHSC >= -256 && RHSC < 256) {
5634     MachineOperand &Base = RootDef->getOperand(1);
5635     return {{
5636         [=](MachineInstrBuilder &MIB) { MIB.add(Base); },
5637         [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); },
5638     }};
5639   }
5640   return None;
5641 }
5642 
5643 InstructionSelector::ComplexRendererFns
5644 AArch64InstructionSelector::tryFoldAddLowIntoImm(MachineInstr &RootDef,
5645                                                  unsigned Size,
5646                                                  MachineRegisterInfo &MRI) const {
5647   if (RootDef.getOpcode() != AArch64::G_ADD_LOW)
5648     return None;
5649   MachineInstr &Adrp = *MRI.getVRegDef(RootDef.getOperand(1).getReg());
5650   if (Adrp.getOpcode() != AArch64::ADRP)
5651     return None;
5652 
5653   // TODO: add heuristics like isWorthFoldingADDlow() from SelectionDAG.
5654   auto Offset = Adrp.getOperand(1).getOffset();
5655   if (Offset % Size != 0)
5656     return None;
5657 
5658   auto GV = Adrp.getOperand(1).getGlobal();
5659   if (GV->isThreadLocal())
5660     return None;
5661 
5662   auto &MF = *RootDef.getParent()->getParent();
5663   if (GV->getPointerAlignment(MF.getDataLayout()) < Size)
5664     return None;
5665 
5666   unsigned OpFlags = STI.ClassifyGlobalReference(GV, MF.getTarget());
5667   MachineIRBuilder MIRBuilder(RootDef);
5668   Register AdrpReg = Adrp.getOperand(0).getReg();
5669   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(AdrpReg); },
5670            [=](MachineInstrBuilder &MIB) {
5671              MIB.addGlobalAddress(GV, Offset,
5672                                   OpFlags | AArch64II::MO_PAGEOFF |
5673                                       AArch64II::MO_NC);
5674            }}};
5675 }
5676 
5677 /// Select a "register plus scaled unsigned 12-bit immediate" address.  The
5678 /// "Size" argument is the size in bytes of the memory reference, which
5679 /// determines the scale.
5680 InstructionSelector::ComplexRendererFns
5681 AArch64InstructionSelector::selectAddrModeIndexed(MachineOperand &Root,
5682                                                   unsigned Size) const {
5683   MachineFunction &MF = *Root.getParent()->getParent()->getParent();
5684   MachineRegisterInfo &MRI = MF.getRegInfo();
5685 
5686   if (!Root.isReg())
5687     return None;
5688 
5689   MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
5690   if (!RootDef)
5691     return None;
5692 
5693   if (RootDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
5694     return {{
5695         [=](MachineInstrBuilder &MIB) { MIB.add(RootDef->getOperand(1)); },
5696         [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
5697     }};
5698   }
5699 
5700   CodeModel::Model CM = MF.getTarget().getCodeModel();
5701   // Check if we can fold in the ADD of small code model ADRP + ADD address.
5702   if (CM == CodeModel::Small) {
5703     auto OpFns = tryFoldAddLowIntoImm(*RootDef, Size, MRI);
5704     if (OpFns)
5705       return OpFns;
5706   }
5707 
5708   if (isBaseWithConstantOffset(Root, MRI)) {
5709     MachineOperand &LHS = RootDef->getOperand(1);
5710     MachineOperand &RHS = RootDef->getOperand(2);
5711     MachineInstr *LHSDef = MRI.getVRegDef(LHS.getReg());
5712     MachineInstr *RHSDef = MRI.getVRegDef(RHS.getReg());
5713     if (LHSDef && RHSDef) {
5714       int64_t RHSC = (int64_t)RHSDef->getOperand(1).getCImm()->getZExtValue();
5715       unsigned Scale = Log2_32(Size);
5716       if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
5717         if (LHSDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
5718           return {{
5719               [=](MachineInstrBuilder &MIB) { MIB.add(LHSDef->getOperand(1)); },
5720               [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
5721           }};
5722 
5723         return {{
5724             [=](MachineInstrBuilder &MIB) { MIB.add(LHS); },
5725             [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
5726         }};
5727       }
5728     }
5729   }
5730 
5731   // Before falling back to our general case, check if the unscaled
5732   // instructions can handle this. If so, that's preferable.
5733   if (selectAddrModeUnscaled(Root, Size).hasValue())
5734     return None;
5735 
5736   return {{
5737       [=](MachineInstrBuilder &MIB) { MIB.add(Root); },
5738       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
5739   }};
5740 }
5741 
5742 /// Given a shift instruction, return the correct shift type for that
5743 /// instruction.
5744 static AArch64_AM::ShiftExtendType getShiftTypeForInst(MachineInstr &MI) {
5745   // TODO: Handle AArch64_AM::ROR
5746   switch (MI.getOpcode()) {
5747   default:
5748     return AArch64_AM::InvalidShiftExtend;
5749   case TargetOpcode::G_SHL:
5750     return AArch64_AM::LSL;
5751   case TargetOpcode::G_LSHR:
5752     return AArch64_AM::LSR;
5753   case TargetOpcode::G_ASHR:
5754     return AArch64_AM::ASR;
5755   }
5756 }
5757 
5758 /// Select a "shifted register" operand. If the value is not shifted, set the
5759 /// shift operand to a default value of "lsl 0".
5760 ///
5761 /// TODO: Allow shifted register to be rotated in logical instructions.
5762 InstructionSelector::ComplexRendererFns
5763 AArch64InstructionSelector::selectShiftedRegister(MachineOperand &Root) const {
5764   if (!Root.isReg())
5765     return None;
5766   MachineRegisterInfo &MRI =
5767       Root.getParent()->getParent()->getParent()->getRegInfo();
5768 
5769   // Check if the operand is defined by an instruction which corresponds to
5770   // a ShiftExtendType. E.g. a G_SHL, G_LSHR, etc.
5771   //
5772   // TODO: Handle AArch64_AM::ROR for logical instructions.
5773   MachineInstr *ShiftInst = MRI.getVRegDef(Root.getReg());
5774   if (!ShiftInst)
5775     return None;
5776   AArch64_AM::ShiftExtendType ShType = getShiftTypeForInst(*ShiftInst);
5777   if (ShType == AArch64_AM::InvalidShiftExtend)
5778     return None;
5779   if (!isWorthFoldingIntoExtendedReg(*ShiftInst, MRI))
5780     return None;
5781 
5782   // Need an immediate on the RHS.
5783   MachineOperand &ShiftRHS = ShiftInst->getOperand(2);
5784   auto Immed = getImmedFromMO(ShiftRHS);
5785   if (!Immed)
5786     return None;
5787 
5788   // We have something that we can fold. Fold in the shift's LHS and RHS into
5789   // the instruction.
5790   MachineOperand &ShiftLHS = ShiftInst->getOperand(1);
5791   Register ShiftReg = ShiftLHS.getReg();
5792 
5793   unsigned NumBits = MRI.getType(ShiftReg).getSizeInBits();
5794   unsigned Val = *Immed & (NumBits - 1);
5795   unsigned ShiftVal = AArch64_AM::getShifterImm(ShType, Val);
5796 
5797   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ShiftReg); },
5798            [=](MachineInstrBuilder &MIB) { MIB.addImm(ShiftVal); }}};
5799 }
5800 
5801 AArch64_AM::ShiftExtendType AArch64InstructionSelector::getExtendTypeForInst(
5802     MachineInstr &MI, MachineRegisterInfo &MRI, bool IsLoadStore) const {
5803   unsigned Opc = MI.getOpcode();
5804 
5805   // Handle explicit extend instructions first.
5806   if (Opc == TargetOpcode::G_SEXT || Opc == TargetOpcode::G_SEXT_INREG) {
5807     unsigned Size;
5808     if (Opc == TargetOpcode::G_SEXT)
5809       Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
5810     else
5811       Size = MI.getOperand(2).getImm();
5812     assert(Size != 64 && "Extend from 64 bits?");
5813     switch (Size) {
5814     case 8:
5815       return AArch64_AM::SXTB;
5816     case 16:
5817       return AArch64_AM::SXTH;
5818     case 32:
5819       return AArch64_AM::SXTW;
5820     default:
5821       return AArch64_AM::InvalidShiftExtend;
5822     }
5823   }
5824 
5825   if (Opc == TargetOpcode::G_ZEXT || Opc == TargetOpcode::G_ANYEXT) {
5826     unsigned Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
5827     assert(Size != 64 && "Extend from 64 bits?");
5828     switch (Size) {
5829     case 8:
5830       return AArch64_AM::UXTB;
5831     case 16:
5832       return AArch64_AM::UXTH;
5833     case 32:
5834       return AArch64_AM::UXTW;
5835     default:
5836       return AArch64_AM::InvalidShiftExtend;
5837     }
5838   }
5839 
5840   // Don't have an explicit extend. Try to handle a G_AND with a constant mask
5841   // on the RHS.
5842   if (Opc != TargetOpcode::G_AND)
5843     return AArch64_AM::InvalidShiftExtend;
5844 
5845   Optional<uint64_t> MaybeAndMask = getImmedFromMO(MI.getOperand(2));
5846   if (!MaybeAndMask)
5847     return AArch64_AM::InvalidShiftExtend;
5848   uint64_t AndMask = *MaybeAndMask;
5849   switch (AndMask) {
5850   default:
5851     return AArch64_AM::InvalidShiftExtend;
5852   case 0xFF:
5853     return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
5854   case 0xFFFF:
5855     return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
5856   case 0xFFFFFFFF:
5857     return AArch64_AM::UXTW;
5858   }
5859 }
5860 
5861 Register AArch64InstructionSelector::moveScalarRegClass(
5862     Register Reg, const TargetRegisterClass &RC, MachineIRBuilder &MIB) const {
5863   MachineRegisterInfo &MRI = *MIB.getMRI();
5864   auto Ty = MRI.getType(Reg);
5865   assert(!Ty.isVector() && "Expected scalars only!");
5866   if (Ty.getSizeInBits() == TRI.getRegSizeInBits(RC))
5867     return Reg;
5868 
5869   // Create a copy and immediately select it.
5870   // FIXME: We should have an emitCopy function?
5871   auto Copy = MIB.buildCopy({&RC}, {Reg});
5872   selectCopy(*Copy, TII, MRI, TRI, RBI);
5873   return Copy.getReg(0);
5874 }
5875 
5876 /// Select an "extended register" operand. This operand folds in an extend
5877 /// followed by an optional left shift.
5878 InstructionSelector::ComplexRendererFns
5879 AArch64InstructionSelector::selectArithExtendedRegister(
5880     MachineOperand &Root) const {
5881   if (!Root.isReg())
5882     return None;
5883   MachineRegisterInfo &MRI =
5884       Root.getParent()->getParent()->getParent()->getRegInfo();
5885 
5886   uint64_t ShiftVal = 0;
5887   Register ExtReg;
5888   AArch64_AM::ShiftExtendType Ext;
5889   MachineInstr *RootDef = getDefIgnoringCopies(Root.getReg(), MRI);
5890   if (!RootDef)
5891     return None;
5892 
5893   if (!isWorthFoldingIntoExtendedReg(*RootDef, MRI))
5894     return None;
5895 
5896   // Check if we can fold a shift and an extend.
5897   if (RootDef->getOpcode() == TargetOpcode::G_SHL) {
5898     // Look for a constant on the RHS of the shift.
5899     MachineOperand &RHS = RootDef->getOperand(2);
5900     Optional<uint64_t> MaybeShiftVal = getImmedFromMO(RHS);
5901     if (!MaybeShiftVal)
5902       return None;
5903     ShiftVal = *MaybeShiftVal;
5904     if (ShiftVal > 4)
5905       return None;
5906     // Look for a valid extend instruction on the LHS of the shift.
5907     MachineOperand &LHS = RootDef->getOperand(1);
5908     MachineInstr *ExtDef = getDefIgnoringCopies(LHS.getReg(), MRI);
5909     if (!ExtDef)
5910       return None;
5911     Ext = getExtendTypeForInst(*ExtDef, MRI);
5912     if (Ext == AArch64_AM::InvalidShiftExtend)
5913       return None;
5914     ExtReg = ExtDef->getOperand(1).getReg();
5915   } else {
5916     // Didn't get a shift. Try just folding an extend.
5917     Ext = getExtendTypeForInst(*RootDef, MRI);
5918     if (Ext == AArch64_AM::InvalidShiftExtend)
5919       return None;
5920     ExtReg = RootDef->getOperand(1).getReg();
5921 
5922     // If we have a 32 bit instruction which zeroes out the high half of a
5923     // register, we get an implicit zero extend for free. Check if we have one.
5924     // FIXME: We actually emit the extend right now even though we don't have
5925     // to.
5926     if (Ext == AArch64_AM::UXTW && MRI.getType(ExtReg).getSizeInBits() == 32) {
5927       MachineInstr *ExtInst = MRI.getVRegDef(ExtReg);
5928       if (ExtInst && isDef32(*ExtInst))
5929         return None;
5930     }
5931   }
5932 
5933   // We require a GPR32 here. Narrow the ExtReg if needed using a subregister
5934   // copy.
5935   MachineIRBuilder MIB(*RootDef);
5936   ExtReg = moveScalarRegClass(ExtReg, AArch64::GPR32RegClass, MIB);
5937 
5938   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
5939            [=](MachineInstrBuilder &MIB) {
5940              MIB.addImm(getArithExtendImm(Ext, ShiftVal));
5941            }}};
5942 }
5943 
5944 void AArch64InstructionSelector::renderTruncImm(MachineInstrBuilder &MIB,
5945                                                 const MachineInstr &MI,
5946                                                 int OpIdx) const {
5947   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5948   assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5949          "Expected G_CONSTANT");
5950   Optional<int64_t> CstVal =
5951       getConstantVRegSExtVal(MI.getOperand(0).getReg(), MRI);
5952   assert(CstVal && "Expected constant value");
5953   MIB.addImm(CstVal.getValue());
5954 }
5955 
5956 void AArch64InstructionSelector::renderLogicalImm32(
5957   MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
5958   assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5959          "Expected G_CONSTANT");
5960   uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
5961   uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 32);
5962   MIB.addImm(Enc);
5963 }
5964 
5965 void AArch64InstructionSelector::renderLogicalImm64(
5966   MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
5967   assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5968          "Expected G_CONSTANT");
5969   uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
5970   uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 64);
5971   MIB.addImm(Enc);
5972 }
5973 
5974 void AArch64InstructionSelector::renderFPImm16(MachineInstrBuilder &MIB,
5975                                                const MachineInstr &MI,
5976                                                int OpIdx) const {
5977   assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
5978          "Expected G_FCONSTANT");
5979   MIB.addImm(
5980       AArch64_AM::getFP16Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
5981 }
5982 
5983 void AArch64InstructionSelector::renderFPImm32(MachineInstrBuilder &MIB,
5984                                                const MachineInstr &MI,
5985                                                int OpIdx) const {
5986   assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
5987          "Expected G_FCONSTANT");
5988   MIB.addImm(
5989       AArch64_AM::getFP32Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
5990 }
5991 
5992 void AArch64InstructionSelector::renderFPImm64(MachineInstrBuilder &MIB,
5993                                                const MachineInstr &MI,
5994                                                int OpIdx) const {
5995   assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
5996          "Expected G_FCONSTANT");
5997   MIB.addImm(
5998       AArch64_AM::getFP64Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
5999 }
6000 
6001 bool AArch64InstructionSelector::isLoadStoreOfNumBytes(
6002     const MachineInstr &MI, unsigned NumBytes) const {
6003   if (!MI.mayLoadOrStore())
6004     return false;
6005   assert(MI.hasOneMemOperand() &&
6006          "Expected load/store to have only one mem op!");
6007   return (*MI.memoperands_begin())->getSize() == NumBytes;
6008 }
6009 
6010 bool AArch64InstructionSelector::isDef32(const MachineInstr &MI) const {
6011   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6012   if (MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() != 32)
6013     return false;
6014 
6015   // Only return true if we know the operation will zero-out the high half of
6016   // the 64-bit register. Truncates can be subregister copies, which don't
6017   // zero out the high bits. Copies and other copy-like instructions can be
6018   // fed by truncates, or could be lowered as subregister copies.
6019   switch (MI.getOpcode()) {
6020   default:
6021     return true;
6022   case TargetOpcode::COPY:
6023   case TargetOpcode::G_BITCAST:
6024   case TargetOpcode::G_TRUNC:
6025   case TargetOpcode::G_PHI:
6026     return false;
6027   }
6028 }
6029 
6030 
6031 // Perform fixups on the given PHI instruction's operands to force them all
6032 // to be the same as the destination regbank.
6033 static void fixupPHIOpBanks(MachineInstr &MI, MachineRegisterInfo &MRI,
6034                             const AArch64RegisterBankInfo &RBI) {
6035   assert(MI.getOpcode() == TargetOpcode::G_PHI && "Expected a G_PHI");
6036   Register DstReg = MI.getOperand(0).getReg();
6037   const RegisterBank *DstRB = MRI.getRegBankOrNull(DstReg);
6038   assert(DstRB && "Expected PHI dst to have regbank assigned");
6039   MachineIRBuilder MIB(MI);
6040 
6041   // Go through each operand and ensure it has the same regbank.
6042   for (unsigned OpIdx = 1; OpIdx < MI.getNumOperands(); ++OpIdx) {
6043     MachineOperand &MO = MI.getOperand(OpIdx);
6044     if (!MO.isReg())
6045       continue;
6046     Register OpReg = MO.getReg();
6047     const RegisterBank *RB = MRI.getRegBankOrNull(OpReg);
6048     if (RB != DstRB) {
6049       // Insert a cross-bank copy.
6050       auto *OpDef = MRI.getVRegDef(OpReg);
6051       const LLT &Ty = MRI.getType(OpReg);
6052       MIB.setInsertPt(*OpDef->getParent(), std::next(OpDef->getIterator()));
6053       auto Copy = MIB.buildCopy(Ty, OpReg);
6054       MRI.setRegBank(Copy.getReg(0), *DstRB);
6055       MO.setReg(Copy.getReg(0));
6056     }
6057   }
6058 }
6059 
6060 void AArch64InstructionSelector::processPHIs(MachineFunction &MF) {
6061   // We're looking for PHIs, build a list so we don't invalidate iterators.
6062   MachineRegisterInfo &MRI = MF.getRegInfo();
6063   SmallVector<MachineInstr *, 32> Phis;
6064   for (auto &BB : MF) {
6065     for (auto &MI : BB) {
6066       if (MI.getOpcode() == TargetOpcode::G_PHI)
6067         Phis.emplace_back(&MI);
6068     }
6069   }
6070 
6071   for (auto *MI : Phis) {
6072     // We need to do some work here if the operand types are < 16 bit and they
6073     // are split across fpr/gpr banks. Since all types <32b on gpr
6074     // end up being assigned gpr32 regclasses, we can end up with PHIs here
6075     // which try to select between a gpr32 and an fpr16. Ideally RBS shouldn't
6076     // be selecting heterogenous regbanks for operands if possible, but we
6077     // still need to be able to deal with it here.
6078     //
6079     // To fix this, if we have a gpr-bank operand < 32b in size and at least
6080     // one other operand is on the fpr bank, then we add cross-bank copies
6081     // to homogenize the operand banks. For simplicity the bank that we choose
6082     // to settle on is whatever bank the def operand has. For example:
6083     //
6084     // %endbb:
6085     //   %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2:fpr(s16), %bb2
6086     //  =>
6087     // %bb2:
6088     //   ...
6089     //   %in2_copy:gpr(s16) = COPY %in2:fpr(s16)
6090     //   ...
6091     // %endbb:
6092     //   %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2_copy:gpr(s16), %bb2
6093     bool HasGPROp = false, HasFPROp = false;
6094     for (unsigned OpIdx = 1; OpIdx < MI->getNumOperands(); ++OpIdx) {
6095       const auto &MO = MI->getOperand(OpIdx);
6096       if (!MO.isReg())
6097         continue;
6098       const LLT &Ty = MRI.getType(MO.getReg());
6099       if (!Ty.isValid() || !Ty.isScalar())
6100         break;
6101       if (Ty.getSizeInBits() >= 32)
6102         break;
6103       const RegisterBank *RB = MRI.getRegBankOrNull(MO.getReg());
6104       // If for some reason we don't have a regbank yet. Don't try anything.
6105       if (!RB)
6106         break;
6107 
6108       if (RB->getID() == AArch64::GPRRegBankID)
6109         HasGPROp = true;
6110       else
6111         HasFPROp = true;
6112     }
6113     // We have heterogenous regbanks, need to fixup.
6114     if (HasGPROp && HasFPROp)
6115       fixupPHIOpBanks(*MI, MRI, RBI);
6116   }
6117 }
6118 
6119 namespace llvm {
6120 InstructionSelector *
6121 createAArch64InstructionSelector(const AArch64TargetMachine &TM,
6122                                  AArch64Subtarget &Subtarget,
6123                                  AArch64RegisterBankInfo &RBI) {
6124   return new AArch64InstructionSelector(TM, Subtarget, RBI);
6125 }
6126 }
6127