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