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