LCOV - code coverage report
Current view: top level - lib/Target/AArch64 - AArch64ISelLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 4169 4595 90.7 %
Date: 2018-06-17 00:07:59 Functions: 265 269 98.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the AArch64TargetLowering class.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "AArch64ISelLowering.h"
      15             : #include "AArch64CallingConvention.h"
      16             : #include "AArch64MachineFunctionInfo.h"
      17             : #include "AArch64PerfectShuffle.h"
      18             : #include "AArch64RegisterInfo.h"
      19             : #include "AArch64Subtarget.h"
      20             : #include "MCTargetDesc/AArch64AddressingModes.h"
      21             : #include "Utils/AArch64BaseInfo.h"
      22             : #include "llvm/ADT/APFloat.h"
      23             : #include "llvm/ADT/APInt.h"
      24             : #include "llvm/ADT/ArrayRef.h"
      25             : #include "llvm/ADT/STLExtras.h"
      26             : #include "llvm/ADT/SmallVector.h"
      27             : #include "llvm/ADT/Statistic.h"
      28             : #include "llvm/ADT/StringRef.h"
      29             : #include "llvm/ADT/StringSwitch.h"
      30             : #include "llvm/ADT/Triple.h"
      31             : #include "llvm/ADT/Twine.h"
      32             : #include "llvm/Analysis/VectorUtils.h"
      33             : #include "llvm/CodeGen/CallingConvLower.h"
      34             : #include "llvm/CodeGen/MachineBasicBlock.h"
      35             : #include "llvm/CodeGen/MachineFrameInfo.h"
      36             : #include "llvm/CodeGen/MachineFunction.h"
      37             : #include "llvm/CodeGen/MachineInstr.h"
      38             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      39             : #include "llvm/CodeGen/MachineMemOperand.h"
      40             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      41             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      42             : #include "llvm/CodeGen/SelectionDAG.h"
      43             : #include "llvm/CodeGen/SelectionDAGNodes.h"
      44             : #include "llvm/CodeGen/TargetCallingConv.h"
      45             : #include "llvm/CodeGen/TargetInstrInfo.h"
      46             : #include "llvm/CodeGen/ValueTypes.h"
      47             : #include "llvm/IR/Attributes.h"
      48             : #include "llvm/IR/Constants.h"
      49             : #include "llvm/IR/DataLayout.h"
      50             : #include "llvm/IR/DebugLoc.h"
      51             : #include "llvm/IR/DerivedTypes.h"
      52             : #include "llvm/IR/Function.h"
      53             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      54             : #include "llvm/IR/GlobalValue.h"
      55             : #include "llvm/IR/IRBuilder.h"
      56             : #include "llvm/IR/Instruction.h"
      57             : #include "llvm/IR/Instructions.h"
      58             : #include "llvm/IR/Intrinsics.h"
      59             : #include "llvm/IR/Module.h"
      60             : #include "llvm/IR/OperandTraits.h"
      61             : #include "llvm/IR/Type.h"
      62             : #include "llvm/IR/Use.h"
      63             : #include "llvm/IR/Value.h"
      64             : #include "llvm/MC/MCRegisterInfo.h"
      65             : #include "llvm/Support/Casting.h"
      66             : #include "llvm/Support/CodeGen.h"
      67             : #include "llvm/Support/CommandLine.h"
      68             : #include "llvm/Support/Compiler.h"
      69             : #include "llvm/Support/Debug.h"
      70             : #include "llvm/Support/ErrorHandling.h"
      71             : #include "llvm/Support/KnownBits.h"
      72             : #include "llvm/Support/MachineValueType.h"
      73             : #include "llvm/Support/MathExtras.h"
      74             : #include "llvm/Support/raw_ostream.h"
      75             : #include "llvm/Target/TargetMachine.h"
      76             : #include "llvm/Target/TargetOptions.h"
      77             : #include <algorithm>
      78             : #include <bitset>
      79             : #include <cassert>
      80             : #include <cctype>
      81             : #include <cstdint>
      82             : #include <cstdlib>
      83             : #include <iterator>
      84             : #include <limits>
      85             : #include <tuple>
      86             : #include <utility>
      87             : #include <vector>
      88             : 
      89             : using namespace llvm;
      90             : 
      91             : #define DEBUG_TYPE "aarch64-lower"
      92             : 
      93             : STATISTIC(NumTailCalls, "Number of tail calls");
      94             : STATISTIC(NumShiftInserts, "Number of vector shift inserts");
      95             : STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
      96             : 
      97             : static cl::opt<bool>
      98      101169 : EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
      99      101169 :                            cl::desc("Allow AArch64 SLI/SRI formation"),
     100      303507 :                            cl::init(false));
     101             : 
     102             : // FIXME: The necessary dtprel relocations don't seem to be supported
     103             : // well in the GNU bfd and gold linkers at the moment. Therefore, by
     104             : // default, for now, fall back to GeneralDynamic code generation.
     105      101169 : cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
     106             :     "aarch64-elf-ldtls-generation", cl::Hidden,
     107      101169 :     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
     108      303507 :     cl::init(false));
     109             : 
     110             : static cl::opt<bool>
     111      101169 : EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
     112      101169 :                          cl::desc("Enable AArch64 logical imm instruction "
     113             :                                   "optimization"),
     114      303507 :                          cl::init(true));
     115             : 
     116             : /// Value type used for condition codes.
     117             : static const MVT MVT_CC = MVT::i32;
     118             : 
     119        1435 : AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
     120        1435 :                                              const AArch64Subtarget &STI)
     121        1435 :     : TargetLowering(TM), Subtarget(&STI) {
     122             :   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
     123             :   // we have to make something up. Arbitrarily, choose ZeroOrOne.
     124             :   setBooleanContents(ZeroOrOneBooleanContent);
     125             :   // When comparing vectors the result sets the different elements in the
     126             :   // vector to all-one or all-zero.
     127             :   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
     128             : 
     129             :   // Set up the register classes.
     130             :   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
     131             :   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
     132             : 
     133        1435 :   if (Subtarget->hasFPARMv8()) {
     134             :     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
     135             :     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
     136             :     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
     137             :     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
     138             :   }
     139             : 
     140        1435 :   if (Subtarget->hasNEON()) {
     141             :     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
     142             :     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
     143             :     // Someone set us up the NEON.
     144        1414 :     addDRTypeForNEON(MVT::v2f32);
     145        1414 :     addDRTypeForNEON(MVT::v8i8);
     146        1414 :     addDRTypeForNEON(MVT::v4i16);
     147        1414 :     addDRTypeForNEON(MVT::v2i32);
     148        1414 :     addDRTypeForNEON(MVT::v1i64);
     149        1414 :     addDRTypeForNEON(MVT::v1f64);
     150        1414 :     addDRTypeForNEON(MVT::v4f16);
     151             : 
     152        1414 :     addQRTypeForNEON(MVT::v4f32);
     153        1414 :     addQRTypeForNEON(MVT::v2f64);
     154        1414 :     addQRTypeForNEON(MVT::v16i8);
     155        1414 :     addQRTypeForNEON(MVT::v8i16);
     156        1414 :     addQRTypeForNEON(MVT::v4i32);
     157        1414 :     addQRTypeForNEON(MVT::v2i64);
     158        1414 :     addQRTypeForNEON(MVT::v8f16);
     159             :   }
     160             : 
     161             :   // Compute derived properties from the register classes
     162        2870 :   computeRegisterProperties(Subtarget->getRegisterInfo());
     163             : 
     164             :   // Provide all sorts of operation actions
     165             :   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
     166             :   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
     167             :   setOperationAction(ISD::SETCC, MVT::i32, Custom);
     168             :   setOperationAction(ISD::SETCC, MVT::i64, Custom);
     169             :   setOperationAction(ISD::SETCC, MVT::f16, Custom);
     170             :   setOperationAction(ISD::SETCC, MVT::f32, Custom);
     171             :   setOperationAction(ISD::SETCC, MVT::f64, Custom);
     172             :   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
     173             :   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
     174             :   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
     175             :   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
     176             :   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
     177             :   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
     178             :   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
     179             :   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
     180             :   setOperationAction(ISD::SELECT, MVT::i32, Custom);
     181             :   setOperationAction(ISD::SELECT, MVT::i64, Custom);
     182             :   setOperationAction(ISD::SELECT, MVT::f16, Custom);
     183             :   setOperationAction(ISD::SELECT, MVT::f32, Custom);
     184             :   setOperationAction(ISD::SELECT, MVT::f64, Custom);
     185             :   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
     186             :   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
     187             :   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
     188             :   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
     189             :   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
     190             :   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
     191             :   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
     192             : 
     193             :   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
     194             :   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
     195             :   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
     196             : 
     197             :   setOperationAction(ISD::FREM, MVT::f32, Expand);
     198             :   setOperationAction(ISD::FREM, MVT::f64, Expand);
     199             :   setOperationAction(ISD::FREM, MVT::f80, Expand);
     200             : 
     201             :   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
     202             : 
     203             :   // Custom lowering hooks are needed for XOR
     204             :   // to fold it into CSINC/CSINV.
     205             :   setOperationAction(ISD::XOR, MVT::i32, Custom);
     206             :   setOperationAction(ISD::XOR, MVT::i64, Custom);
     207             : 
     208             :   // Virtually no operation on f128 is legal, but LLVM can't expand them when
     209             :   // there's a valid register class, so we need custom operations in most cases.
     210             :   setOperationAction(ISD::FABS, MVT::f128, Expand);
     211             :   setOperationAction(ISD::FADD, MVT::f128, Custom);
     212             :   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
     213             :   setOperationAction(ISD::FCOS, MVT::f128, Expand);
     214             :   setOperationAction(ISD::FDIV, MVT::f128, Custom);
     215             :   setOperationAction(ISD::FMA, MVT::f128, Expand);
     216             :   setOperationAction(ISD::FMUL, MVT::f128, Custom);
     217             :   setOperationAction(ISD::FNEG, MVT::f128, Expand);
     218             :   setOperationAction(ISD::FPOW, MVT::f128, Expand);
     219             :   setOperationAction(ISD::FREM, MVT::f128, Expand);
     220             :   setOperationAction(ISD::FRINT, MVT::f128, Expand);
     221             :   setOperationAction(ISD::FSIN, MVT::f128, Expand);
     222             :   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
     223             :   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
     224             :   setOperationAction(ISD::FSUB, MVT::f128, Custom);
     225             :   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
     226             :   setOperationAction(ISD::SETCC, MVT::f128, Custom);
     227             :   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
     228             :   setOperationAction(ISD::SELECT, MVT::f128, Custom);
     229             :   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
     230             :   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
     231             : 
     232             :   // Lowering for many of the conversions is actually specified by the non-f128
     233             :   // type. The LowerXXX function will be trivial when f128 isn't involved.
     234             :   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
     235             :   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
     236             :   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
     237             :   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
     238             :   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
     239             :   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
     240             :   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
     241             :   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
     242             :   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
     243             :   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
     244             :   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
     245             :   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
     246             :   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
     247             :   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
     248             : 
     249             :   // Variable arguments.
     250             :   setOperationAction(ISD::VASTART, MVT::Other, Custom);
     251             :   setOperationAction(ISD::VAARG, MVT::Other, Custom);
     252             :   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
     253             :   setOperationAction(ISD::VAEND, MVT::Other, Expand);
     254             : 
     255             :   // Variable-sized objects.
     256             :   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
     257             :   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
     258             : 
     259        2870 :   if (Subtarget->isTargetWindows())
     260             :     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
     261             :   else
     262             :     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
     263             : 
     264             :   // Constant pool entries
     265             :   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
     266             : 
     267             :   // BlockAddress
     268             :   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
     269             : 
     270             :   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
     271             :   setOperationAction(ISD::ADDC, MVT::i32, Custom);
     272             :   setOperationAction(ISD::ADDE, MVT::i32, Custom);
     273             :   setOperationAction(ISD::SUBC, MVT::i32, Custom);
     274             :   setOperationAction(ISD::SUBE, MVT::i32, Custom);
     275             :   setOperationAction(ISD::ADDC, MVT::i64, Custom);
     276             :   setOperationAction(ISD::ADDE, MVT::i64, Custom);
     277             :   setOperationAction(ISD::SUBC, MVT::i64, Custom);
     278             :   setOperationAction(ISD::SUBE, MVT::i64, Custom);
     279             : 
     280             :   // AArch64 lacks both left-rotate and popcount instructions.
     281             :   setOperationAction(ISD::ROTL, MVT::i32, Expand);
     282             :   setOperationAction(ISD::ROTL, MVT::i64, Expand);
     283      137760 :   for (MVT VT : MVT::vector_valuetypes()) {
     284             :     setOperationAction(ISD::ROTL, VT, Expand);
     285             :     setOperationAction(ISD::ROTR, VT, Expand);
     286             :   }
     287             : 
     288             :   // AArch64 doesn't have {U|S}MUL_LOHI.
     289             :   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
     290             :   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
     291             : 
     292             :   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
     293             :   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
     294             : 
     295             :   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
     296             :   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
     297      137760 :   for (MVT VT : MVT::vector_valuetypes()) {
     298             :     setOperationAction(ISD::SDIVREM, VT, Expand);
     299             :     setOperationAction(ISD::UDIVREM, VT, Expand);
     300             :   }
     301             :   setOperationAction(ISD::SREM, MVT::i32, Expand);
     302             :   setOperationAction(ISD::SREM, MVT::i64, Expand);
     303             :   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
     304             :   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
     305             :   setOperationAction(ISD::UREM, MVT::i32, Expand);
     306             :   setOperationAction(ISD::UREM, MVT::i64, Expand);
     307             : 
     308             :   // Custom lower Add/Sub/Mul with overflow.
     309             :   setOperationAction(ISD::SADDO, MVT::i32, Custom);
     310             :   setOperationAction(ISD::SADDO, MVT::i64, Custom);
     311             :   setOperationAction(ISD::UADDO, MVT::i32, Custom);
     312             :   setOperationAction(ISD::UADDO, MVT::i64, Custom);
     313             :   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
     314             :   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
     315             :   setOperationAction(ISD::USUBO, MVT::i32, Custom);
     316             :   setOperationAction(ISD::USUBO, MVT::i64, Custom);
     317             :   setOperationAction(ISD::SMULO, MVT::i32, Custom);
     318             :   setOperationAction(ISD::SMULO, MVT::i64, Custom);
     319             :   setOperationAction(ISD::UMULO, MVT::i32, Custom);
     320             :   setOperationAction(ISD::UMULO, MVT::i64, Custom);
     321             : 
     322             :   setOperationAction(ISD::FSIN, MVT::f32, Expand);
     323             :   setOperationAction(ISD::FSIN, MVT::f64, Expand);
     324             :   setOperationAction(ISD::FCOS, MVT::f32, Expand);
     325             :   setOperationAction(ISD::FCOS, MVT::f64, Expand);
     326             :   setOperationAction(ISD::FPOW, MVT::f32, Expand);
     327             :   setOperationAction(ISD::FPOW, MVT::f64, Expand);
     328             :   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
     329             :   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
     330        1435 :   if (Subtarget->hasFullFP16())
     331             :     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
     332             :   else
     333             :     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
     334             : 
     335             :   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
     336             :   setOperationAction(ISD::FREM,    MVT::v4f16, Promote);
     337             :   setOperationAction(ISD::FREM,    MVT::v8f16, Promote);
     338             :   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
     339             :   setOperationAction(ISD::FPOW,    MVT::v4f16, Promote);
     340             :   setOperationAction(ISD::FPOW,    MVT::v8f16, Promote);
     341             :   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
     342             :   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
     343             :   setOperationAction(ISD::FCOS,    MVT::v4f16, Promote);
     344             :   setOperationAction(ISD::FCOS,    MVT::v8f16, Promote);
     345             :   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
     346             :   setOperationAction(ISD::FSIN,    MVT::v4f16, Promote);
     347             :   setOperationAction(ISD::FSIN,    MVT::v8f16, Promote);
     348             :   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
     349             :   setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
     350             :   setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
     351             :   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
     352             :   setOperationAction(ISD::FEXP,    MVT::v4f16, Promote);
     353             :   setOperationAction(ISD::FEXP,    MVT::v8f16, Promote);
     354             :   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
     355             :   setOperationAction(ISD::FEXP2,   MVT::v4f16, Promote);
     356             :   setOperationAction(ISD::FEXP2,   MVT::v8f16, Promote);
     357             :   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
     358             :   setOperationAction(ISD::FLOG,    MVT::v4f16, Promote);
     359             :   setOperationAction(ISD::FLOG,    MVT::v8f16, Promote);
     360             :   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
     361             :   setOperationAction(ISD::FLOG2,   MVT::v4f16, Promote);
     362             :   setOperationAction(ISD::FLOG2,   MVT::v8f16, Promote);
     363             :   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
     364             :   setOperationAction(ISD::FLOG10,  MVT::v4f16, Promote);
     365             :   setOperationAction(ISD::FLOG10,  MVT::v8f16, Promote);
     366             : 
     367        1435 :   if (!Subtarget->hasFullFP16()) {
     368             :     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
     369             :     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
     370             :     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
     371             :     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
     372             :     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
     373             :     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
     374             :     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
     375             :     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
     376             :     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
     377             :     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
     378             :     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
     379             :     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
     380             :     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
     381             :     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
     382             :     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
     383             :     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
     384             :     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
     385             :     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
     386             :     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
     387             :     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
     388             :     setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
     389             :     setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
     390             : 
     391             :     // promote v4f16 to v4f32 when that is known to be safe.
     392             :     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
     393             :     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
     394             :     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
     395             :     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
     396             :     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
     397             :     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
     398             :     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
     399             :     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
     400             :     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
     401             :     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
     402             :     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
     403             :     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
     404             : 
     405             :     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
     406             :     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
     407             :     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
     408             :     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
     409             :     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
     410             :     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
     411             :     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
     412             :     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
     413             :     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
     414             :     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
     415             :     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
     416             :     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
     417             :     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
     418             :     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
     419             :     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
     420             : 
     421             :     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
     422             :     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
     423             :     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
     424             :     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
     425             :     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
     426             :     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
     427             :     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
     428             :     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
     429             :     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
     430             :     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
     431             :     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
     432             :     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
     433             :     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
     434             :     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
     435             :     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
     436             :     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
     437             :     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
     438             :     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
     439             :     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
     440             :     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
     441             :   }
     442             : 
     443             :   // AArch64 has implementations of a lot of rounding-like FP operations.
     444        7175 :   for (MVT Ty : {MVT::f32, MVT::f64}) {
     445             :     setOperationAction(ISD::FFLOOR, Ty, Legal);
     446             :     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
     447             :     setOperationAction(ISD::FCEIL, Ty, Legal);
     448             :     setOperationAction(ISD::FRINT, Ty, Legal);
     449             :     setOperationAction(ISD::FTRUNC, Ty, Legal);
     450             :     setOperationAction(ISD::FROUND, Ty, Legal);
     451             :     setOperationAction(ISD::FMINNUM, Ty, Legal);
     452             :     setOperationAction(ISD::FMAXNUM, Ty, Legal);
     453             :     setOperationAction(ISD::FMINNAN, Ty, Legal);
     454             :     setOperationAction(ISD::FMAXNAN, Ty, Legal);
     455             :   }
     456             : 
     457        1435 :   if (Subtarget->hasFullFP16()) {
     458             :     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
     459             :     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
     460             :     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
     461             :     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
     462             :     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
     463             :     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
     464             :     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
     465             :     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
     466             :     setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
     467             :     setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
     468             :   }
     469             : 
     470             :   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
     471             : 
     472             :   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
     473             :   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
     474             :   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
     475             :   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
     476             :   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
     477             : 
     478             :   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
     479             :   // This requires the Performance Monitors extension.
     480        1435 :   if (Subtarget->hasPerfMon())
     481             :     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
     482             : 
     483        1521 :   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
     484             :       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
     485             :     // Issue __sincos_stret if available.
     486             :     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
     487             :     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
     488             :   } else {
     489             :     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
     490             :     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
     491             :   }
     492             : 
     493             :   // Make floating-point constants legal for the large code model, so they don't
     494             :   // become loads from the constant pool.
     495        2870 :   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
     496             :     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
     497             :     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
     498             :   }
     499             : 
     500             :   // AArch64 does not have floating-point extending loads, i1 sign-extending
     501             :   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
     502       10045 :   for (MVT VT : MVT::fp_valuetypes()) {
     503             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
     504             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
     505             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
     506             :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
     507             :   }
     508       10045 :   for (MVT VT : MVT::integer_valuetypes())
     509             :     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
     510             : 
     511             :   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
     512             :   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
     513             :   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
     514             :   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
     515             :   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
     516             :   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
     517             :   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
     518             : 
     519             :   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
     520             :   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
     521             : 
     522             :   // Indexed loads and stores are supported.
     523        5740 :   for (unsigned im = (unsigned)ISD::PRE_INC;
     524        7175 :        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
     525             :     setIndexedLoadAction(im, MVT::i8, Legal);
     526             :     setIndexedLoadAction(im, MVT::i16, Legal);
     527             :     setIndexedLoadAction(im, MVT::i32, Legal);
     528             :     setIndexedLoadAction(im, MVT::i64, Legal);
     529             :     setIndexedLoadAction(im, MVT::f64, Legal);
     530             :     setIndexedLoadAction(im, MVT::f32, Legal);
     531             :     setIndexedLoadAction(im, MVT::f16, Legal);
     532             :     setIndexedStoreAction(im, MVT::i8, Legal);
     533             :     setIndexedStoreAction(im, MVT::i16, Legal);
     534             :     setIndexedStoreAction(im, MVT::i32, Legal);
     535             :     setIndexedStoreAction(im, MVT::i64, Legal);
     536             :     setIndexedStoreAction(im, MVT::f64, Legal);
     537             :     setIndexedStoreAction(im, MVT::f32, Legal);
     538             :     setIndexedStoreAction(im, MVT::f16, Legal);
     539             :   }
     540             : 
     541             :   // Trap.
     542             :   setOperationAction(ISD::TRAP, MVT::Other, Legal);
     543             : 
     544             :   // We combine OR nodes for bitfield operations.
     545             :   setTargetDAGCombine(ISD::OR);
     546             : 
     547             :   // Vector add and sub nodes may conceal a high-half opportunity.
     548             :   // Also, try to fold ADD into CSINC/CSINV..
     549             :   setTargetDAGCombine(ISD::ADD);
     550             :   setTargetDAGCombine(ISD::SUB);
     551             :   setTargetDAGCombine(ISD::SRL);
     552             :   setTargetDAGCombine(ISD::XOR);
     553             :   setTargetDAGCombine(ISD::SINT_TO_FP);
     554             :   setTargetDAGCombine(ISD::UINT_TO_FP);
     555             : 
     556             :   setTargetDAGCombine(ISD::FP_TO_SINT);
     557             :   setTargetDAGCombine(ISD::FP_TO_UINT);
     558             :   setTargetDAGCombine(ISD::FDIV);
     559             : 
     560             :   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
     561             : 
     562             :   setTargetDAGCombine(ISD::ANY_EXTEND);
     563             :   setTargetDAGCombine(ISD::ZERO_EXTEND);
     564             :   setTargetDAGCombine(ISD::SIGN_EXTEND);
     565             :   setTargetDAGCombine(ISD::BITCAST);
     566             :   setTargetDAGCombine(ISD::CONCAT_VECTORS);
     567             :   setTargetDAGCombine(ISD::STORE);
     568        1435 :   if (Subtarget->supportsAddressTopByteIgnored())
     569             :     setTargetDAGCombine(ISD::LOAD);
     570             : 
     571             :   setTargetDAGCombine(ISD::MUL);
     572             : 
     573             :   setTargetDAGCombine(ISD::SELECT);
     574             :   setTargetDAGCombine(ISD::VSELECT);
     575             : 
     576             :   setTargetDAGCombine(ISD::INTRINSIC_VOID);
     577             :   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
     578             :   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
     579             : 
     580             :   setTargetDAGCombine(ISD::GlobalAddress);
     581             : 
     582             :   // In case of strict alignment, avoid an excessive number of byte wide stores.
     583        1435 :   MaxStoresPerMemsetOptSize = 8;
     584        2870 :   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
     585        1435 :                        ? MaxStoresPerMemsetOptSize : 32;
     586             : 
     587        1435 :   MaxGluedStoresPerMemcpy = 4;
     588        1435 :   MaxStoresPerMemcpyOptSize = 4;
     589        1435 :   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
     590        1435 :                        ? MaxStoresPerMemcpyOptSize : 16;
     591             : 
     592        1435 :   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
     593             : 
     594             :   setStackPointerRegisterToSaveRestore(AArch64::SP);
     595             : 
     596             :   setSchedulingPreference(Sched::Hybrid);
     597             : 
     598        1435 :   EnableExtLdPromotion = true;
     599             : 
     600             :   // Set required alignment.
     601             :   setMinFunctionAlignment(2);
     602             :   // Set preferred alignments.
     603        1435 :   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
     604        1435 :   setPrefLoopAlignment(STI.getPrefLoopAlignment());
     605             : 
     606             :   // Only change the limit for entries in a jump table if specified by
     607             :   // the subtarget, but not at the command line.
     608        1435 :   unsigned MaxJT = STI.getMaximumJumpTableSize();
     609        1435 :   if (MaxJT && getMaximumJumpTableSize() == 0)
     610          37 :     setMaximumJumpTableSize(MaxJT);
     611             : 
     612             :   setHasExtractBitsInsn(true);
     613             : 
     614             :   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
     615             : 
     616        1435 :   if (Subtarget->hasNEON()) {
     617             :     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
     618             :     // silliness like this:
     619             :     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
     620             :     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
     621             :     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
     622             :     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
     623             :     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
     624             :     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
     625             :     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
     626             :     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
     627             :     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
     628             :     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
     629             :     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
     630             :     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
     631             :     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
     632             :     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
     633             :     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
     634             :     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
     635             :     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
     636             :     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
     637             :     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
     638             :     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
     639             :     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
     640             :     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
     641             :     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
     642             :     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
     643             :     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
     644             : 
     645             :     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
     646             :     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
     647             :     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
     648             :     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
     649             :     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
     650             : 
     651             :     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
     652             : 
     653             :     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
     654             :     // elements smaller than i32, so promote the input to i32 first.
     655             :     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
     656             :     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
     657             :     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
     658             :     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
     659             :     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
     660             :     // -> v8f16 conversions.
     661             :     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
     662             :     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
     663             :     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
     664             :     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
     665             :     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
     666             :     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
     667             :     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
     668             :     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
     669             :     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
     670             :     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
     671             :     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
     672             :     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
     673             :     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
     674             : 
     675             :     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
     676             :     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
     677             : 
     678             :     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
     679             :     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
     680             :     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
     681             :     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
     682             :     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
     683             :     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
     684             :     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
     685             :     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
     686             : 
     687             :     // AArch64 doesn't have MUL.2d:
     688             :     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
     689             :     // Custom handling for some quad-vector types to detect MULL.
     690             :     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
     691             :     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
     692             :     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
     693             : 
     694             :     // Vector reductions
     695        9898 :     for (MVT VT : MVT::integer_valuetypes()) {
     696             :       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
     697             :       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
     698             :       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
     699             :       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
     700             :       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
     701             :     }
     702        9898 :     for (MVT VT : MVT::fp_valuetypes()) {
     703             :       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
     704             :       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
     705             :     }
     706             : 
     707             :     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
     708             :     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
     709             :     // Likewise, narrowing and extending vector loads/stores aren't handled
     710             :     // directly.
     711      135744 :     for (MVT VT : MVT::vector_valuetypes()) {
     712             :       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
     713             : 
     714      134330 :       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
     715             :         setOperationAction(ISD::MULHS, VT, Custom);
     716             :         setOperationAction(ISD::MULHU, VT, Custom);
     717             :       } else {
     718             :         setOperationAction(ISD::MULHS, VT, Expand);
     719             :         setOperationAction(ISD::MULHU, VT, Expand);
     720             :       }
     721             :       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
     722             :       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
     723             : 
     724             :       setOperationAction(ISD::BSWAP, VT, Expand);
     725             : 
     726    12895680 :       for (MVT InnerVT : MVT::vector_valuetypes()) {
     727             :         setTruncStoreAction(VT, InnerVT, Expand);
     728             :         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
     729             :         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
     730             :         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
     731             :       }
     732             :     }
     733             : 
     734             :     // AArch64 has implementations of a lot of rounding-like FP operations.
     735        9898 :     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
     736             :       setOperationAction(ISD::FFLOOR, Ty, Legal);
     737             :       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
     738             :       setOperationAction(ISD::FCEIL, Ty, Legal);
     739             :       setOperationAction(ISD::FRINT, Ty, Legal);
     740             :       setOperationAction(ISD::FTRUNC, Ty, Legal);
     741             :       setOperationAction(ISD::FROUND, Ty, Legal);
     742             :     }
     743             :   }
     744             : 
     745        1435 :   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
     746        1435 : }
     747             : 
     748       19796 : void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
     749             :   assert(VT.isVector() && "VT should be a vector type");
     750             : 
     751       19796 :   if (VT.isFloatingPoint()) {
     752        8484 :     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
     753             :     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
     754             :     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
     755             :   }
     756             : 
     757             :   // Mark vector float intrinsics as expand.
     758       19796 :   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
     759             :     setOperationAction(ISD::FSIN, VT, Expand);
     760             :     setOperationAction(ISD::FCOS, VT, Expand);
     761             :     setOperationAction(ISD::FPOW, VT, Expand);
     762             :     setOperationAction(ISD::FLOG, VT, Expand);
     763             :     setOperationAction(ISD::FLOG2, VT, Expand);
     764             :     setOperationAction(ISD::FLOG10, VT, Expand);
     765             :     setOperationAction(ISD::FEXP, VT, Expand);
     766             :     setOperationAction(ISD::FEXP2, VT, Expand);
     767             : 
     768             :     // But we do support custom-lowering for FCOPYSIGN.
     769             :     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
     770             :   }
     771             : 
     772             :   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
     773             :   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
     774             :   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
     775             :   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
     776             :   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
     777             :   setOperationAction(ISD::SRA, VT, Custom);
     778             :   setOperationAction(ISD::SRL, VT, Custom);
     779             :   setOperationAction(ISD::SHL, VT, Custom);
     780             :   setOperationAction(ISD::AND, VT, Custom);
     781             :   setOperationAction(ISD::OR, VT, Custom);
     782             :   setOperationAction(ISD::SETCC, VT, Custom);
     783             :   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
     784             : 
     785             :   setOperationAction(ISD::SELECT, VT, Expand);
     786             :   setOperationAction(ISD::SELECT_CC, VT, Expand);
     787             :   setOperationAction(ISD::VSELECT, VT, Expand);
     788     2256744 :   for (MVT InnerVT : MVT::all_valuetypes())
     789             :     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
     790             : 
     791             :   // CNT supports only B element sizes.
     792       19796 :   if (VT != MVT::v8i8 && VT != MVT::v16i8)
     793             :     setOperationAction(ISD::CTPOP, VT, Expand);
     794             : 
     795             :   setOperationAction(ISD::UDIV, VT, Expand);
     796             :   setOperationAction(ISD::SDIV, VT, Expand);
     797             :   setOperationAction(ISD::UREM, VT, Expand);
     798             :   setOperationAction(ISD::SREM, VT, Expand);
     799             :   setOperationAction(ISD::FREM, VT, Expand);
     800             : 
     801             :   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
     802             :   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
     803             : 
     804       19796 :   if (!VT.isFloatingPoint())
     805             :     setOperationAction(ISD::ABS, VT, Legal);
     806             : 
     807             :   // [SU][MIN|MAX] are available for all NEON types apart from i64.
     808       19796 :   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
     809       76356 :     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
     810             :       setOperationAction(Opcode, VT, Legal);
     811             : 
     812             :   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
     813       28280 :   if (VT.isFloatingPoint() &&
     814       11312 :       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
     815       45552 :     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
     816       28470 :                             ISD::FMINNUM, ISD::FMAXNUM})
     817             :       setOperationAction(Opcode, VT, Legal);
     818             : 
     819       19796 :   if (Subtarget->isLittleEndian()) {
     820       77616 :     for (unsigned im = (unsigned)ISD::PRE_INC;
     821       97020 :          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
     822             :       setIndexedLoadAction(im, VT, Legal);
     823             :       setIndexedStoreAction(im, VT, Legal);
     824             :     }
     825             :   }
     826       19796 : }
     827             : 
     828        9898 : void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
     829             :   addRegisterClass(VT, &AArch64::FPR64RegClass);
     830        9898 :   addTypeForNEON(VT, MVT::v2i32);
     831        9898 : }
     832             : 
     833        9898 : void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
     834             :   addRegisterClass(VT, &AArch64::FPR128RegClass);
     835        9898 :   addTypeForNEON(VT, MVT::v4i32);
     836        9898 : }
     837             : 
     838        3783 : EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
     839             :                                               EVT VT) const {
     840        3783 :   if (!VT.isVector())
     841        3272 :     return MVT::i32;
     842         511 :   return VT.changeVectorElementTypeToInteger();
     843             : }
     844             : 
     845         642 : static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
     846             :                                const APInt &Demanded,
     847             :                                TargetLowering::TargetLoweringOpt &TLO,
     848             :                                unsigned NewOpc) {
     849             :   uint64_t OldImm = Imm, NewImm, Enc;
     850         642 :   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
     851             : 
     852             :   // Return if the immediate is already all zeros, all ones, a bimm32 or a
     853             :   // bimm64.
     854        1284 :   if (Imm == 0 || Imm == Mask ||
     855         642 :       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
     856             :     return false;
     857             : 
     858             :   unsigned EltSize = Size;
     859             :   uint64_t DemandedBits = Demanded.getZExtValue();
     860             : 
     861             :   // Clear bits that are not demanded.
     862          23 :   Imm &= DemandedBits;
     863             : 
     864             :   while (true) {
     865             :     // The goal here is to set the non-demanded bits in a way that minimizes
     866             :     // the number of switching between 0 and 1. In order to achieve this goal,
     867             :     // we set the non-demanded bits to the value of the preceding demanded bits.
     868             :     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
     869             :     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
     870             :     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
     871             :     // The final result is 0b11000011.
     872          28 :     uint64_t NonDemandedBits = ~DemandedBits;
     873          28 :     uint64_t InvertedImm = ~Imm & DemandedBits;
     874          28 :     uint64_t RotatedImm =
     875          28 :         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
     876             :         NonDemandedBits;
     877          28 :     uint64_t Sum = RotatedImm + NonDemandedBits;
     878          28 :     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
     879          28 :     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
     880          28 :     NewImm = (Imm | Ones) & Mask;
     881             : 
     882             :     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
     883             :     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
     884             :     // we halve the element size and continue the search.
     885          28 :     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
     886             :       break;
     887             : 
     888             :     // We cannot shrink the element size any further if it is 2-bits.
     889          23 :     if (EltSize == 2)
     890             :       return false;
     891             : 
     892          23 :     EltSize /= 2;
     893          23 :     Mask >>= EltSize;
     894          23 :     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
     895             : 
     896             :     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
     897          23 :     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
     898             :       return false;
     899             : 
     900             :     // Merge the upper and lower halves of Imm and DemandedBits.
     901           5 :     Imm |= Hi;
     902           5 :     DemandedBits |= DemandedBitsHi;
     903             :   }
     904             : 
     905             :   ++NumOptimizedImms;
     906             : 
     907             :   // Replicate the element across the register width.
     908          10 :   while (EltSize < Size) {
     909           5 :     NewImm |= NewImm << EltSize;
     910           5 :     EltSize *= 2;
     911             :   }
     912             : 
     913             :   (void)OldImm;
     914             :   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
     915             :          "demanded bits should never be altered");
     916             :   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
     917             : 
     918             :   // Create the new constant immediate node.
     919           5 :   EVT VT = Op.getValueType();
     920             :   SDLoc DL(Op);
     921             :   SDValue New;
     922             : 
     923             :   // If the new constant immediate is all-zeros or all-ones, let the target
     924             :   // independent DAG combine optimize this node.
     925           5 :   if (NewImm == 0 || NewImm == OrigMask) {
     926           2 :     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
     927           2 :                           TLO.DAG.getConstant(NewImm, DL, VT));
     928             :   // Otherwise, create a machine node so that target independent DAG combine
     929             :   // doesn't undo this optimization.
     930             :   } else {
     931             :     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
     932           8 :     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
     933             :     New = SDValue(
     934           8 :         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
     935             :   }
     936             : 
     937             :   return TLO.CombineTo(Op, New);
     938             : }
     939             : 
     940        8718 : bool AArch64TargetLowering::targetShrinkDemandedConstant(
     941             :     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
     942             :   // Delay this optimization to as late as possible.
     943        8718 :   if (!TLO.LegalOps)
     944             :     return false;
     945             : 
     946        4379 :   if (!EnableOptimizeLogicalImm)
     947             :     return false;
     948             : 
     949        4379 :   EVT VT = Op.getValueType();
     950        4379 :   if (VT.isVector())
     951             :     return false;
     952             : 
     953        3326 :   unsigned Size = VT.getSizeInBits();
     954             :   assert((Size == 32 || Size == 64) &&
     955             :          "i32 or i64 is expected after legalization.");
     956             : 
     957             :   // Exit early if we demand all bits.
     958        3326 :   if (Demanded.countPopulation() == Size)
     959             :     return false;
     960             : 
     961             :   unsigned NewOpc;
     962         725 :   switch (Op.getOpcode()) {
     963             :   default:
     964             :     return false;
     965         656 :   case ISD::AND:
     966         656 :     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
     967             :     break;
     968          65 :   case ISD::OR:
     969          65 :     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
     970             :     break;
     971           2 :   case ISD::XOR:
     972           2 :     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
     973             :     break;
     974             :   }
     975             :   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
     976             :   if (!C)
     977             :     return false;
     978         642 :   uint64_t Imm = C->getZExtValue();
     979         642 :   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
     980             : }
     981             : 
     982             : /// computeKnownBitsForTargetNode - Determine which of the bits specified in
     983             : /// Mask are known to be either zero or one and return them Known.
     984        6675 : void AArch64TargetLowering::computeKnownBitsForTargetNode(
     985             :     const SDValue Op, KnownBits &Known,
     986             :     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
     987        6675 :   switch (Op.getOpcode()) {
     988             :   default:
     989             :     break;
     990             :   case AArch64ISD::CSEL: {
     991         346 :     KnownBits Known2;
     992         692 :     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
     993         692 :     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
     994         346 :     Known.Zero &= Known2.Zero;
     995         346 :     Known.One &= Known2.One;
     996             :     break;
     997             :   }
     998        1193 :   case ISD::INTRINSIC_W_CHAIN: {
     999        1193 :     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
    1000        2386 :     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
    1001        1193 :     switch (IntID) {
    1002             :     default: return;
    1003             :     case Intrinsic::aarch64_ldaxr:
    1004             :     case Intrinsic::aarch64_ldxr: {
    1005             :       unsigned BitWidth = Known.getBitWidth();
    1006        1013 :       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
    1007             :       unsigned MemBits = VT.getScalarSizeInBits();
    1008        2026 :       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
    1009             :       return;
    1010             :     }
    1011             :     }
    1012             :     break;
    1013             :   }
    1014        1433 :   case ISD::INTRINSIC_WO_CHAIN:
    1015             :   case ISD::INTRINSIC_VOID: {
    1016        2866 :     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    1017        1433 :     switch (IntNo) {
    1018             :     default:
    1019             :       break;
    1020          25 :     case Intrinsic::aarch64_neon_umaxv:
    1021             :     case Intrinsic::aarch64_neon_uminv: {
    1022             :       // Figure out the datatype of the vector operand. The UMINV instruction
    1023             :       // will zero extend the result, so we can mark as known zero all the
    1024             :       // bits larger than the element datatype. 32-bit or larget doesn't need
    1025             :       // this as those are legal types and will be handled by isel directly.
    1026          25 :       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
    1027             :       unsigned BitWidth = Known.getBitWidth();
    1028          25 :       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
    1029             :         assert(BitWidth >= 8 && "Unexpected width!");
    1030          16 :         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
    1031          16 :         Known.Zero |= Mask;
    1032          13 :       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
    1033             :         assert(BitWidth >= 16 && "Unexpected width!");
    1034           9 :         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
    1035           9 :         Known.Zero |= Mask;
    1036             :       }
    1037             :       break;
    1038             :     } break;
    1039             :     }
    1040             :   }
    1041             :   }
    1042             : }
    1043             : 
    1044        3688 : MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
    1045             :                                                   EVT) const {
    1046        3688 :   return MVT::i64;
    1047             : }
    1048             : 
    1049        2598 : bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
    1050             :                                                            unsigned AddrSpace,
    1051             :                                                            unsigned Align,
    1052             :                                                            bool *Fast) const {
    1053        2598 :   if (Subtarget->requiresStrictAlign())
    1054             :     return false;
    1055             : 
    1056        2107 :   if (Fast) {
    1057             :     // Some CPUs are fine with unaligned stores except for 128-bit ones.
    1058         500 :     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
    1059             :             // See comments in performSTORECombine() for more details about
    1060             :             // these conditions.
    1061             : 
    1062             :             // Code that uses clang vector extensions can mark that it
    1063             :             // wants unaligned accesses to be treated as fast by
    1064             :             // underspecifying alignment to be 1 or 2.
    1065         232 :             Align <= 2 ||
    1066             : 
    1067             :             // Disregard v2i64. Memcpy lowering produces those and splitting
    1068             :             // them regresses performance on micro-benchmarks and olden/bh.
    1069             :             VT == MVT::v2i64;
    1070             :   }
    1071             :   return true;
    1072             : }
    1073             : 
    1074             : FastISel *
    1075        1196 : AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
    1076             :                                       const TargetLibraryInfo *libInfo) const {
    1077        1196 :   return AArch64::createFastISel(funcInfo, libInfo);
    1078             : }
    1079             : 
    1080           0 : const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
    1081           0 :   switch ((AArch64ISD::NodeType)Opcode) {
    1082             :   case AArch64ISD::FIRST_NUMBER:      break;
    1083             :   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
    1084           0 :   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
    1085           0 :   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
    1086           0 :   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
    1087           0 :   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
    1088           0 :   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
    1089           0 :   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
    1090           0 :   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
    1091           0 :   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
    1092           0 :   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
    1093           0 :   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
    1094           0 :   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
    1095           0 :   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
    1096           0 :   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
    1097           0 :   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
    1098           0 :   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
    1099           0 :   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
    1100           0 :   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
    1101           0 :   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
    1102           0 :   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
    1103           0 :   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
    1104           0 :   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
    1105           0 :   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
    1106           0 :   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
    1107           0 :   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
    1108           0 :   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
    1109           0 :   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
    1110           0 :   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
    1111           0 :   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
    1112           0 :   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
    1113           0 :   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
    1114           0 :   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
    1115           0 :   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
    1116           0 :   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
    1117           0 :   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
    1118           0 :   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
    1119           0 :   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
    1120           0 :   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
    1121           0 :   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
    1122           0 :   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
    1123           0 :   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
    1124           0 :   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
    1125           0 :   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
    1126           0 :   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
    1127           0 :   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
    1128           0 :   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
    1129           0 :   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
    1130           0 :   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
    1131           0 :   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
    1132           0 :   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
    1133           0 :   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
    1134           0 :   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
    1135           0 :   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
    1136           0 :   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
    1137           0 :   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
    1138           0 :   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
    1139           0 :   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
    1140           0 :   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
    1141           0 :   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
    1142           0 :   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
    1143           0 :   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
    1144           0 :   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
    1145           0 :   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
    1146           0 :   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
    1147           0 :   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
    1148           0 :   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
    1149           0 :   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
    1150           0 :   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
    1151           0 :   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
    1152           0 :   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
    1153           0 :   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
    1154           0 :   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
    1155           0 :   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
    1156           0 :   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
    1157           0 :   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
    1158           0 :   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
    1159           0 :   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
    1160           0 :   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
    1161           0 :   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
    1162           0 :   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
    1163           0 :   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
    1164           0 :   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
    1165           0 :   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
    1166           0 :   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
    1167           0 :   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
    1168           0 :   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
    1169           0 :   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
    1170           0 :   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
    1171           0 :   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
    1172           0 :   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
    1173           0 :   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
    1174           0 :   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
    1175           0 :   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
    1176           0 :   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
    1177           0 :   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
    1178           0 :   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
    1179           0 :   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
    1180           0 :   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
    1181           0 :   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
    1182           0 :   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
    1183           0 :   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
    1184           0 :   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
    1185           0 :   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
    1186           0 :   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
    1187           0 :   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
    1188           0 :   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
    1189           0 :   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
    1190           0 :   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
    1191           0 :   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
    1192           0 :   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
    1193           0 :   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
    1194           0 :   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
    1195           0 :   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
    1196           0 :   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
    1197           0 :   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
    1198           0 :   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
    1199           0 :   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
    1200           0 :   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
    1201           0 :   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
    1202           0 :   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
    1203           0 :   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
    1204           0 :   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
    1205           0 :   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
    1206           0 :   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
    1207             :   }
    1208           0 :   return nullptr;
    1209             : }
    1210             : 
    1211             : MachineBasicBlock *
    1212           3 : AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
    1213             :                                     MachineBasicBlock *MBB) const {
    1214             :   // We materialise the F128CSEL pseudo-instruction as some control flow and a
    1215             :   // phi node:
    1216             : 
    1217             :   // OrigBB:
    1218             :   //     [... previous instrs leading to comparison ...]
    1219             :   //     b.ne TrueBB
    1220             :   //     b EndBB
    1221             :   // TrueBB:
    1222             :   //     ; Fallthrough
    1223             :   // EndBB:
    1224             :   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
    1225             : 
    1226           3 :   MachineFunction *MF = MBB->getParent();
    1227           3 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    1228           3 :   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
    1229             :   DebugLoc DL = MI.getDebugLoc();
    1230           3 :   MachineFunction::iterator It = ++MBB->getIterator();
    1231             : 
    1232           3 :   unsigned DestReg = MI.getOperand(0).getReg();
    1233           3 :   unsigned IfTrueReg = MI.getOperand(1).getReg();
    1234           3 :   unsigned IfFalseReg = MI.getOperand(2).getReg();
    1235           3 :   unsigned CondCode = MI.getOperand(3).getImm();
    1236             :   bool NZCVKilled = MI.getOperand(4).isKill();
    1237             : 
    1238           3 :   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
    1239           3 :   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
    1240             :   MF->insert(It, TrueBB);
    1241             :   MF->insert(It, EndBB);
    1242             : 
    1243             :   // Transfer rest of current basic-block to EndBB
    1244             :   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
    1245             :                 MBB->end());
    1246           3 :   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
    1247             : 
    1248           3 :   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
    1249           3 :   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
    1250           3 :   MBB->addSuccessor(TrueBB);
    1251           3 :   MBB->addSuccessor(EndBB);
    1252             : 
    1253             :   // TrueBB falls through to the end.
    1254           3 :   TrueBB->addSuccessor(EndBB);
    1255             : 
    1256           3 :   if (!NZCVKilled) {
    1257             :     TrueBB->addLiveIn(AArch64::NZCV);
    1258             :     EndBB->addLiveIn(AArch64::NZCV);
    1259             :   }
    1260             : 
    1261           9 :   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
    1262           3 :       .addReg(IfTrueReg)
    1263             :       .addMBB(TrueBB)
    1264           3 :       .addReg(IfFalseReg)
    1265             :       .addMBB(MBB);
    1266             : 
    1267           3 :   MI.eraseFromParent();
    1268           3 :   return EndBB;
    1269             : }
    1270             : 
    1271          67 : MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
    1272             :     MachineInstr &MI, MachineBasicBlock *BB) const {
    1273         134 :   switch (MI.getOpcode()) {
    1274           0 :   default:
    1275             : #ifndef NDEBUG
    1276             :     MI.dump();
    1277             : #endif
    1278           0 :     llvm_unreachable("Unexpected instruction for custom inserter!");
    1279             : 
    1280           3 :   case AArch64::F128CSEL:
    1281           3 :     return EmitF128CSEL(MI, BB);
    1282             : 
    1283          64 :   case TargetOpcode::STACKMAP:
    1284             :   case TargetOpcode::PATCHPOINT:
    1285          64 :     return emitPatchPoint(MI, BB);
    1286             :   }
    1287             : }
    1288             : 
    1289             : //===----------------------------------------------------------------------===//
    1290             : // AArch64 Lowering private implementation.
    1291             : //===----------------------------------------------------------------------===//
    1292             : 
    1293             : //===----------------------------------------------------------------------===//
    1294             : // Lowering Code
    1295             : //===----------------------------------------------------------------------===//
    1296             : 
    1297             : /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
    1298             : /// CC
    1299        1092 : static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
    1300        1092 :   switch (CC) {
    1301           0 :   default:
    1302           0 :     llvm_unreachable("Unknown condition code!");
    1303             :   case ISD::SETNE:
    1304             :     return AArch64CC::NE;
    1305         214 :   case ISD::SETEQ:
    1306         214 :     return AArch64CC::EQ;
    1307          95 :   case ISD::SETGT:
    1308          95 :     return AArch64CC::GT;
    1309          63 :   case ISD::SETGE:
    1310          63 :     return AArch64CC::GE;
    1311         139 :   case ISD::SETLT:
    1312         139 :     return AArch64CC::LT;
    1313          77 :   case ISD::SETLE:
    1314          77 :     return AArch64CC::LE;
    1315          99 :   case ISD::SETUGT:
    1316          99 :     return AArch64CC::HI;
    1317          42 :   case ISD::SETUGE:
    1318          42 :     return AArch64CC::HS;
    1319          48 :   case ISD::SETULT:
    1320          48 :     return AArch64CC::LO;
    1321          70 :   case ISD::SETULE:
    1322          70 :     return AArch64CC::LS;
    1323             :   }
    1324             : }
    1325             : 
    1326             : /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
    1327         608 : static void changeFPCCToAArch64CC(ISD::CondCode CC,
    1328             :                                   AArch64CC::CondCode &CondCode,
    1329             :                                   AArch64CC::CondCode &CondCode2) {
    1330         608 :   CondCode2 = AArch64CC::AL;
    1331         608 :   switch (CC) {
    1332           0 :   default:
    1333           0 :     llvm_unreachable("Unknown FP condition!");
    1334          83 :   case ISD::SETEQ:
    1335             :   case ISD::SETOEQ:
    1336          83 :     CondCode = AArch64CC::EQ;
    1337          83 :     break;
    1338          48 :   case ISD::SETGT:
    1339             :   case ISD::SETOGT:
    1340          48 :     CondCode = AArch64CC::GT;
    1341          48 :     break;
    1342          50 :   case ISD::SETGE:
    1343             :   case ISD::SETOGE:
    1344          50 :     CondCode = AArch64CC::GE;
    1345          50 :     break;
    1346          66 :   case ISD::SETOLT:
    1347          66 :     CondCode = AArch64CC::MI;
    1348          66 :     break;
    1349          47 :   case ISD::SETOLE:
    1350          47 :     CondCode = AArch64CC::LS;
    1351          47 :     break;
    1352          45 :   case ISD::SETONE:
    1353          45 :     CondCode = AArch64CC::MI;
    1354          45 :     CondCode2 = AArch64CC::GT;
    1355          45 :     break;
    1356          27 :   case ISD::SETO:
    1357          27 :     CondCode = AArch64CC::VC;
    1358          27 :     break;
    1359          27 :   case ISD::SETUO:
    1360          27 :     CondCode = AArch64CC::VS;
    1361          27 :     break;
    1362          31 :   case ISD::SETUEQ:
    1363          31 :     CondCode = AArch64CC::EQ;
    1364          31 :     CondCode2 = AArch64CC::VS;
    1365          31 :     break;
    1366          27 :   case ISD::SETUGT:
    1367          27 :     CondCode = AArch64CC::HI;
    1368          27 :     break;
    1369          30 :   case ISD::SETUGE:
    1370          30 :     CondCode = AArch64CC::PL;
    1371          30 :     break;
    1372          29 :   case ISD::SETLT:
    1373             :   case ISD::SETULT:
    1374          29 :     CondCode = AArch64CC::LT;
    1375          29 :     break;
    1376          33 :   case ISD::SETLE:
    1377             :   case ISD::SETULE:
    1378          33 :     CondCode = AArch64CC::LE;
    1379          33 :     break;
    1380          65 :   case ISD::SETNE:
    1381             :   case ISD::SETUNE:
    1382          65 :     CondCode = AArch64CC::NE;
    1383          65 :     break;
    1384             :   }
    1385         608 : }
    1386             : 
    1387             : /// Convert a DAG fp condition code to an AArch64 CC.
    1388             : /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
    1389             : /// should be AND'ed instead of OR'ed.
    1390          28 : static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
    1391             :                                      AArch64CC::CondCode &CondCode,
    1392             :                                      AArch64CC::CondCode &CondCode2) {
    1393          28 :   CondCode2 = AArch64CC::AL;
    1394          28 :   switch (CC) {
    1395          17 :   default:
    1396          17 :     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
    1397             :     assert(CondCode2 == AArch64CC::AL);
    1398          17 :     break;
    1399           7 :   case ISD::SETONE:
    1400             :     // (a one b)
    1401             :     // == ((a olt b) || (a ogt b))
    1402             :     // == ((a ord b) && (a une b))
    1403           7 :     CondCode = AArch64CC::VC;
    1404           7 :     CondCode2 = AArch64CC::NE;
    1405           7 :     break;
    1406           4 :   case ISD::SETUEQ:
    1407             :     // (a ueq b)
    1408             :     // == ((a uno b) || (a oeq b))
    1409             :     // == ((a ule b) && (a uge b))
    1410           4 :     CondCode = AArch64CC::PL;
    1411           4 :     CondCode2 = AArch64CC::LE;
    1412           4 :     break;
    1413             :   }
    1414          28 : }
    1415             : 
    1416             : /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
    1417             : /// CC usable with the vector instructions. Fewer operations are available
    1418             : /// without a real NZCV register, so we have to use less efficient combinations
    1419             : /// to get the same effect.
    1420         149 : static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
    1421             :                                         AArch64CC::CondCode &CondCode,
    1422             :                                         AArch64CC::CondCode &CondCode2,
    1423             :                                         bool &Invert) {
    1424         149 :   Invert = false;
    1425         149 :   switch (CC) {
    1426          93 :   default:
    1427             :     // Mostly the scalar mappings work fine.
    1428          93 :     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
    1429          93 :     break;
    1430           8 :   case ISD::SETUO:
    1431           8 :     Invert = true;
    1432             :     LLVM_FALLTHROUGH;
    1433          16 :   case ISD::SETO:
    1434          16 :     CondCode = AArch64CC::MI;
    1435          16 :     CondCode2 = AArch64CC::GE;
    1436          16 :     break;
    1437          40 :   case ISD::SETUEQ:
    1438             :   case ISD::SETULT:
    1439             :   case ISD::SETULE:
    1440             :   case ISD::SETUGT:
    1441             :   case ISD::SETUGE:
    1442             :     // All of the compare-mask comparisons are ordered, but we can switch
    1443             :     // between the two by a double inversion. E.g. ULE == !OGT.
    1444          40 :     Invert = true;
    1445          40 :     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
    1446          40 :     break;
    1447             :   }
    1448         149 : }
    1449             : 
    1450             : static bool isLegalArithImmed(uint64_t C) {
    1451             :   // Matches AArch64DAGToDAGISel::SelectArithImmed().
    1452         448 :   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
    1453             :   LLVM_DEBUG(dbgs() << "Is imm " << C
    1454             :                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
    1455             :   return IsLegal;
    1456             : }
    1457             : 
    1458        1156 : static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
    1459             :                               const SDLoc &dl, SelectionDAG &DAG) {
    1460        1156 :   EVT VT = LHS.getValueType();
    1461             :   const bool FullFP16 =
    1462        2312 :     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
    1463             : 
    1464        1156 :   if (VT.isFloatingPoint()) {
    1465             :     assert(VT != MVT::f128);
    1466         198 :     if (VT == MVT::f16 && !FullFP16) {
    1467           3 :       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
    1468           3 :       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
    1469           3 :       VT = MVT::f32;
    1470             :     }
    1471         436 :     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
    1472             :   }
    1473             : 
    1474             :   // The CMP instruction is just an alias for SUBS, and representing it as
    1475             :   // SUBS means that it's possible to get CSE with subtract operations.
    1476             :   // A later phase can perform the optimization of setting the destination
    1477             :   // register to WZR/XZR if it ends up being unused.
    1478             :   unsigned Opcode = AArch64ISD::SUBS;
    1479             : 
    1480         736 :   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
    1481           8 :       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    1482             :     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
    1483             :     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
    1484             :     // can be set differently by this operation. It comes down to whether
    1485             :     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
    1486             :     // everything is fine. If not then the optimization is wrong. Thus general
    1487             :     // comparisons are only valid if op2 != 0.
    1488             : 
    1489             :     // So, finally, the only LLVM-native comparisons that don't mention C and V
    1490             :     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
    1491             :     // the absence of information about op2.
    1492             :     Opcode = AArch64ISD::ADDS;
    1493           6 :     RHS = RHS.getOperand(1);
    1494         800 :   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
    1495             :              !isUnsignedIntSetCC(CC)) {
    1496             :     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
    1497             :     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
    1498             :     // of the signed comparisons.
    1499             :     Opcode = AArch64ISD::ANDS;
    1500          34 :     RHS = LHS.getOperand(1);
    1501          34 :     LHS = LHS.getOperand(0);
    1502             :   }
    1503             : 
    1504        1440 :   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
    1505         720 :       .getValue(1);
    1506             : }
    1507             : 
    1508             : /// \defgroup AArch64CCMP CMP;CCMP matching
    1509             : ///
    1510             : /// These functions deal with the formation of CMP;CCMP;... sequences.
    1511             : /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
    1512             : /// a comparison. They set the NZCV flags to a predefined value if their
    1513             : /// predicate is false. This allows to express arbitrary conjunctions, for
    1514             : /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
    1515             : /// expressed as:
    1516             : ///   cmp A
    1517             : ///   ccmp B, inv(CB), CA
    1518             : ///   check for CB flags
    1519             : ///
    1520             : /// In general we can create code for arbitrary "... (and (and A B) C)"
    1521             : /// sequences. We can also implement some "or" expressions, because "(or A B)"
    1522             : /// is equivalent to "not (and (not A) (not B))" and we can implement some
    1523             : /// negation operations:
    1524             : /// We can negate the results of a single comparison by inverting the flags
    1525             : /// used when the predicate fails and inverting the flags tested in the next
    1526             : /// instruction; We can also negate the results of the whole previous
    1527             : /// conditional compare sequence by inverting the flags tested in the next
    1528             : /// instruction. However there is no way to negate the result of a partial
    1529             : /// sequence.
    1530             : ///
    1531             : /// Therefore on encountering an "or" expression we can negate the subtree on
    1532             : /// one side and have to be able to push the negate to the leafs of the subtree
    1533             : /// on the other side (see also the comments in code). As complete example:
    1534             : /// "or (or (setCA (cmp A)) (setCB (cmp B)))
    1535             : ///     (and (setCC (cmp C)) (setCD (cmp D)))"
    1536             : /// is transformed to
    1537             : /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
    1538             : ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
    1539             : /// and implemented as:
    1540             : ///   cmp C
    1541             : ///   ccmp D, inv(CD), CC
    1542             : ///   ccmp A, CA, inv(CD)
    1543             : ///   ccmp B, CB, inv(CA)
    1544             : ///   check for CB flags
    1545             : /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
    1546             : /// by conditional compare sequences.
    1547             : /// @{
    1548             : 
    1549             : /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
    1550          38 : static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
    1551             :                                          ISD::CondCode CC, SDValue CCOp,
    1552             :                                          AArch64CC::CondCode Predicate,
    1553             :                                          AArch64CC::CondCode OutCC,
    1554             :                                          const SDLoc &DL, SelectionDAG &DAG) {
    1555             :   unsigned Opcode = 0;
    1556             :   const bool FullFP16 =
    1557          76 :     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
    1558             : 
    1559          38 :   if (LHS.getValueType().isFloatingPoint()) {
    1560             :     assert(LHS.getValueType() != MVT::f128);
    1561           4 :     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
    1562           4 :       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
    1563           4 :       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
    1564             :     }
    1565             :     Opcode = AArch64ISD::FCCMP;
    1566          12 :   } else if (RHS.getOpcode() == ISD::SUB) {
    1567           0 :     SDValue SubOp0 = RHS.getOperand(0);
    1568           0 :     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    1569             :       // See emitComparison() on why we can only do this for SETEQ and SETNE.
    1570             :       Opcode = AArch64ISD::CCMN;
    1571           0 :       RHS = RHS.getOperand(1);
    1572             :     }
    1573             :   }
    1574             :   if (Opcode == 0)
    1575             :     Opcode = AArch64ISD::CCMP;
    1576             : 
    1577          38 :   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
    1578             :   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
    1579          38 :   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
    1580          38 :   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
    1581          38 :   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
    1582             : }
    1583             : 
    1584             : /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
    1585             : /// CanPushNegate is set to true if we can push a negate operation through
    1586             : /// the tree in a was that we are left with AND operations and negate operations
    1587             : /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
    1588             : /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
    1589             : /// brought into such a form.
    1590         234 : static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
    1591             :                                          unsigned Depth = 0) {
    1592         468 :   if (!Val.hasOneUse())
    1593             :     return false;
    1594         207 :   unsigned Opcode = Val->getOpcode();
    1595         207 :   if (Opcode == ISD::SETCC) {
    1596          75 :     if (Val->getOperand(0).getValueType() == MVT::f128)
    1597             :       return false;
    1598          74 :     CanNegate = true;
    1599             :     return true;
    1600             :   }
    1601             :   // Protect against exponential runtime and stack overflow.
    1602         132 :   if (Depth > 6)
    1603             :     return false;
    1604         132 :   if (Opcode == ISD::AND || Opcode == ISD::OR) {
    1605          59 :     SDValue O0 = Val->getOperand(0);
    1606          59 :     SDValue O1 = Val->getOperand(1);
    1607             :     bool CanNegateL;
    1608          59 :     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
    1609             :       return false;
    1610             :     bool CanNegateR;
    1611          34 :     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
    1612             :       return false;
    1613             : 
    1614          34 :     if (Opcode == ISD::OR) {
    1615             :       // For an OR expression we need to be able to negate at least one side or
    1616             :       // we cannot do the transformation at all.
    1617          21 :       if (!CanNegateL && !CanNegateR)
    1618             :         return false;
    1619             :       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
    1620             :       // can negate the x and y subtrees.
    1621          20 :       CanNegate = CanNegateL && CanNegateR;
    1622             :     } else {
    1623             :       // If the operands are OR expressions then we finally need to negate their
    1624             :       // outputs, we can only do that for the operand with emitted last by
    1625             :       // negating OutCC, not for both operands.
    1626          13 :       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
    1627          13 :       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
    1628          13 :       if (NeedsNegOutL && NeedsNegOutR)
    1629             :         return false;
    1630             :       // We cannot negate an AND operation (it would become an OR),
    1631          12 :       CanNegate = false;
    1632             :     }
    1633             :     return true;
    1634             :   }
    1635             :   return false;
    1636             : }
    1637             : 
    1638             : /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
    1639             : /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
    1640             : /// Tries to transform the given i1 producing node @p Val to a series compare
    1641             : /// and conditional compare operations. @returns an NZCV flags producing node
    1642             : /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
    1643             : /// transformation was not possible.
    1644             : /// On recursive invocations @p PushNegate may be set to true to have negation
    1645             : /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
    1646             : /// for the comparisons in the current subtree; @p Depth limits the search
    1647             : /// depth to avoid stack overflow.
    1648          75 : static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
    1649             :     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
    1650             :     AArch64CC::CondCode Predicate) {
    1651             :   // We're at a tree leaf, produce a conditional comparison operation.
    1652          75 :   unsigned Opcode = Val->getOpcode();
    1653          75 :   if (Opcode == ISD::SETCC) {
    1654          48 :     SDValue LHS = Val->getOperand(0);
    1655          48 :     SDValue RHS = Val->getOperand(1);
    1656          48 :     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
    1657          48 :     bool isInteger = LHS.getValueType().isInteger();
    1658          48 :     if (Negate)
    1659          17 :       CC = getSetCCInverse(CC, isInteger);
    1660             :     SDLoc DL(Val);
    1661             :     // Determine OutCC and handle FP special case.
    1662          48 :     if (isInteger) {
    1663          20 :       OutCC = changeIntCCToAArch64CC(CC);
    1664             :     } else {
    1665             :       assert(LHS.getValueType().isFloatingPoint());
    1666             :       AArch64CC::CondCode ExtraCC;
    1667          28 :       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
    1668             :       // Some floating point conditions can't be tested with a single condition
    1669             :       // code. Construct an additional comparison in this case.
    1670          28 :       if (ExtraCC != AArch64CC::AL) {
    1671             :         SDValue ExtraCmp;
    1672          11 :         if (!CCOp.getNode())
    1673           4 :           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
    1674             :         else
    1675           7 :           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
    1676             :                                                ExtraCC, DL, DAG);
    1677          11 :         CCOp = ExtraCmp;
    1678          11 :         Predicate = ExtraCC;
    1679             :       }
    1680             :     }
    1681             : 
    1682             :     // Produce a normal comparison if we are first in the chain
    1683          48 :     if (!CCOp)
    1684          17 :       return emitComparison(LHS, RHS, CC, DL, DAG);
    1685             :     // Otherwise produce a ccmp.
    1686             :     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
    1687          31 :                                      DAG);
    1688             :   }
    1689             :   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
    1690             :          "Valid conjunction/disjunction tree");
    1691             : 
    1692             :   // Check if both sides can be transformed.
    1693          27 :   SDValue LHS = Val->getOperand(0);
    1694          27 :   SDValue RHS = Val->getOperand(1);
    1695             : 
    1696             :   // In case of an OR we need to negate our operands and the result.
    1697             :   // (A v B) <=> not(not(A) ^ not(B))
    1698          27 :   bool NegateOpsAndResult = Opcode == ISD::OR;
    1699             :   // We can negate the results of all previous operations by inverting the
    1700             :   // predicate flags giving us a free negation for one side. The other side
    1701             :   // must be negatable by itself.
    1702          27 :   if (NegateOpsAndResult) {
    1703             :     // See which side we can negate.
    1704             :     bool CanNegateL;
    1705          17 :     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
    1706             :     assert(isValidL && "Valid conjunction/disjunction tree");
    1707             :     (void)isValidL;
    1708             : 
    1709             : #ifndef NDEBUG
    1710             :     bool CanNegateR;
    1711             :     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
    1712             :     assert(isValidR && "Valid conjunction/disjunction tree");
    1713             :     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
    1714             : #endif
    1715             : 
    1716             :     // Order the side which we cannot negate to RHS so we can emit it first.
    1717          17 :     if (!CanNegateL)
    1718             :       std::swap(LHS, RHS);
    1719             :   } else {
    1720          10 :     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
    1721             :     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
    1722             :            "Valid conjunction/disjunction tree");
    1723             :     // Order the side where we need to negate the output flags to RHS so it
    1724             :     // gets emitted first.
    1725          10 :     if (NeedsNegOutL)
    1726             :       std::swap(LHS, RHS);
    1727             :   }
    1728             : 
    1729             :   // Emit RHS. If we want to negate the tree we only need to push a negate
    1730             :   // through if we are already in a PushNegate case, otherwise we can negate
    1731             :   // the "flags to test" afterwards.
    1732             :   AArch64CC::CondCode RHSCC;
    1733             :   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
    1734          27 :                                                    CCOp, Predicate);
    1735          27 :   if (NegateOpsAndResult && !Negate)
    1736          32 :     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
    1737             :   // Emit LHS. We may need to negate it.
    1738             :   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
    1739             :                                                    NegateOpsAndResult, CmpR,
    1740          27 :                                                    RHSCC);
    1741             :   // If we transformed an OR to and AND then we have to negate the result
    1742             :   // (or absorb the Negate parameter).
    1743          27 :   if (NegateOpsAndResult && !Negate)
    1744          32 :     OutCC = AArch64CC::getInvertedCondCode(OutCC);
    1745          27 :   return CmpL;
    1746             : }
    1747             : 
    1748             : /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
    1749             : /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
    1750             : /// \see emitConjunctionDisjunctionTreeRec().
    1751         124 : static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
    1752             :                                               AArch64CC::CondCode &OutCC) {
    1753             :   bool CanNegate;
    1754         124 :   if (!isConjunctionDisjunctionTree(Val, CanNegate))
    1755         103 :     return SDValue();
    1756             : 
    1757             :   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
    1758          21 :                                            AArch64CC::AL);
    1759             : }
    1760             : 
    1761             : /// @}
    1762             : 
    1763         727 : static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
    1764             :                              SDValue &AArch64cc, SelectionDAG &DAG,
    1765             :                              const SDLoc &dl) {
    1766             :   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
    1767         428 :     EVT VT = RHS.getValueType();
    1768         428 :     uint64_t C = RHSC->getZExtValue();
    1769             :     if (!isLegalArithImmed(C)) {
    1770             :       // Constant does not fit, try adjusting it by one?
    1771          30 :       switch (CC) {
    1772             :       default:
    1773             :         break;
    1774             :       case ISD::SETLT:
    1775             :       case ISD::SETGE:
    1776           4 :         if ((VT == MVT::i32 && C != 0x80000000 &&
    1777           4 :              isLegalArithImmed((uint32_t)(C - 1))) ||
    1778           0 :             (VT == MVT::i64 && C != 0x80000000ULL &&
    1779           0 :              isLegalArithImmed(C - 1ULL))) {
    1780           0 :           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
    1781           0 :           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
    1782           0 :           RHS = DAG.getConstant(C, dl, VT);
    1783             :         }
    1784             :         break;
    1785             :       case ISD::SETULT:
    1786             :       case ISD::SETUGE:
    1787           1 :         if ((VT == MVT::i32 && C != 0 &&
    1788           1 :              isLegalArithImmed((uint32_t)(C - 1))) ||
    1789           0 :             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
    1790           0 :           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
    1791           0 :           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
    1792           0 :           RHS = DAG.getConstant(C, dl, VT);
    1793             :         }
    1794             :         break;
    1795             :       case ISD::SETLE:
    1796             :       case ISD::SETGT:
    1797           7 :         if ((VT == MVT::i32 && C != INT32_MAX &&
    1798           7 :              isLegalArithImmed((uint32_t)(C + 1))) ||
    1799           3 :             (VT == MVT::i64 && C != INT64_MAX &&
    1800           3 :              isLegalArithImmed(C + 1ULL))) {
    1801           4 :           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
    1802           2 :           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
    1803           4 :           RHS = DAG.getConstant(C, dl, VT);
    1804             :         }
    1805             :         break;
    1806             :       case ISD::SETULE:
    1807             :       case ISD::SETUGT:
    1808           3 :         if ((VT == MVT::i32 && C != UINT32_MAX &&
    1809           3 :              isLegalArithImmed((uint32_t)(C + 1))) ||
    1810           2 :             (VT == MVT::i64 && C != UINT64_MAX &&
    1811           0 :              isLegalArithImmed(C + 1ULL))) {
    1812           0 :           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
    1813           0 :           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
    1814           0 :           RHS = DAG.getConstant(C, dl, VT);
    1815             :         }
    1816             :         break;
    1817             :       }
    1818             :     }
    1819             :   }
    1820             :   SDValue Cmp;
    1821             :   AArch64CC::CondCode AArch64CC;
    1822         727 :   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
    1823             :     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
    1824             : 
    1825             :     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
    1826             :     // For the i8 operand, the largest immediate is 255, so this can be easily
    1827             :     // encoded in the compare instruction. For the i16 operand, however, the
    1828             :     // largest immediate cannot be encoded in the compare.
    1829             :     // Therefore, use a sign extending load and cmn to avoid materializing the
    1830             :     // -1 constant. For example,
    1831             :     // movz w1, #65535
    1832             :     // ldrh w0, [x0, #0]
    1833             :     // cmp w0, w1
    1834             :     // >
    1835             :     // ldrsh w0, [x0, #0]
    1836             :     // cmn w0, #1
    1837             :     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
    1838             :     // if and only if (sext LHS) == (sext RHS). The checks are in place to
    1839             :     // ensure both the LHS and RHS are truly zero extended and to make sure the
    1840             :     // transformation is profitable.
    1841         667 :     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
    1842             :         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
    1843         223 :         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
    1844           2 :         LHS.getNode()->hasNUsesOfValue(1, 0)) {
    1845           4 :       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
    1846           2 :       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
    1847             :         SDValue SExt =
    1848             :             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
    1849           4 :                         DAG.getValueType(MVT::i16));
    1850           2 :         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
    1851             :                                                    RHS.getValueType()),
    1852           2 :                              CC, dl, DAG);
    1853           2 :         AArch64CC = changeIntCCToAArch64CC(CC);
    1854             :       }
    1855             :     }
    1856             : 
    1857         561 :     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
    1858         124 :       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
    1859          42 :         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
    1860           2 :           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
    1861             :       }
    1862             :     }
    1863             :   }
    1864             : 
    1865         727 :   if (!Cmp) {
    1866         704 :     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    1867         704 :     AArch64CC = changeIntCCToAArch64CC(CC);
    1868             :   }
    1869         727 :   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
    1870         727 :   return Cmp;
    1871             : }
    1872             : 
    1873             : static std::pair<SDValue, SDValue>
    1874          74 : getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
    1875             :   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
    1876             :          "Unsupported value type");
    1877             :   SDValue Value, Overflow;
    1878             :   SDLoc DL(Op);
    1879          74 :   SDValue LHS = Op.getOperand(0);
    1880          74 :   SDValue RHS = Op.getOperand(1);
    1881             :   unsigned Opc = 0;
    1882          74 :   switch (Op.getOpcode()) {
    1883           0 :   default:
    1884           0 :     llvm_unreachable("Unknown overflow instruction!");
    1885          19 :   case ISD::SADDO:
    1886             :     Opc = AArch64ISD::ADDS;
    1887          19 :     CC = AArch64CC::VS;
    1888             :     break;
    1889          13 :   case ISD::UADDO:
    1890             :     Opc = AArch64ISD::ADDS;
    1891          13 :     CC = AArch64CC::HS;
    1892             :     break;
    1893          11 :   case ISD::SSUBO:
    1894             :     Opc = AArch64ISD::SUBS;
    1895          11 :     CC = AArch64CC::VS;
    1896             :     break;
    1897          10 :   case ISD::USUBO:
    1898             :     Opc = AArch64ISD::SUBS;
    1899          10 :     CC = AArch64CC::LO;
    1900             :     break;
    1901             :   // Multiply needs a little bit extra work.
    1902          21 :   case ISD::SMULO:
    1903             :   case ISD::UMULO: {
    1904          21 :     CC = AArch64CC::NE;
    1905             :     bool IsSigned = Op.getOpcode() == ISD::SMULO;
    1906             :     if (Op.getValueType() == MVT::i32) {
    1907          10 :       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    1908             :       // For a 32 bit multiply with overflow check we want the instruction
    1909             :       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
    1910             :       // need to generate the following pattern:
    1911             :       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
    1912          10 :       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
    1913          10 :       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
    1914          10 :       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
    1915             :       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
    1916          20 :                                 DAG.getConstant(0, DL, MVT::i64));
    1917             :       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
    1918             :       // operation. We need to clear out the upper 32 bits, because we used a
    1919             :       // widening multiply that wrote all 64 bits. In the end this should be a
    1920             :       // noop.
    1921          10 :       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
    1922          10 :       if (IsSigned) {
    1923             :         // The signed overflow check requires more than just a simple check for
    1924             :         // any bit set in the upper 32 bits of the result. These bits could be
    1925             :         // just the sign bits of a negative number. To perform the overflow
    1926             :         // check we have to arithmetic shift right the 32nd bit of the result by
    1927             :         // 31 bits. Then we compare the result to the upper 32 bits.
    1928             :         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
    1929          10 :                                         DAG.getConstant(32, DL, MVT::i64));
    1930           5 :         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
    1931             :         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
    1932          10 :                                         DAG.getConstant(31, DL, MVT::i64));
    1933             :         // It is important that LowerBits is last, otherwise the arithmetic
    1934             :         // shift will not be folded into the compare (SUBS).
    1935           5 :         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
    1936          10 :         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
    1937           5 :                        .getValue(1);
    1938             :       } else {
    1939             :         // The overflow check for unsigned multiply is easy. We only need to
    1940             :         // check if any of the upper 32 bits are set. This can be done with a
    1941             :         // CMP (shifted register). For that we need to generate the following
    1942             :         // pattern:
    1943             :         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
    1944             :         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
    1945          10 :                                         DAG.getConstant(32, DL, MVT::i64));
    1946           5 :         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1947             :         Overflow =
    1948          10 :             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
    1949             :                         DAG.getConstant(0, DL, MVT::i64),
    1950          15 :                         UpperBits).getValue(1);
    1951             :       }
    1952             :       break;
    1953             :     }
    1954             :     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
    1955             :     // For the 64 bit multiply
    1956          11 :     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
    1957          11 :     if (IsSigned) {
    1958           5 :       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
    1959             :       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
    1960          10 :                                       DAG.getConstant(63, DL, MVT::i64));
    1961             :       // It is important that LowerBits is last, otherwise the arithmetic
    1962             :       // shift will not be folded into the compare (SUBS).
    1963           5 :       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1964          10 :       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
    1965           5 :                      .getValue(1);
    1966             :     } else {
    1967           6 :       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
    1968           6 :       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1969             :       Overflow =
    1970          12 :           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
    1971             :                       DAG.getConstant(0, DL, MVT::i64),
    1972          18 :                       UpperBits).getValue(1);
    1973             :     }
    1974             :     break;
    1975             :   }
    1976             :   } // switch (...)
    1977             : 
    1978             :   if (Opc) {
    1979         106 :     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
    1980             : 
    1981             :     // Emit the AArch64 operation with overflow check.
    1982          53 :     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
    1983             :     Overflow = Value.getValue(1);
    1984             :   }
    1985          74 :   return std::make_pair(Value, Overflow);
    1986             : }
    1987             : 
    1988          93 : SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
    1989             :                                              RTLIB::Libcall Call) const {
    1990          93 :   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
    1991         372 :   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
    1992             : }
    1993             : 
    1994             : // Returns true if the given Op is the overflow flag result of an overflow
    1995             : // intrinsic operation.
    1996             : static bool isOverflowIntrOpRes(SDValue Op) {
    1997             :   unsigned Opc = Op.getOpcode();
    1998        1396 :   return (Op.getResNo() == 1 &&
    1999             :           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    2000          51 :            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
    2001             : }
    2002             : 
    2003         903 : static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
    2004         903 :   SDValue Sel = Op.getOperand(0);
    2005         903 :   SDValue Other = Op.getOperand(1);
    2006             :   SDLoc dl(Sel);
    2007             : 
    2008             :   // If the operand is an overflow checking operation, invert the condition
    2009             :   // code and kill the Not operation. I.e., transform:
    2010             :   // (xor (overflow_op_bool, 1))
    2011             :   //   -->
    2012             :   // (csel 1, 0, invert(cc), overflow_op_bool)
    2013             :   // ... which later gets transformed to just a cset instruction with an
    2014             :   // inverted condition code, rather than a cset + eor sequence.
    2015         903 :   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
    2016             :     // Only lower legal XALUO ops.
    2017          24 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
    2018           0 :       return SDValue();
    2019             : 
    2020          24 :     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
    2021          24 :     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
    2022             :     AArch64CC::CondCode CC;
    2023             :     SDValue Value, Overflow;
    2024          48 :     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
    2025          48 :     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
    2026             :     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
    2027          24 :                        CCVal, Overflow);
    2028             :   }
    2029             :   // If neither operand is a SELECT_CC, give up.
    2030         879 :   if (Sel.getOpcode() != ISD::SELECT_CC)
    2031             :     std::swap(Sel, Other);
    2032         879 :   if (Sel.getOpcode() != ISD::SELECT_CC)
    2033         878 :     return Op;
    2034             : 
    2035             :   // The folding we want to perform is:
    2036             :   // (xor x, (select_cc a, b, cc, 0, -1) )
    2037             :   //   -->
    2038             :   // (csel x, (xor x, -1), cc ...)
    2039             :   //
    2040             :   // The latter will get matched to a CSINV instruction.
    2041             : 
    2042           1 :   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
    2043           1 :   SDValue LHS = Sel.getOperand(0);
    2044           1 :   SDValue RHS = Sel.getOperand(1);
    2045           1 :   SDValue TVal = Sel.getOperand(2);
    2046           1 :   SDValue FVal = Sel.getOperand(3);
    2047             : 
    2048             :   // FIXME: This could be generalized to non-integer comparisons.
    2049             :   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
    2050           0 :     return Op;
    2051             : 
    2052             :   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
    2053             :   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
    2054             : 
    2055             :   // The values aren't constants, this isn't the pattern we're looking for.
    2056           1 :   if (!CFVal || !CTVal)
    2057           0 :     return Op;
    2058             : 
    2059             :   // We can commute the SELECT_CC by inverting the condition.  This
    2060             :   // might be needed to make this fit into a CSINV pattern.
    2061           3 :   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
    2062             :     std::swap(TVal, FVal);
    2063             :     std::swap(CTVal, CFVal);
    2064           1 :     CC = ISD::getSetCCInverse(CC, true);
    2065             :   }
    2066             : 
    2067             :   // If the constants line up, perform the transform!
    2068           3 :   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
    2069           1 :     SDValue CCVal;
    2070           1 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    2071             : 
    2072             :     FVal = Other;
    2073           1 :     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
    2074           2 :                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
    2075             : 
    2076             :     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
    2077           1 :                        CCVal, Cmp);
    2078             :   }
    2079             : 
    2080           0 :   return Op;
    2081             : }
    2082             : 
    2083          48 : static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
    2084          48 :   EVT VT = Op.getValueType();
    2085             : 
    2086             :   // Let legalize expand this if it isn't a legal type yet.
    2087          48 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
    2088           0 :     return SDValue();
    2089             : 
    2090          48 :   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
    2091             : 
    2092             :   unsigned Opc;
    2093             :   bool ExtraOp = false;
    2094          48 :   switch (Op.getOpcode()) {
    2095           0 :   default:
    2096           0 :     llvm_unreachable("Invalid code");
    2097             :   case ISD::ADDC:
    2098             :     Opc = AArch64ISD::ADDS;
    2099             :     break;
    2100           3 :   case ISD::SUBC:
    2101             :     Opc = AArch64ISD::SUBS;
    2102             :     break;
    2103          23 :   case ISD::ADDE:
    2104             :     Opc = AArch64ISD::ADCS;
    2105             :     ExtraOp = true;
    2106             :     break;
    2107           3 :   case ISD::SUBE:
    2108             :     Opc = AArch64ISD::SBCS;
    2109             :     ExtraOp = true;
    2110             :     break;
    2111             :   }
    2112             : 
    2113          48 :   if (!ExtraOp)
    2114          44 :     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
    2115          26 :   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
    2116          26 :                      Op.getOperand(2));
    2117             : }
    2118             : 
    2119          23 : static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
    2120             :   // Let legalize expand this if it isn't a legal type yet.
    2121          23 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
    2122           0 :     return SDValue();
    2123             : 
    2124             :   SDLoc dl(Op);
    2125             :   AArch64CC::CondCode CC;
    2126             :   // The actual operation that sets the overflow or carry flag.
    2127             :   SDValue Value, Overflow;
    2128          46 :   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
    2129             : 
    2130             :   // We use 0 and 1 as false and true values.
    2131          23 :   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
    2132          23 :   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
    2133             : 
    2134             :   // We use an inverted condition, because the conditional select is inverted
    2135             :   // too. This will allow it to be selected to a single instruction:
    2136             :   // CSINC Wd, WZR, WZR, invert(cond).
    2137          46 :   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
    2138          23 :   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
    2139          23 :                          CCVal, Overflow);
    2140             : 
    2141          23 :   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
    2142          23 :   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
    2143             : }
    2144             : 
    2145             : // Prefetch operands are:
    2146             : // 1: Address to prefetch
    2147             : // 2: bool isWrite
    2148             : // 3: int locality (0 = no locality ... 3 = extreme locality)
    2149             : // 4: bool isDataCache
    2150          24 : static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
    2151             :   SDLoc DL(Op);
    2152          48 :   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
    2153          48 :   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
    2154          48 :   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
    2155             : 
    2156          24 :   bool IsStream = !Locality;
    2157             :   // When the locality number is set
    2158          24 :   if (Locality) {
    2159             :     // The front-end should have filtered out the out-of-range values
    2160             :     assert(Locality <= 3 && "Prefetch locality out-of-range");
    2161             :     // The locality degree is the opposite of the cache speed.
    2162             :     // Put the number the other way around.
    2163             :     // The encoding starts at 0 for level 1
    2164          18 :     Locality = 3 - Locality;
    2165             :   }
    2166             : 
    2167             :   // built the mask value encoding the expected behavior.
    2168          72 :   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
    2169          48 :                    (!IsData << 3) |     // IsDataCache bit
    2170          24 :                    (Locality << 1) |    // Cache level bits
    2171          24 :                    (unsigned)IsStream;  // Stream bit
    2172             :   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
    2173          72 :                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
    2174             : }
    2175             : 
    2176           2 : SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
    2177             :                                               SelectionDAG &DAG) const {
    2178             :   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
    2179             : 
    2180             :   RTLIB::Libcall LC;
    2181           6 :   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
    2182             : 
    2183           2 :   return LowerF128Call(Op, DAG, LC);
    2184             : }
    2185             : 
    2186          36 : SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
    2187             :                                              SelectionDAG &DAG) const {
    2188          36 :   if (Op.getOperand(0).getValueType() != MVT::f128) {
    2189             :     // It's legal except when f128 is involved
    2190          31 :     return Op;
    2191             :   }
    2192             : 
    2193             :   RTLIB::Libcall LC;
    2194          10 :   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
    2195             : 
    2196             :   // FP_ROUND node has a second operand indicating whether it is known to be
    2197             :   // precise. That doesn't take part in the LibCall so we can't directly use
    2198             :   // LowerF128Call.
    2199           5 :   SDValue SrcVal = Op.getOperand(0);
    2200          10 :   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
    2201          20 :                      SDLoc(Op)).first;
    2202             : }
    2203             : 
    2204         240 : static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
    2205             :   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
    2206             :   // Any additional optimization in this function should be recorded
    2207             :   // in the cost tables.
    2208         480 :   EVT InVT = Op.getOperand(0).getValueType();
    2209         240 :   EVT VT = Op.getValueType();
    2210         240 :   unsigned NumElts = InVT.getVectorNumElements();
    2211             : 
    2212             :   // f16 vectors are promoted to f32 before a conversion.
    2213         480 :   if (InVT.getVectorElementType() == MVT::f16) {
    2214          16 :     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
    2215             :     SDLoc dl(Op);
    2216             :     return DAG.getNode(
    2217             :         Op.getOpcode(), dl, Op.getValueType(),
    2218          32 :         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
    2219             :   }
    2220             : 
    2221         224 :   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
    2222             :     SDLoc dl(Op);
    2223             :     SDValue Cv =
    2224             :         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
    2225          72 :                     Op.getOperand(0));
    2226          36 :     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
    2227             :   }
    2228             : 
    2229         188 :   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
    2230             :     SDLoc dl(Op);
    2231             :     MVT ExtVT =
    2232             :         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
    2233           6 :                          VT.getVectorNumElements());
    2234           3 :     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
    2235           3 :     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
    2236             :   }
    2237             : 
    2238             :   // Type changing conversions are illegal.
    2239         185 :   return Op;
    2240             : }
    2241             : 
    2242         461 : SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
    2243             :                                               SelectionDAG &DAG) const {
    2244        1383 :   if (Op.getOperand(0).getValueType().isVector())
    2245         240 :     return LowerVectorFP_TO_INT(Op, DAG);
    2246             : 
    2247             :   // f16 conversions are promoted to f32 when full fp16 is not supported.
    2248          23 :   if (Op.getOperand(0).getValueType() == MVT::f16 &&
    2249          23 :       !Subtarget->hasFullFP16()) {
    2250             :     SDLoc dl(Op);
    2251             :     return DAG.getNode(
    2252             :         Op.getOpcode(), dl, Op.getValueType(),
    2253          14 :         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
    2254             :   }
    2255             : 
    2256             :   if (Op.getOperand(0).getValueType() != MVT::f128) {
    2257             :     // It's legal except when f128 is involved
    2258         202 :     return Op;
    2259             :   }
    2260             : 
    2261             :   RTLIB::Libcall LC;
    2262          12 :   if (Op.getOpcode() == ISD::FP_TO_SINT)
    2263          10 :     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
    2264             :   else
    2265          14 :     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
    2266             : 
    2267          12 :   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
    2268          36 :   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
    2269             : }
    2270             : 
    2271         431 : static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
    2272             :   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
    2273             :   // Any additional optimization in this function should be recorded
    2274             :   // in the cost tables.
    2275         431 :   EVT VT = Op.getValueType();
    2276             :   SDLoc dl(Op);
    2277         431 :   SDValue In = Op.getOperand(0);
    2278         431 :   EVT InVT = In.getValueType();
    2279             : 
    2280         431 :   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
    2281             :     MVT CastVT =
    2282             :         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
    2283         180 :                          InVT.getVectorNumElements());
    2284          90 :     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
    2285          90 :     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
    2286             :   }
    2287             : 
    2288         341 :   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
    2289             :     unsigned CastOpc =
    2290           9 :         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    2291           9 :     EVT CastVT = VT.changeVectorElementTypeToInteger();
    2292           9 :     In = DAG.getNode(CastOpc, dl, CastVT, In);
    2293           9 :     return DAG.getNode(Op.getOpcode(), dl, VT, In);
    2294             :   }
    2295             : 
    2296         332 :   return Op;
    2297             : }
    2298             : 
    2299         721 : SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
    2300             :                                             SelectionDAG &DAG) const {
    2301        1442 :   if (Op.getValueType().isVector())
    2302         431 :     return LowerVectorINT_TO_FP(Op, DAG);
    2303             : 
    2304             :   // f16 conversions are promoted to f32 when full fp16 is not supported.
    2305          34 :   if (Op.getValueType() == MVT::f16 &&
    2306          34 :       !Subtarget->hasFullFP16()) {
    2307             :     SDLoc dl(Op);
    2308             :     return DAG.getNode(
    2309             :         ISD::FP_ROUND, dl, MVT::f16,
    2310             :         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
    2311          48 :         DAG.getIntPtrConstant(0, dl));
    2312             :   }
    2313             : 
    2314             :   // i128 conversions are libcalls.
    2315         274 :   if (Op.getOperand(0).getValueType() == MVT::i128)
    2316           6 :     return SDValue();
    2317             : 
    2318             :   // Other conversions are legal, unless it's to the completely software-based
    2319             :   // fp128.
    2320             :   if (Op.getValueType() != MVT::f128)
    2321         262 :     return Op;
    2322             : 
    2323             :   RTLIB::Libcall LC;
    2324           6 :   if (Op.getOpcode() == ISD::SINT_TO_FP)
    2325           4 :     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
    2326             :   else
    2327           8 :     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
    2328             : 
    2329           6 :   return LowerF128Call(Op, DAG, LC);
    2330             : }
    2331             : 
    2332           2 : SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
    2333             :                                             SelectionDAG &DAG) const {
    2334             :   // For iOS, we want to call an alternative entry point: __sincos_stret,
    2335             :   // which returns the values in two S / D registers.
    2336             :   SDLoc dl(Op);
    2337           2 :   SDValue Arg = Op.getOperand(0);
    2338           2 :   EVT ArgVT = Arg.getValueType();
    2339           2 :   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
    2340             : 
    2341             :   ArgListTy Args;
    2342             :   ArgListEntry Entry;
    2343             : 
    2344           2 :   Entry.Node = Arg;
    2345           2 :   Entry.Ty = ArgTy;
    2346             :   Entry.IsSExt = false;
    2347             :   Entry.IsZExt = false;
    2348           2 :   Args.push_back(Entry);
    2349             : 
    2350             :   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
    2351             :                                         : RTLIB::SINCOS_STRET_F32;
    2352             :   const char *LibcallName = getLibcallName(LC);
    2353             :   SDValue Callee =
    2354           4 :       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
    2355             : 
    2356           2 :   StructType *RetTy = StructType::get(ArgTy, ArgTy);
    2357           4 :   TargetLowering::CallLoweringInfo CLI(DAG);
    2358             :   CLI.setDebugLoc(dl)
    2359             :       .setChain(DAG.getEntryNode())
    2360           2 :       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
    2361             : 
    2362           2 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    2363           4 :   return CallResult.first;
    2364             : }
    2365             : 
    2366           8 : static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
    2367             :   if (Op.getValueType() != MVT::f16)
    2368           0 :     return SDValue();
    2369             : 
    2370             :   assert(Op.getOperand(0).getValueType() == MVT::i16);
    2371             :   SDLoc DL(Op);
    2372             : 
    2373           8 :   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
    2374           8 :   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
    2375             :   return SDValue(
    2376          16 :       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
    2377             :                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
    2378           8 :       0);
    2379             : }
    2380             : 
    2381           0 : static EVT getExtensionTo64Bits(const EVT &OrigVT) {
    2382           0 :   if (OrigVT.getSizeInBits() >= 64)
    2383           0 :     return OrigVT;
    2384             : 
    2385             :   assert(OrigVT.isSimple() && "Expecting a simple value type");
    2386             : 
    2387             :   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
    2388           0 :   switch (OrigSimpleTy) {
    2389           0 :   default: llvm_unreachable("Unexpected Vector Type");
    2390             :   case MVT::v2i8:
    2391             :   case MVT::v2i16:
    2392           0 :      return MVT::v2i32;
    2393             :   case MVT::v4i8:
    2394           0 :     return  MVT::v4i16;
    2395             :   }
    2396             : }
    2397             : 
    2398          45 : static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
    2399             :                                                  const EVT &OrigTy,
    2400             :                                                  const EVT &ExtTy,
    2401             :                                                  unsigned ExtOpcode) {
    2402             :   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
    2403             :   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
    2404             :   // 64-bits we need to insert a new extension so that it will be 64-bits.
    2405             :   assert(ExtTy.is128BitVector() && "Unexpected extension size");
    2406          45 :   if (OrigTy.getSizeInBits() >= 64)
    2407          45 :     return N;
    2408             : 
    2409             :   // Must extend size to at least 64 bits to be used as an operand for VMULL.
    2410           0 :   EVT NewVT = getExtensionTo64Bits(OrigTy);
    2411             : 
    2412           0 :   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
    2413             : }
    2414             : 
    2415        1568 : static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
    2416             :                                    bool isSigned) {
    2417        3136 :   EVT VT = N->getValueType(0);
    2418             : 
    2419        1568 :   if (N->getOpcode() != ISD::BUILD_VECTOR)
    2420             :     return false;
    2421             : 
    2422         155 :   for (const SDValue &Elt : N->op_values()) {
    2423             :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
    2424             :       unsigned EltSize = VT.getScalarSizeInBits();
    2425         104 :       unsigned HalfSize = EltSize / 2;
    2426         104 :       if (isSigned) {
    2427          52 :         if (!isIntN(HalfSize, C->getSExtValue()))
    2428             :           return false;
    2429             :       } else {
    2430          52 :         if (!isUIntN(HalfSize, C->getZExtValue()))
    2431             :           return false;
    2432             :       }
    2433          90 :       continue;
    2434             :     }
    2435             :     return false;
    2436             :   }
    2437             : 
    2438             :   return true;
    2439             : }
    2440             : 
    2441          51 : static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
    2442         102 :   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
    2443             :     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
    2444         135 :                                              N->getOperand(0)->getValueType(0),
    2445             :                                              N->getValueType(0),
    2446          45 :                                              N->getOpcode());
    2447             : 
    2448             :   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
    2449          12 :   EVT VT = N->getValueType(0);
    2450             :   SDLoc dl(N);
    2451           6 :   unsigned EltSize = VT.getScalarSizeInBits() / 2;
    2452           6 :   unsigned NumElts = VT.getVectorNumElements();
    2453           6 :   MVT TruncVT = MVT::getIntegerVT(EltSize);
    2454             :   SmallVector<SDValue, 8> Ops;
    2455          62 :   for (unsigned i = 0; i != NumElts; ++i) {
    2456          28 :     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
    2457          28 :     const APInt &CInt = C->getAPIntValue();
    2458             :     // Element types smaller than 32 bits are not legal, so use i32 elements.
    2459             :     // The values are implicitly truncated so sext vs. zext doesn't matter.
    2460          56 :     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
    2461             :   }
    2462          12 :   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
    2463             : }
    2464             : 
    2465             : static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
    2466        1245 :   return N->getOpcode() == ISD::SIGN_EXTEND ||
    2467         798 :          isExtendedBUILD_VECTOR(N, DAG, true);
    2468             : }
    2469             : 
    2470             : static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
    2471        1200 :   return N->getOpcode() == ISD::ZERO_EXTEND ||
    2472         770 :          isExtendedBUILD_VECTOR(N, DAG, false);
    2473             : }
    2474             : 
    2475           4 : static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
    2476           4 :   unsigned Opcode = N->getOpcode();
    2477           4 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    2478           4 :     SDNode *N0 = N->getOperand(0).getNode();
    2479           4 :     SDNode *N1 = N->getOperand(1).getNode();
    2480             :     return N0->hasOneUse() && N1->hasOneUse() &&
    2481             :       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
    2482             :   }
    2483             :   return false;
    2484             : }
    2485             : 
    2486           7 : static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
    2487           7 :   unsigned Opcode = N->getOpcode();
    2488           7 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    2489           5 :     SDNode *N0 = N->getOperand(0).getNode();
    2490           5 :     SDNode *N1 = N->getOperand(1).getNode();
    2491             :     return N0->hasOneUse() && N1->hasOneUse() &&
    2492             :       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
    2493             :   }
    2494             :   return false;
    2495             : }
    2496             : 
    2497         384 : static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
    2498             :   // Multiplications are only custom-lowered for 128-bit vectors so that
    2499             :   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
    2500         384 :   EVT VT = Op.getValueType();
    2501             :   assert(VT.is128BitVector() && VT.isInteger() &&
    2502             :          "unexpected type for custom-lowering ISD::MUL");
    2503         384 :   SDNode *N0 = Op.getOperand(0).getNode();
    2504         384 :   SDNode *N1 = Op.getOperand(1).getNode();
    2505             :   unsigned NewOpc = 0;
    2506             :   bool isMLA = false;
    2507             :   bool isN0SExt = isSignExtended(N0, DAG);
    2508             :   bool isN1SExt = isSignExtended(N1, DAG);
    2509         384 :   if (isN0SExt && isN1SExt)
    2510             :     NewOpc = AArch64ISD::SMULL;
    2511             :   else {
    2512             :     bool isN0ZExt = isZeroExtended(N0, DAG);
    2513             :     bool isN1ZExt = isZeroExtended(N1, DAG);
    2514         372 :     if (isN0ZExt && isN1ZExt)
    2515             :       NewOpc = AArch64ISD::UMULL;
    2516         360 :     else if (isN1SExt || isN1ZExt) {
    2517             :       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
    2518             :       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
    2519           7 :       if (isN1SExt && isAddSubSExt(N0, DAG)) {
    2520             :         NewOpc = AArch64ISD::SMULL;
    2521             :         isMLA = true;
    2522           7 :       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
    2523             :         NewOpc =  AArch64ISD::UMULL;
    2524             :         isMLA = true;
    2525           6 :       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
    2526             :         std::swap(N0, N1);
    2527             :         NewOpc =  AArch64ISD::UMULL;
    2528             :         isMLA = true;
    2529             :       }
    2530             :     }
    2531             : 
    2532         372 :     if (!NewOpc) {
    2533             :       if (VT == MVT::v2i64)
    2534             :         // Fall through to expand this.  It is not legal.
    2535           2 :         return SDValue();
    2536             :       else
    2537             :         // Other vector multiplications are legal.
    2538         357 :         return Op;
    2539             :     }
    2540             :   }
    2541             : 
    2542             :   // Legalize to a S/UMULL instruction
    2543             :   SDLoc DL(Op);
    2544          25 :   SDValue Op0;
    2545          25 :   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
    2546          25 :   if (!isMLA) {
    2547          24 :     Op0 = skipExtensionForVectorMULL(N0, DAG);
    2548             :     assert(Op0.getValueType().is64BitVector() &&
    2549             :            Op1.getValueType().is64BitVector() &&
    2550             :            "unexpected types for extended operands to VMULL");
    2551          24 :     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
    2552             :   }
    2553             :   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
    2554             :   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
    2555             :   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
    2556           1 :   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
    2557           1 :   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
    2558           2 :   EVT Op1VT = Op1.getValueType();
    2559             :   return DAG.getNode(N0->getOpcode(), DL, VT,
    2560             :                      DAG.getNode(NewOpc, DL, VT,
    2561             :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
    2562             :                      DAG.getNode(NewOpc, DL, VT,
    2563           3 :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
    2564             : }
    2565             : 
    2566             : // Lower vector multiply high (ISD::MULHS and ISD::MULHU).
    2567           8 : static SDValue LowerMULH(SDValue Op, SelectionDAG &DAG) {
    2568             :   // Multiplications are only custom-lowered for 128-bit vectors so that
    2569             :   // {S,U}MULL{2} can be detected.  Otherwise v2i64 multiplications are not
    2570             :   // legal.
    2571           8 :   EVT VT = Op.getValueType();
    2572             :   assert(VT.is128BitVector() && VT.isInteger() &&
    2573             :          "unexpected type for custom-lowering ISD::MULH{U,S}");
    2574             : 
    2575           8 :   SDValue V0 = Op.getOperand(0);
    2576           8 :   SDValue V1 = Op.getOperand(1);
    2577             : 
    2578             :   SDLoc DL(Op);
    2579             : 
    2580           8 :   EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
    2581             : 
    2582             :   // We turn (V0 mulhs/mulhu V1) to:
    2583             :   //
    2584             :   // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
    2585             :   //              (extract_subvector (ExtractVT V128:V1, (i64 0))))),
    2586             :   //       (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
    2587             :   //              (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
    2588             :   //
    2589             :   // Where ExtractVT is a subvector with half number of elements, and
    2590             :   // VMullIdx2 is the index of the middle element (the high part).
    2591             :   //
    2592             :   // The vector hight part extract and multiply will be matched against
    2593             :   // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
    2594             :   // issue a {s}mull2 instruction.
    2595             :   //
    2596             :   // This basically multiply the lower subvector with '{s,u}mull', the high
    2597             :   // subvector with '{s,u}mull2', and shuffle both results high part in
    2598             :   // resulting vector.
    2599           8 :   unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
    2600           8 :   SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
    2601           8 :   SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
    2602             : 
    2603             :   SDValue VMullV0 =
    2604           8 :     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
    2605             :   SDValue VMullV1 =
    2606           8 :     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
    2607             : 
    2608             :   SDValue VMull2V0 =
    2609           8 :     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
    2610             :   SDValue VMull2V1 =
    2611           8 :     DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
    2612             : 
    2613           8 :   unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
    2614             :                                                   : AArch64ISD::UMULL;
    2615             : 
    2616           8 :   EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
    2617           8 :   SDValue Mull  = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
    2618           8 :   SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
    2619             : 
    2620           8 :   Mull  = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
    2621           8 :   Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
    2622             : 
    2623          16 :   return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
    2624             : }
    2625             : 
    2626        5699 : SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
    2627             :                                                      SelectionDAG &DAG) const {
    2628       11398 :   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    2629             :   SDLoc dl(Op);
    2630        5699 :   switch (IntNo) {
    2631        5612 :   default: return SDValue();    // Don't custom lower most intrinsics.
    2632           6 :   case Intrinsic::thread_pointer: {
    2633           6 :     EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2634           6 :     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
    2635             :   }
    2636             :   case Intrinsic::aarch64_neon_abs:
    2637             :     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
    2638           8 :                        Op.getOperand(1));
    2639             :   case Intrinsic::aarch64_neon_smax:
    2640             :     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
    2641          19 :                        Op.getOperand(1), Op.getOperand(2));
    2642             :   case Intrinsic::aarch64_neon_umax:
    2643             :     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
    2644          18 :                        Op.getOperand(1), Op.getOperand(2));
    2645             :   case Intrinsic::aarch64_neon_smin:
    2646             :     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
    2647          18 :                        Op.getOperand(1), Op.getOperand(2));
    2648             :   case Intrinsic::aarch64_neon_umin:
    2649             :     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
    2650          18 :                        Op.getOperand(1), Op.getOperand(2));
    2651             :   }
    2652             : }
    2653             : 
    2654       28456 : SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
    2655             :                                               SelectionDAG &DAG) const {
    2656             :   LLVM_DEBUG(dbgs() << "Custom lowering: ");
    2657             :   LLVM_DEBUG(Op.dump());
    2658             : 
    2659       28456 :   switch (Op.getOpcode()) {
    2660           0 :   default:
    2661           0 :     llvm_unreachable("unimplemented operand");
    2662             :     return SDValue();
    2663           8 :   case ISD::BITCAST:
    2664           8 :     return LowerBITCAST(Op, DAG);
    2665        2971 :   case ISD::GlobalAddress:
    2666        2971 :     return LowerGlobalAddress(Op, DAG);
    2667         104 :   case ISD::GlobalTLSAddress:
    2668         104 :     return LowerGlobalTLSAddress(Op, DAG);
    2669         670 :   case ISD::SETCC:
    2670         670 :     return LowerSETCC(Op, DAG);
    2671         952 :   case ISD::BR_CC:
    2672         952 :     return LowerBR_CC(Op, DAG);
    2673         359 :   case ISD::SELECT:
    2674         359 :     return LowerSELECT(Op, DAG);
    2675         213 :   case ISD::SELECT_CC:
    2676         213 :     return LowerSELECT_CC(Op, DAG);
    2677          27 :   case ISD::JumpTable:
    2678          27 :     return LowerJumpTable(Op, DAG);
    2679         145 :   case ISD::ConstantPool:
    2680         145 :     return LowerConstantPool(Op, DAG);
    2681           6 :   case ISD::BlockAddress:
    2682           6 :     return LowerBlockAddress(Op, DAG);
    2683          25 :   case ISD::VASTART:
    2684          25 :     return LowerVASTART(Op, DAG);
    2685           2 :   case ISD::VACOPY:
    2686           2 :     return LowerVACOPY(Op, DAG);
    2687          16 :   case ISD::VAARG:
    2688          16 :     return LowerVAARG(Op, DAG);
    2689          48 :   case ISD::ADDC:
    2690             :   case ISD::ADDE:
    2691             :   case ISD::SUBC:
    2692             :   case ISD::SUBE:
    2693          48 :     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
    2694          23 :   case ISD::SADDO:
    2695             :   case ISD::UADDO:
    2696             :   case ISD::SSUBO:
    2697             :   case ISD::USUBO:
    2698             :   case ISD::SMULO:
    2699             :   case ISD::UMULO:
    2700          23 :     return LowerXALUO(Op, DAG);
    2701          78 :   case ISD::FADD:
    2702          78 :     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
    2703           2 :   case ISD::FSUB:
    2704           2 :     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
    2705           4 :   case ISD::FMUL:
    2706           4 :     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
    2707           1 :   case ISD::FDIV:
    2708           1 :     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
    2709          36 :   case ISD::FP_ROUND:
    2710          36 :     return LowerFP_ROUND(Op, DAG);
    2711           2 :   case ISD::FP_EXTEND:
    2712           2 :     return LowerFP_EXTEND(Op, DAG);
    2713           2 :   case ISD::FRAMEADDR:
    2714           2 :     return LowerFRAMEADDR(Op, DAG);
    2715           6 :   case ISD::RETURNADDR:
    2716           6 :     return LowerRETURNADDR(Op, DAG);
    2717        2102 :   case ISD::INSERT_VECTOR_ELT:
    2718        2102 :     return LowerINSERT_VECTOR_ELT(Op, DAG);
    2719        5267 :   case ISD::EXTRACT_VECTOR_ELT:
    2720        5267 :     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
    2721        1746 :   case ISD::BUILD_VECTOR:
    2722        1746 :     return LowerBUILD_VECTOR(Op, DAG);
    2723        1680 :   case ISD::VECTOR_SHUFFLE:
    2724        1680 :     return LowerVECTOR_SHUFFLE(Op, DAG);
    2725        1646 :   case ISD::EXTRACT_SUBVECTOR:
    2726        1646 :     return LowerEXTRACT_SUBVECTOR(Op, DAG);
    2727         231 :   case ISD::SRA:
    2728             :   case ISD::SRL:
    2729             :   case ISD::SHL:
    2730         231 :     return LowerVectorSRA_SRL_SHL(Op, DAG);
    2731           1 :   case ISD::SHL_PARTS:
    2732           1 :     return LowerShiftLeftParts(Op, DAG);
    2733           2 :   case ISD::SRL_PARTS:
    2734             :   case ISD::SRA_PARTS:
    2735           2 :     return LowerShiftRightParts(Op, DAG);
    2736          34 :   case ISD::CTPOP:
    2737          34 :     return LowerCTPOP(Op, DAG);
    2738          29 :   case ISD::FCOPYSIGN:
    2739          29 :     return LowerFCOPYSIGN(Op, DAG);
    2740         868 :   case ISD::AND:
    2741         868 :     return LowerVectorAND(Op, DAG);
    2742         569 :   case ISD::OR:
    2743         569 :     return LowerVectorOR(Op, DAG);
    2744         903 :   case ISD::XOR:
    2745         903 :     return LowerXOR(Op, DAG);
    2746          24 :   case ISD::PREFETCH:
    2747          24 :     return LowerPREFETCH(Op, DAG);
    2748         721 :   case ISD::SINT_TO_FP:
    2749             :   case ISD::UINT_TO_FP:
    2750         721 :     return LowerINT_TO_FP(Op, DAG);
    2751         461 :   case ISD::FP_TO_SINT:
    2752             :   case ISD::FP_TO_UINT:
    2753         461 :     return LowerFP_TO_INT(Op, DAG);
    2754           2 :   case ISD::FSINCOS:
    2755           2 :     return LowerFSINCOS(Op, DAG);
    2756         384 :   case ISD::MUL:
    2757         384 :     return LowerMUL(Op, DAG);
    2758           8 :   case ISD::MULHS:
    2759             :   case ISD::MULHU:
    2760           8 :     return LowerMULH(Op, DAG);
    2761        5699 :   case ISD::INTRINSIC_WO_CHAIN:
    2762        5699 :     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
    2763          23 :   case ISD::VECREDUCE_ADD:
    2764             :   case ISD::VECREDUCE_SMAX:
    2765             :   case ISD::VECREDUCE_SMIN:
    2766             :   case ISD::VECREDUCE_UMAX:
    2767             :   case ISD::VECREDUCE_UMIN:
    2768             :   case ISD::VECREDUCE_FMAX:
    2769             :   case ISD::VECREDUCE_FMIN:
    2770          23 :     return LowerVECREDUCE(Op, DAG);
    2771         176 :   case ISD::ATOMIC_LOAD_SUB:
    2772         176 :     return LowerATOMIC_LOAD_SUB(Op, DAG);
    2773         176 :   case ISD::ATOMIC_LOAD_AND:
    2774         176 :     return LowerATOMIC_LOAD_AND(Op, DAG);
    2775           4 :   case ISD::DYNAMIC_STACKALLOC:
    2776           4 :     return LowerDYNAMIC_STACKALLOC(Op, DAG);
    2777             :   }
    2778             : }
    2779             : 
    2780             : //===----------------------------------------------------------------------===//
    2781             : //                      Calling Convention Implementation
    2782             : //===----------------------------------------------------------------------===//
    2783             : 
    2784             : #include "AArch64GenCallingConv.inc"
    2785             : 
    2786             : /// Selects the correct CCAssignFn for a given CallingConvention value.
    2787       28680 : CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
    2788             :                                                      bool IsVarArg) const {
    2789       28680 :   switch (CC) {
    2790           0 :   default:
    2791           0 :     report_fatal_error("Unsupported calling convention.");
    2792             :   case CallingConv::WebKit_JS:
    2793             :     return CC_AArch64_WebKit_JS;
    2794           9 :   case CallingConv::GHC:
    2795           9 :     return CC_AArch64_GHC;
    2796       28540 :   case CallingConv::C:
    2797             :   case CallingConv::Fast:
    2798             :   case CallingConv::PreserveMost:
    2799             :   case CallingConv::CXX_FAST_TLS:
    2800             :   case CallingConv::Swift:
    2801       57080 :     if (Subtarget->isTargetWindows() && IsVarArg)
    2802             :       return CC_AArch64_Win64_VarArg;
    2803             :     if (!Subtarget->isTargetDarwin())
    2804             :       return CC_AArch64_AAPCS;
    2805        6416 :     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
    2806          25 :   case CallingConv::Win64:
    2807          25 :     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
    2808             :   }
    2809             : }
    2810             : 
    2811             : CCAssignFn *
    2812         195 : AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
    2813             :   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
    2814         195 :                                       : RetCC_AArch64_AAPCS;
    2815             : }
    2816             : 
    2817       12854 : SDValue AArch64TargetLowering::LowerFormalArguments(
    2818             :     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
    2819             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
    2820             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
    2821       12854 :   MachineFunction &MF = DAG.getMachineFunction();
    2822       12854 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    2823       12854 :   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
    2824             : 
    2825             :   // Assign locations to all of the incoming arguments.
    2826             :   SmallVector<CCValAssign, 16> ArgLocs;
    2827             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
    2828       25708 :                  *DAG.getContext());
    2829             : 
    2830             :   // At this point, Ins[].VT may already be promoted to i32. To correctly
    2831             :   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
    2832             :   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
    2833             :   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
    2834             :   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
    2835             :   // LocVT.
    2836       12854 :   unsigned NumArgs = Ins.size();
    2837       12854 :   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
    2838             :   unsigned CurArgIdx = 0;
    2839       61146 :   for (unsigned i = 0; i != NumArgs; ++i) {
    2840       48292 :     MVT ValVT = Ins[i].VT;
    2841       24146 :     if (Ins[i].isOrigArg()) {
    2842       24140 :       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
    2843             :       CurArgIdx = Ins[i].getOrigArgIndex();
    2844             : 
    2845             :       // Get type of the original argument.
    2846             :       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
    2847       48280 :                                   /*AllowUnknown*/ true);
    2848       24140 :       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
    2849             :       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
    2850       24140 :       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
    2851         617 :         ValVT = MVT::i8;
    2852       23523 :       else if (ActualMVT == MVT::i16)
    2853         583 :         ValVT = MVT::i16;
    2854             :     }
    2855       24146 :     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
    2856             :     bool Res =
    2857       24146 :         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
    2858             :     assert(!Res && "Call operand has unhandled type");
    2859             :     (void)Res;
    2860             :   }
    2861             :   assert(ArgLocs.size() == Ins.size());
    2862             :   SmallVector<SDValue, 16> ArgValues;
    2863       37000 :   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    2864       24146 :     CCValAssign &VA = ArgLocs[i];
    2865             : 
    2866       24146 :     if (Ins[i].Flags.isByVal()) {
    2867             :       // Byval is used for HFAs in the PCS, but the system should work in a
    2868             :       // non-compliant manner for larger structs.
    2869          10 :       EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2870          10 :       int Size = Ins[i].Flags.getByValSize();
    2871          10 :       unsigned NumRegs = (Size + 7) / 8;
    2872             : 
    2873             :       // FIXME: This works on big-endian for composite byvals, which are the common
    2874             :       // case. It should also work for fundamental types too.
    2875             :       unsigned FrameIdx =
    2876          10 :         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
    2877          10 :       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
    2878          10 :       InVals.push_back(FrameIdxN);
    2879             : 
    2880          10 :       continue;
    2881             :     }
    2882             : 
    2883       24136 :     if (VA.isRegLoc()) {
    2884             :       // Arguments stored in registers.
    2885             :       EVT RegVT = VA.getLocVT();
    2886             : 
    2887       23694 :       SDValue ArgValue;
    2888             :       const TargetRegisterClass *RC;
    2889             : 
    2890             :       if (RegVT == MVT::i32)
    2891             :         RC = &AArch64::GPR32RegClass;
    2892             :       else if (RegVT == MVT::i64)
    2893             :         RC = &AArch64::GPR64RegClass;
    2894             :       else if (RegVT == MVT::f16)
    2895             :         RC = &AArch64::FPR16RegClass;
    2896             :       else if (RegVT == MVT::f32)
    2897             :         RC = &AArch64::FPR32RegClass;
    2898        9929 :       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
    2899             :         RC = &AArch64::FPR64RegClass;
    2900        5803 :       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
    2901             :         RC = &AArch64::FPR128RegClass;
    2902             :       else
    2903           0 :         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
    2904             : 
    2905             :       // Transform the arguments in physical registers into virtual ones.
    2906       23694 :       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
    2907       23694 :       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
    2908             : 
    2909             :       // If this is an 8, 16 or 32-bit value, it is really passed promoted
    2910             :       // to 64 bits.  Insert an assert[sz]ext to capture this, then
    2911             :       // truncate to the right size.
    2912       23694 :       switch (VA.getLocInfo()) {
    2913           0 :       default:
    2914           0 :         llvm_unreachable("Unknown loc info!");
    2915             :       case CCValAssign::Full:
    2916             :         break;
    2917             :       case CCValAssign::BCvt:
    2918        1865 :         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
    2919        1865 :         break;
    2920             :       case CCValAssign::AExt:
    2921             :       case CCValAssign::SExt:
    2922             :       case CCValAssign::ZExt:
    2923             :         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
    2924             :         // nodes after our lowering.
    2925             :         assert(RegVT == Ins[i].VT && "incorrect register location selected");
    2926             :         break;
    2927             :       }
    2928             : 
    2929       23694 :       InVals.push_back(ArgValue);
    2930             : 
    2931             :     } else { // VA.isRegLoc()
    2932             :       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
    2933         442 :       unsigned ArgOffset = VA.getLocMemOffset();
    2934         442 :       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
    2935             : 
    2936             :       uint32_t BEAlign = 0;
    2937         448 :       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
    2938             :           !Ins[i].Flags.isInConsecutiveRegs())
    2939           4 :         BEAlign = 8 - ArgSize;
    2940             : 
    2941         442 :       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
    2942             : 
    2943             :       // Create load nodes to retrieve arguments from the stack.
    2944         884 :       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
    2945         442 :       SDValue ArgValue;
    2946             : 
    2947             :       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
    2948             :       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
    2949             :       MVT MemVT = VA.getValVT();
    2950             : 
    2951         442 :       switch (VA.getLocInfo()) {
    2952             :       default:
    2953             :         break;
    2954          15 :       case CCValAssign::BCvt:
    2955             :         MemVT = VA.getLocVT();
    2956          15 :         break;
    2957           8 :       case CCValAssign::SExt:
    2958             :         ExtType = ISD::SEXTLOAD;
    2959           8 :         break;
    2960           5 :       case CCValAssign::ZExt:
    2961             :         ExtType = ISD::ZEXTLOAD;
    2962           5 :         break;
    2963           9 :       case CCValAssign::AExt:
    2964             :         ExtType = ISD::EXTLOAD;
    2965           9 :         break;
    2966             :       }
    2967             : 
    2968         442 :       ArgValue = DAG.getExtLoad(
    2969             :           ExtType, DL, VA.getLocVT(), Chain, FIN,
    2970             :           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
    2971         884 :           MemVT);
    2972             : 
    2973         442 :       InVals.push_back(ArgValue);
    2974             :     }
    2975             :   }
    2976             : 
    2977             :   // varargs
    2978       12854 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    2979       12854 :   if (isVarArg) {
    2980          37 :     if (!Subtarget->isTargetDarwin() || IsWin64) {
    2981             :       // The AAPCS variadic function ABI is identical to the non-variadic
    2982             :       // one. As a result there may be more arguments in registers and we should
    2983             :       // save them for future reference.
    2984             :       // Win64 variadic functions also pass arguments in registers, but all float
    2985             :       // arguments are passed in integer registers.
    2986          19 :       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
    2987             :     }
    2988             : 
    2989             :     // This will point to the next argument passed via stack.
    2990          28 :     unsigned StackOffset = CCInfo.getNextStackOffset();
    2991             :     // We currently pass all varargs at 8-byte alignment.
    2992          28 :     StackOffset = ((StackOffset + 7) & ~7);
    2993          28 :     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
    2994             :   }
    2995             : 
    2996       12854 :   unsigned StackArgSize = CCInfo.getNextStackOffset();
    2997       12854 :   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
    2998       12854 :   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
    2999             :     // This is a non-standard ABI so by fiat I say we're allowed to make full
    3000             :     // use of the stack area to be popped, which must be aligned to 16 bytes in
    3001             :     // any case:
    3002          42 :     StackArgSize = alignTo(StackArgSize, 16);
    3003             : 
    3004             :     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
    3005             :     // a multiple of 16.
    3006             :     FuncInfo->setArgumentStackToRestore(StackArgSize);
    3007             : 
    3008             :     // This realignment carries over to the available bytes below. Our own
    3009             :     // callers will guarantee the space is free by giving an aligned value to
    3010             :     // CALLSEQ_START.
    3011             :   }
    3012             :   // Even if we're not expected to free up the space, it's useful to know how
    3013             :   // much is there while considering tail calls (because we can reuse it).
    3014             :   FuncInfo->setBytesInStackArgArea(StackArgSize);
    3015             : 
    3016       25708 :   return Chain;
    3017             : }
    3018             : 
    3019          19 : void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
    3020             :                                                 SelectionDAG &DAG,
    3021             :                                                 const SDLoc &DL,
    3022             :                                                 SDValue &Chain) const {
    3023          19 :   MachineFunction &MF = DAG.getMachineFunction();
    3024          19 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    3025          19 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    3026          19 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    3027          19 :   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
    3028             : 
    3029             :   SmallVector<SDValue, 8> MemOps;
    3030             : 
    3031             :   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
    3032             :                                           AArch64::X3, AArch64::X4, AArch64::X5,
    3033             :                                           AArch64::X6, AArch64::X7 };
    3034             :   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
    3035             :   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
    3036             : 
    3037          19 :   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
    3038             :   int GPRIdx = 0;
    3039          19 :   if (GPRSaveSize != 0) {
    3040          13 :     if (IsWin64) {
    3041           8 :       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
    3042           8 :       if (GPRSaveSize & 15)
    3043             :         // The extra size here, if triggered, will always be 8.
    3044           7 :         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
    3045             :     } else
    3046           5 :       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
    3047             : 
    3048          13 :     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
    3049             : 
    3050         157 :     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
    3051          72 :       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
    3052          72 :       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
    3053             :       SDValue Store = DAG.getStore(
    3054             :           Val.getValue(1), DL, Val, FIN,
    3055             :           IsWin64
    3056             :               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
    3057             :                                                   GPRIdx,
    3058          39 :                                                   (i - FirstVariadicGPR) * 8)
    3059         111 :               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
    3060          72 :       MemOps.push_back(Store);
    3061          72 :       FIN =
    3062         216 :           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
    3063             :     }
    3064             :   }
    3065             :   FuncInfo->setVarArgsGPRIndex(GPRIdx);
    3066             :   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
    3067             : 
    3068          19 :   if (Subtarget->hasFPARMv8() && !IsWin64) {
    3069             :     static const MCPhysReg FPRArgRegs[] = {
    3070             :         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
    3071             :         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
    3072             :     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
    3073             :     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
    3074             : 
    3075           6 :     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
    3076             :     int FPRIdx = 0;
    3077           6 :     if (FPRSaveSize != 0) {
    3078           5 :       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
    3079             : 
    3080           5 :       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
    3081             : 
    3082          77 :       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
    3083          36 :         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
    3084          36 :         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
    3085             : 
    3086             :         SDValue Store = DAG.getStore(
    3087             :             Val.getValue(1), DL, Val, FIN,
    3088          36 :             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
    3089          36 :         MemOps.push_back(Store);
    3090          36 :         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
    3091          72 :                           DAG.getConstant(16, DL, PtrVT));
    3092             :       }
    3093             :     }
    3094             :     FuncInfo->setVarArgsFPRIndex(FPRIdx);
    3095             :     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
    3096             :   }
    3097             : 
    3098          19 :   if (!MemOps.empty()) {
    3099          14 :     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
    3100             :   }
    3101          19 : }
    3102             : 
    3103             : /// LowerCallResult - Lower the result values of a call into the
    3104             : /// appropriate copies out of appropriate physical registers.
    3105        1665 : SDValue AArch64TargetLowering::LowerCallResult(
    3106             :     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
    3107             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
    3108             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
    3109             :     SDValue ThisVal) const {
    3110             :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    3111        1665 :                           ? RetCC_AArch64_WebKit_JS
    3112             :                           : RetCC_AArch64_AAPCS;
    3113             :   // Assign locations to each value returned by this call.
    3114             :   SmallVector<CCValAssign, 16> RVLocs;
    3115             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    3116        3330 :                  *DAG.getContext());
    3117        1665 :   CCInfo.AnalyzeCallResult(Ins, RetCC);
    3118             : 
    3119             :   // Copy all of the result registers out of their specified physreg.
    3120        6864 :   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    3121        1178 :     CCValAssign VA = RVLocs[i];
    3122             : 
    3123             :     // Pass 'this' value directly from the argument to return value, to avoid
    3124             :     // reg unit interference
    3125        1185 :     if (i == 0 && isThisReturn) {
    3126             :       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
    3127             :              "unexpected return calling convention register assignment");
    3128           7 :       InVals.push_back(ThisVal);
    3129           7 :       continue;
    3130             :     }
    3131             : 
    3132             :     SDValue Val =
    3133        1171 :         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
    3134        1171 :     Chain = Val.getValue(1);
    3135        1171 :     InFlag = Val.getValue(2);
    3136             : 
    3137        1171 :     switch (VA.getLocInfo()) {
    3138           0 :     default:
    3139           0 :       llvm_unreachable("Unknown loc info!");
    3140             :     case CCValAssign::Full:
    3141             :       break;
    3142             :     case CCValAssign::BCvt:
    3143         136 :       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
    3144         136 :       break;
    3145             :     }
    3146             : 
    3147        1171 :     InVals.push_back(Val);
    3148             :   }
    3149             : 
    3150        3330 :   return Chain;
    3151             : }
    3152             : 
    3153             : /// Return true if the calling convention is one that we can guarantee TCO for.
    3154             : static bool canGuaranteeTCO(CallingConv::ID CC) {
    3155          12 :   return CC == CallingConv::Fast;
    3156             : }
    3157             : 
    3158             : /// Return true if we might ever do TCO for calls with this calling convention.
    3159             : static bool mayTailCallThisCC(CallingConv::ID CC) {
    3160             :   switch (CC) {
    3161             :   case CallingConv::C:
    3162             :   case CallingConv::PreserveMost:
    3163             :   case CallingConv::Swift:
    3164             :     return true;
    3165             :   default:
    3166             :     return canGuaranteeTCO(CC);
    3167             :   }
    3168             : }
    3169             : 
    3170         244 : bool AArch64TargetLowering::isEligibleForTailCallOptimization(
    3171             :     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
    3172             :     const SmallVectorImpl<ISD::OutputArg> &Outs,
    3173             :     const SmallVectorImpl<SDValue> &OutVals,
    3174             :     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
    3175          12 :   if (!mayTailCallThisCC(CalleeCC))
    3176             :     return false;
    3177             : 
    3178         241 :   MachineFunction &MF = DAG.getMachineFunction();
    3179         241 :   const Function &CallerF = MF.getFunction();
    3180             :   CallingConv::ID CallerCC = CallerF.getCallingConv();
    3181             :   bool CCMatch = CallerCC == CalleeCC;
    3182             : 
    3183             :   // Byval parameters hand the function a pointer directly into the stack area
    3184             :   // we want to reuse during a tail call. Working around this *is* possible (see
    3185             :   // X86) but less efficient and uglier in LowerCall.
    3186         251 :   for (Function::const_arg_iterator i = CallerF.arg_begin(),
    3187             :                                     e = CallerF.arg_end();
    3188         492 :        i != e; ++i)
    3189         251 :     if (i->hasByValAttr())
    3190             :       return false;
    3191             : 
    3192         241 :   if (getTargetMachine().Options.GuaranteedTailCallOpt)
    3193           8 :     return canGuaranteeTCO(CalleeCC) && CCMatch;
    3194             : 
    3195             :   // Externally-defined functions with weak linkage should not be
    3196             :   // tail-called on AArch64 when the OS does not support dynamic
    3197             :   // pre-emption of symbols, as the AAELF spec requires normal calls
    3198             :   // to undefined weak functions to be replaced with a NOP or jump to the
    3199             :   // next instruction. The behaviour of branch instructions in this
    3200             :   // situation (as used for tail calls) is implementation-defined, so we
    3201             :   // cannot rely on the linker replacing the tail call with a return.
    3202             :   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
    3203         220 :     const GlobalValue *GV = G->getGlobal();
    3204             :     const Triple &TT = getTargetMachine().getTargetTriple();
    3205         220 :     if (GV->hasExternalWeakLinkage() &&
    3206           0 :         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
    3207             :       return false;
    3208             :   }
    3209             : 
    3210             :   // Now we search for cases where we can use a tail call without changing the
    3211             :   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
    3212             :   // concept.
    3213             : 
    3214             :   // I want anyone implementing a new calling convention to think long and hard
    3215             :   // about this assert.
    3216             :   assert((!isVarArg || CalleeCC == CallingConv::C) &&
    3217             :          "Unexpected variadic calling convention");
    3218             : 
    3219         233 :   LLVMContext &C = *DAG.getContext();
    3220         233 :   if (isVarArg && !Outs.empty()) {
    3221             :     // At least two cases here: if caller is fastcc then we can't have any
    3222             :     // memory arguments (we'd be expected to clean up the stack afterwards). If
    3223             :     // caller is C then we could potentially use its argument area.
    3224             : 
    3225             :     // FIXME: for now we take the most conservative of these in both cases:
    3226             :     // disallow all variadic memory operands.
    3227             :     SmallVector<CCValAssign, 16> ArgLocs;
    3228           2 :     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
    3229             : 
    3230           2 :     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
    3231          18 :     for (const CCValAssign &ArgLoc : ArgLocs)
    3232          10 :       if (!ArgLoc.isRegLoc())
    3233           2 :         return false;
    3234             :   }
    3235             : 
    3236             :   // Check that the call results are passed in the same way.
    3237         231 :   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
    3238             :                                   CCAssignFnForCall(CalleeCC, isVarArg),
    3239             :                                   CCAssignFnForCall(CallerCC, isVarArg)))
    3240             :     return false;
    3241             :   // The callee has to preserve all registers the caller needs to preserve.
    3242         231 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3243         231 :   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
    3244         231 :   if (!CCMatch) {
    3245           7 :     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
    3246           7 :     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
    3247             :       return false;
    3248             :   }
    3249             : 
    3250             :   // Nothing more to check if the callee is taking no arguments
    3251         227 :   if (Outs.empty())
    3252             :     return true;
    3253             : 
    3254             :   SmallVector<CCValAssign, 16> ArgLocs;
    3255         362 :   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
    3256             : 
    3257         181 :   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
    3258             : 
    3259         181 :   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    3260             : 
    3261             :   // If the stack arguments for this call do not fit into our own save area then
    3262             :   // the call cannot be made tail.
    3263         181 :   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
    3264             :     return false;
    3265             : 
    3266         153 :   const MachineRegisterInfo &MRI = MF.getRegInfo();
    3267         153 :   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
    3268             :     return false;
    3269             : 
    3270         149 :   return true;
    3271             : }
    3272             : 
    3273          11 : SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
    3274             :                                                    SelectionDAG &DAG,
    3275             :                                                    MachineFrameInfo &MFI,
    3276             :                                                    int ClobberedFI) const {
    3277             :   SmallVector<SDValue, 8> ArgChains;
    3278             :   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
    3279          11 :   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
    3280             : 
    3281             :   // Include the original chain at the beginning of the list. When this is
    3282             :   // used by target LowerCall hooks, this helps legalize find the
    3283             :   // CALLSEQ_BEGIN node.
    3284          11 :   ArgChains.push_back(Chain);
    3285             : 
    3286             :   // Add a chain value for each stack argument corresponding
    3287          11 :   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
    3288             :                             UE = DAG.getEntryNode().getNode()->use_end();
    3289         120 :        U != UE; ++U)
    3290             :     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
    3291             :       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
    3292          18 :         if (FI->getIndex() < 0) {
    3293             :           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
    3294             :           int64_t InLastByte = InFirstByte;
    3295          18 :           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
    3296             : 
    3297          27 :           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
    3298           9 :               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
    3299           9 :             ArgChains.push_back(SDValue(L, 1));
    3300             :         }
    3301             : 
    3302             :   // Build a tokenfactor for all the chains.
    3303          33 :   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
    3304             : }
    3305             : 
    3306       14519 : bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
    3307             :                                                    bool TailCallOpt) const {
    3308       14519 :   return CallCC == CallingConv::Fast && TailCallOpt;
    3309             : }
    3310             : 
    3311             : /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
    3312             : /// and add input and output parameter nodes.
    3313             : SDValue
    3314        1867 : AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
    3315             :                                  SmallVectorImpl<SDValue> &InVals) const {
    3316        1867 :   SelectionDAG &DAG = CLI.DAG;
    3317        1867 :   SDLoc &DL = CLI.DL;
    3318             :   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
    3319             :   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
    3320             :   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
    3321        1867 :   SDValue Chain = CLI.Chain;
    3322        1867 :   SDValue Callee = CLI.Callee;
    3323             :   bool &IsTailCall = CLI.IsTailCall;
    3324        1867 :   CallingConv::ID CallConv = CLI.CallConv;
    3325        1867 :   bool IsVarArg = CLI.IsVarArg;
    3326             : 
    3327        1867 :   MachineFunction &MF = DAG.getMachineFunction();
    3328             :   bool IsThisReturn = false;
    3329             : 
    3330        1867 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    3331        1867 :   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
    3332             :   bool IsSibCall = false;
    3333             : 
    3334        1867 :   if (IsTailCall) {
    3335             :     // Check if it's really possible to do a tail call.
    3336         244 :     IsTailCall = isEligibleForTailCallOptimization(
    3337             :         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
    3338         286 :     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
    3339           0 :       report_fatal_error("failed to perform tail call elimination on a call "
    3340             :                          "site marked musttail");
    3341             : 
    3342             :     // A sibling call is one where we're under the usual C ABI and not planning
    3343             :     // to change that but can still do a tail call:
    3344         480 :     if (!TailCallOpt && IsTailCall)
    3345             :       IsSibCall = true;
    3346             : 
    3347             :     if (IsTailCall)
    3348             :       ++NumTailCalls;
    3349             :   }
    3350             : 
    3351             :   // Analyze operands of the call, assigning locations to each operand.
    3352             :   SmallVector<CCValAssign, 16> ArgLocs;
    3353             :   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
    3354        3734 :                  *DAG.getContext());
    3355             : 
    3356        1867 :   if (IsVarArg) {
    3357             :     // Handle fixed and variable vector arguments differently.
    3358             :     // Variable vector arguments always go into memory.
    3359          26 :     unsigned NumArgs = Outs.size();
    3360             : 
    3361         220 :     for (unsigned i = 0; i != NumArgs; ++i) {
    3362         194 :       MVT ArgVT = Outs[i].VT;
    3363          97 :       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
    3364          97 :       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
    3365         194 :                                                /*IsVarArg=*/ !Outs[i].IsFixed);
    3366          97 :       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
    3367             :       assert(!Res && "Call operand has unhandled type");
    3368             :       (void)Res;
    3369             :     }
    3370             :   } else {
    3371             :     // At this point, Outs[].VT may already be promoted to i32. To correctly
    3372             :     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
    3373             :     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
    3374             :     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
    3375             :     // we use a special version of AnalyzeCallOperands to pass in ValVT and
    3376             :     // LocVT.
    3377        1841 :     unsigned NumArgs = Outs.size();
    3378        8719 :     for (unsigned i = 0; i != NumArgs; ++i) {
    3379        6878 :       MVT ValVT = Outs[i].VT;
    3380             :       // Get type of the original argument.
    3381             :       EVT ActualVT = getValueType(DAG.getDataLayout(),
    3382        3439 :                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
    3383       10317 :                                   /*AllowUnknown*/ true);
    3384        3439 :       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
    3385        3439 :       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
    3386             :       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
    3387        3439 :       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
    3388             :         ValVT = MVT::i8;
    3389        3368 :       else if (ActualMVT == MVT::i16)
    3390             :         ValVT = MVT::i16;
    3391             : 
    3392        3439 :       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
    3393        3439 :       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
    3394             :       assert(!Res && "Call operand has unhandled type");
    3395             :       (void)Res;
    3396             :     }
    3397             :   }
    3398             : 
    3399             :   // Get a count of how many bytes are to be pushed on the stack.
    3400        1867 :   unsigned NumBytes = CCInfo.getNextStackOffset();
    3401             : 
    3402        1867 :   if (IsSibCall) {
    3403             :     // Since we're not changing the ABI to make this a tail call, the memory
    3404             :     // operands are already available in the caller's incoming argument space.
    3405             :     NumBytes = 0;
    3406             :   }
    3407             : 
    3408             :   // FPDiff is the byte offset of the call's argument area from the callee's.
    3409             :   // Stores to callee stack arguments will be placed in FixedStackSlots offset
    3410             :   // by this amount for a tail call. In a sibling call it must be 0 because the
    3411             :   // caller will deallocate the entire stack and the callee still expects its
    3412             :   // arguments to begin at SP+0. Completely unused for non-tail calls.
    3413             :   int FPDiff = 0;
    3414             : 
    3415        1867 :   if (IsTailCall && !IsSibCall) {
    3416           7 :     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
    3417             : 
    3418             :     // Since callee will pop argument stack as a tail call, we must keep the
    3419             :     // popped size 16-byte aligned.
    3420          14 :     NumBytes = alignTo(NumBytes, 16);
    3421             : 
    3422             :     // FPDiff will be negative if this tail call requires more space than we
    3423             :     // would automatically have in our incoming argument space. Positive if we
    3424             :     // can actually shrink the stack.
    3425           7 :     FPDiff = NumReusableBytes - NumBytes;
    3426             : 
    3427             :     // The stack pointer must be 16-byte aligned at all times it's used for a
    3428             :     // memory operation, which in practice means at *all* times and in
    3429             :     // particular across call boundaries. Therefore our own arguments started at
    3430             :     // a 16-byte aligned SP and the delta applied for the tail call should
    3431             :     // satisfy the same constraint.
    3432             :     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
    3433             :   }
    3434             : 
    3435             :   // Adjust the stack pointer for the new arguments...
    3436             :   // These operations are automatically eliminated by the prolog/epilog pass
    3437        1867 :   if (!IsSibCall)
    3438        1672 :     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
    3439             : 
    3440             :   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
    3441        3734 :                                         getPointerTy(DAG.getDataLayout()));
    3442             : 
    3443             :   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
    3444             :   SmallVector<SDValue, 8> MemOpChains;
    3445        1867 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    3446             : 
    3447             :   // Walk the register/memloc assignments, inserting copies/loads.
    3448        5403 :   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
    3449             :        ++i, ++realArgIdx) {
    3450        3536 :     CCValAssign &VA = ArgLocs[i];
    3451        3536 :     SDValue Arg = OutVals[realArgIdx];
    3452        3536 :     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
    3453             : 
    3454             :     // Promote the value if needed.
    3455        3536 :     switch (VA.getLocInfo()) {
    3456           0 :     default:
    3457           0 :       llvm_unreachable("Unknown loc info!");
    3458             :     case CCValAssign::Full:
    3459             :       break;
    3460             :     case CCValAssign::SExt:
    3461          25 :       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
    3462          25 :       break;
    3463             :     case CCValAssign::ZExt:
    3464          13 :       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
    3465          13 :       break;
    3466             :     case CCValAssign::AExt:
    3467             :       if (Outs[realArgIdx].ArgVT == MVT::i1) {
    3468             :         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
    3469           1 :         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
    3470           1 :         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
    3471             :       }
    3472          89 :       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
    3473          89 :       break;
    3474             :     case CCValAssign::BCvt:
    3475         225 :       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
    3476         225 :       break;
    3477             :     case CCValAssign::FPExt:
    3478           0 :       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
    3479           0 :       break;
    3480             :     }
    3481             : 
    3482        3536 :     if (VA.isRegLoc()) {
    3483        4339 :       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
    3484             :           Outs[0].VT == MVT::i64) {
    3485             :         assert(VA.getLocVT() == MVT::i64 &&
    3486             :                "unexpected calling convention register assignment");
    3487             :         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
    3488             :                "unexpected use of 'returned'");
    3489             :         IsThisReturn = true;
    3490             :       }
    3491        5542 :       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
    3492             :     } else {
    3493             :       assert(VA.isMemLoc());
    3494             : 
    3495         765 :       SDValue DstAddr;
    3496             :       MachinePointerInfo DstInfo;
    3497             : 
    3498             :       // FIXME: This works on big-endian for composite byvals, which are the
    3499             :       // common case. It should also work for fundamental types too.
    3500             :       uint32_t BEAlign = 0;
    3501        1525 :       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
    3502        1525 :                                         : VA.getValVT().getSizeInBits();
    3503         765 :       OpSize = (OpSize + 7) / 8;
    3504         775 :       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
    3505             :           !Flags.isInConsecutiveRegs()) {
    3506           8 :         if (OpSize < 8)
    3507           6 :           BEAlign = 8 - OpSize;
    3508             :       }
    3509         765 :       unsigned LocMemOffset = VA.getLocMemOffset();
    3510         765 :       int32_t Offset = LocMemOffset + BEAlign;
    3511         765 :       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
    3512         765 :       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
    3513             : 
    3514         765 :       if (IsTailCall) {
    3515          11 :         Offset = Offset + FPDiff;
    3516          11 :         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
    3517             : 
    3518          11 :         DstAddr = DAG.getFrameIndex(FI, PtrVT);
    3519          11 :         DstInfo =
    3520          11 :             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
    3521             : 
    3522             :         // Make sure any stack arguments overlapping with where we're storing
    3523             :         // are loaded before this eventual operation. Otherwise they'll be
    3524             :         // clobbered.
    3525          11 :         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
    3526             :       } else {
    3527         754 :         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
    3528             : 
    3529         754 :         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
    3530         754 :         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
    3531         754 :                                                LocMemOffset);
    3532             :       }
    3533             : 
    3534         765 :       if (Outs[i].Flags.isByVal()) {
    3535             :         SDValue SizeNode =
    3536           5 :             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
    3537             :         SDValue Cpy = DAG.getMemcpy(
    3538             :             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
    3539             :             /*isVol = */ false, /*AlwaysInline = */ false,
    3540             :             /*isTailCall = */ false,
    3541           5 :             DstInfo, MachinePointerInfo());
    3542             : 
    3543           5 :         MemOpChains.push_back(Cpy);
    3544             :       } else {
    3545             :         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
    3546             :         // promoted to a legal register type i32, we should truncate Arg back to
    3547             :         // i1/i8/i16.
    3548         760 :         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
    3549             :             VA.getValVT() == MVT::i16)
    3550          23 :           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
    3551             : 
    3552         760 :         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
    3553         760 :         MemOpChains.push_back(Store);
    3554             :       }
    3555             :     }
    3556             :   }
    3557             : 
    3558        1867 :   if (!MemOpChains.empty())
    3559         100 :     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
    3560             : 
    3561             :   // Build a sequence of copy-to-reg nodes chained together with token chain
    3562             :   // and flag operands which copy the outgoing args into the appropriate regs.
    3563        1867 :   SDValue InFlag;
    3564        7409 :   for (auto &RegToPass : RegsToPass) {
    3565        2771 :     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
    3566        2771 :                              RegToPass.second, InFlag);
    3567        2771 :     InFlag = Chain.getValue(1);
    3568             :   }
    3569             : 
    3570             :   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
    3571             :   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
    3572             :   // node so that legalize doesn't hack it.
    3573             :   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
    3574        1287 :     auto GV = G->getGlobal();
    3575        1287 :     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
    3576             :         AArch64II::MO_GOT) {
    3577           2 :       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
    3578           2 :       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
    3579        2589 :     } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
    3580             :       assert(Subtarget->isTargetWindows() &&
    3581             :              "Windows is the only supported COFF target");
    3582           3 :       Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
    3583             :     } else {
    3584        1282 :       const GlobalValue *GV = G->getGlobal();
    3585        1282 :       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
    3586             :     }
    3587             :   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
    3588         536 :     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    3589           3 :         Subtarget->isTargetMachO()) {
    3590           0 :       const char *Sym = S->getSymbol();
    3591           0 :       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
    3592           0 :       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
    3593             :     } else {
    3594         533 :       const char *Sym = S->getSymbol();
    3595         533 :       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
    3596             :     }
    3597             :   }
    3598             : 
    3599             :   // We don't usually want to end the call-sequence here because we would tidy
    3600             :   // the frame up *after* the call, however in the ABI-changing tail-call case
    3601             :   // we've carefully laid out the parameters so that when sp is reset they'll be
    3602             :   // in the correct location.
    3603        1867 :   if (IsTailCall && !IsSibCall) {
    3604           7 :     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
    3605           7 :                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
    3606           7 :     InFlag = Chain.getValue(1);
    3607             :   }
    3608             : 
    3609             :   std::vector<SDValue> Ops;
    3610        1867 :   Ops.push_back(Chain);
    3611        1867 :   Ops.push_back(Callee);
    3612             : 
    3613        1867 :   if (IsTailCall) {
    3614             :     // Each tail call may have to adjust the stack by a different amount, so
    3615             :     // this information must travel along with the operation for eventual
    3616             :     // consumption by emitEpilogue.
    3617         606 :     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
    3618             :   }
    3619             : 
    3620             :   // Add argument registers to the end of the list so that they are known live
    3621             :   // into the call.
    3622        7409 :   for (auto &RegToPass : RegsToPass)
    3623        5542 :     Ops.push_back(DAG.getRegister(RegToPass.first,
    3624        5542 :                                   RegToPass.second.getValueType()));
    3625             : 
    3626             :   // Add a register mask operand representing the call-preserved registers.
    3627             :   const uint32_t *Mask;
    3628        1867 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3629        1867 :   if (IsThisReturn) {
    3630             :     // For 'this' returns, use the X0-preserving mask if applicable
    3631          10 :     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
    3632          10 :     if (!Mask) {
    3633             :       IsThisReturn = false;
    3634           0 :       Mask = TRI->getCallPreservedMask(MF, CallConv);
    3635             :     }
    3636             :   } else
    3637        1857 :     Mask = TRI->getCallPreservedMask(MF, CallConv);
    3638             : 
    3639             :   assert(Mask && "Missing call preserved mask for calling convention");
    3640        3734 :   Ops.push_back(DAG.getRegisterMask(Mask));
    3641             : 
    3642        1867 :   if (InFlag.getNode())
    3643        1547 :     Ops.push_back(InFlag);
    3644             : 
    3645        1867 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    3646             : 
    3647             :   // If we're doing a tall call, use a TC_RETURN here rather than an
    3648             :   // actual call instruction.
    3649        1867 :   if (IsTailCall) {
    3650         202 :     MF.getFrameInfo().setHasTailCall();
    3651         202 :     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
    3652             :   }
    3653             : 
    3654             :   // Returns a chain and a flag for retval copy to use.
    3655        1665 :   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
    3656        1665 :   InFlag = Chain.getValue(1);
    3657             : 
    3658             :   uint64_t CalleePopBytes =
    3659        1665 :       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
    3660             : 
    3661        1665 :   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
    3662             :                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
    3663        1665 :                              InFlag, DL);
    3664        1665 :   if (!Ins.empty())
    3665        1080 :     InFlag = Chain.getValue(1);
    3666             : 
    3667             :   // Handle result values, copying them out of physregs into vregs that we
    3668             :   // return.
    3669             :   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
    3670             :                          InVals, IsThisReturn,
    3671        1672 :                          IsThisReturn ? OutVals[0] : SDValue());
    3672             : }
    3673             : 
    3674       16027 : bool AArch64TargetLowering::CanLowerReturn(
    3675             :     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
    3676             :     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
    3677             :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    3678       16027 :                           ? RetCC_AArch64_WebKit_JS
    3679             :                           : RetCC_AArch64_AAPCS;
    3680             :   SmallVector<CCValAssign, 16> RVLocs;
    3681       32054 :   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
    3682       32054 :   return CCInfo.CheckReturn(Outs, RetCC);
    3683             : }
    3684             : 
    3685             : SDValue
    3686       12833 : AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
    3687             :                                    bool isVarArg,
    3688             :                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
    3689             :                                    const SmallVectorImpl<SDValue> &OutVals,
    3690             :                                    const SDLoc &DL, SelectionDAG &DAG) const {
    3691             :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    3692       12833 :                           ? RetCC_AArch64_WebKit_JS
    3693             :                           : RetCC_AArch64_AAPCS;
    3694             :   SmallVector<CCValAssign, 16> RVLocs;
    3695             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    3696       25666 :                  *DAG.getContext());
    3697       12833 :   CCInfo.AnalyzeReturn(Outs, RetCC);
    3698             : 
    3699             :   // Copy the result values into the output registers.
    3700       12833 :   SDValue Flag;
    3701             :   SmallVector<SDValue, 4> RetOps(1, Chain);
    3702       60025 :   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
    3703             :        ++i, ++realRVLocIdx) {
    3704             :     CCValAssign &VA = RVLocs[i];
    3705             :     assert(VA.isRegLoc() && "Can only return in registers!");
    3706       11453 :     SDValue Arg = OutVals[realRVLocIdx];
    3707             : 
    3708       11453 :     switch (VA.getLocInfo()) {
    3709           0 :     default:
    3710           0 :       llvm_unreachable("Unknown loc info!");
    3711             :     case CCValAssign::Full:
    3712             :       if (Outs[i].ArgVT == MVT::i1) {
    3713             :         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
    3714             :         // value. This is strictly redundant on Darwin (which uses "zeroext
    3715             :         // i1"), but will be optimised out before ISel.
    3716          96 :         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
    3717          96 :         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
    3718             :       }
    3719             :       break;
    3720             :     case CCValAssign::BCvt:
    3721        1146 :       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
    3722        1146 :       break;
    3723             :     }
    3724             : 
    3725       11453 :     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
    3726       11453 :     Flag = Chain.getValue(1);
    3727       11453 :     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    3728             :   }
    3729       12833 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3730             :   const MCPhysReg *I =
    3731       12833 :       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
    3732       12833 :   if (I) {
    3733         678 :     for (; *I; ++I) {
    3734         672 :       if (AArch64::GPR64RegClass.contains(*I))
    3735         144 :         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
    3736         384 :       else if (AArch64::FPR64RegClass.contains(*I))
    3737         192 :         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
    3738             :       else
    3739           0 :         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
    3740             :     }
    3741             :   }
    3742             : 
    3743       12833 :   RetOps[0] = Chain; // Update chain.
    3744             : 
    3745             :   // Add the flag if we have it.
    3746       12833 :   if (Flag.getNode())
    3747       10324 :     RetOps.push_back(Flag);
    3748             : 
    3749       25666 :   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
    3750             : }
    3751             : 
    3752             : //===----------------------------------------------------------------------===//
    3753             : //  Other Lowering Code
    3754             : //===----------------------------------------------------------------------===//
    3755             : 
    3756        5795 : SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
    3757             :                                              SelectionDAG &DAG,
    3758             :                                              unsigned Flag) const {
    3759        5795 :   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
    3760       17385 :                                     N->getOffset(), Flag);
    3761             : }
    3762             : 
    3763          56 : SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
    3764             :                                              SelectionDAG &DAG,
    3765             :                                              unsigned Flag) const {
    3766         112 :   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
    3767             : }
    3768             : 
    3769         298 : SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
    3770             :                                              SelectionDAG &DAG,
    3771             :                                              unsigned Flag) const {
    3772             :   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
    3773         894 :                                    N->getOffset(), Flag);
    3774             : }
    3775             : 
    3776          16 : SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
    3777             :                                              SelectionDAG &DAG,
    3778             :                                              unsigned Flag) const {
    3779          32 :   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
    3780             : }
    3781             : 
    3782             : // (loadGOT sym)
    3783             : template <class NodeTy>
    3784         197 : SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
    3785             :                                       unsigned Flags) const {
    3786             :   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
    3787             :   SDLoc DL(N);
    3788         197 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3789         197 :   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
    3790             :   // FIXME: Once remat is capable of dealing with instructions with register
    3791             :   // operands, expand this into two nodes instead of using a wrapper node.
    3792         394 :   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
    3793             : }
    3794             : 
    3795             : // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
    3796             : template <class NodeTy>
    3797          29 : SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
    3798             :                                             unsigned Flags) const {
    3799             :   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
    3800             :   SDLoc DL(N);
    3801          29 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3802             :   const unsigned char MO_NC = AArch64II::MO_NC;
    3803             :   return DAG.getNode(
    3804             :       AArch64ISD::WrapperLarge, DL, Ty,
    3805             :       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
    3806             :       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
    3807             :       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
    3808          58 :       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
    3809             : }
    3810             : 
    3811             : // (addlow (adrp %hi(sym)) %lo(sym))
    3812             : template <class NodeTy>
    3813        2926 : SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
    3814             :                                        unsigned Flags) const {
    3815             :   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
    3816             :   SDLoc DL(N);
    3817        2926 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3818        2926 :   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
    3819        2926 :   SDValue Lo = getTargetNode(N, Ty, DAG,
    3820             :                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
    3821        2926 :   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
    3822        5852 :   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
    3823             : }
    3824             : 
    3825        2971 : SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
    3826             :                                                   SelectionDAG &DAG) const {
    3827             :   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
    3828        2971 :   const GlobalValue *GV = GN->getGlobal();
    3829             :   const AArch64II::TOF TargetFlags =
    3830        2971 :       (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT
    3831             :                                       : AArch64II::MO_NO_FLAG);
    3832             :   unsigned char OpFlags =
    3833        2971 :       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
    3834             : 
    3835             :   if (OpFlags != AArch64II::MO_NO_FLAG)
    3836             :     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
    3837             :            "unexpected offset in global node");
    3838             : 
    3839             :   // This also catches the large code model case for Darwin.
    3840        2971 :   if ((OpFlags & AArch64II::MO_GOT) != 0) {
    3841         194 :     return getGOT(GN, DAG, TargetFlags);
    3842             :   }
    3843             : 
    3844             :   SDValue Result;
    3845        2777 :   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
    3846          22 :     Result = getAddrLarge(GN, DAG, TargetFlags);
    3847             :   } else {
    3848        2755 :     Result = getAddr(GN, DAG, TargetFlags);
    3849             :   }
    3850        2777 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3851             :   SDLoc DL(GN);
    3852        2777 :   if (GV->hasDLLImportStorageClass())
    3853           0 :     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
    3854           0 :                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
    3855        2777 :   return Result;
    3856             : }
    3857             : 
    3858             : /// Convert a TLS address reference into the correct sequence of loads
    3859             : /// and calls to compute the variable's address (for Darwin, currently) and
    3860             : /// return an SDValue containing the final node.
    3861             : 
    3862             : /// Darwin only has one TLS scheme which must be capable of dealing with the
    3863             : /// fully general situation, in the worst case. This means:
    3864             : ///     + "extern __thread" declaration.
    3865             : ///     + Defined in a possibly unknown dynamic library.
    3866             : ///
    3867             : /// The general system is that each __thread variable has a [3 x i64] descriptor
    3868             : /// which contains information used by the runtime to calculate the address. The
    3869             : /// only part of this the compiler needs to know about is the first xword, which
    3870             : /// contains a function pointer that must be called with the address of the
    3871             : /// entire descriptor in "x0".
    3872             : ///
    3873             : /// Since this descriptor may be in a different unit, in general even the
    3874             : /// descriptor must be accessed via an indirect load. The "ideal" code sequence
    3875             : /// is:
    3876             : ///     adrp x0, _var@TLVPPAGE
    3877             : ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
    3878             : ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
    3879             : ///                                      ; the function pointer
    3880             : ///     blr x1                           ; Uses descriptor address in x0
    3881             : ///     ; Address of _var is now in x0.
    3882             : ///
    3883             : /// If the address of _var's descriptor *is* known to the linker, then it can
    3884             : /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
    3885             : /// a slight efficiency gain.
    3886             : SDValue
    3887          27 : AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
    3888             :                                                    SelectionDAG &DAG) const {
    3889             :   assert(Subtarget->isTargetDarwin() &&
    3890             :          "This function expects a Darwin target");
    3891             : 
    3892             :   SDLoc DL(Op);
    3893          27 :   MVT PtrVT = getPointerTy(DAG.getDataLayout());
    3894          27 :   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    3895             : 
    3896             :   SDValue TLVPAddr =
    3897          27 :       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    3898          27 :   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
    3899             : 
    3900             :   // The first entry in the descriptor is a function pointer that we must call
    3901             :   // to obtain the address of the variable.
    3902          27 :   SDValue Chain = DAG.getEntryNode();
    3903             :   SDValue FuncTLVGet = DAG.getLoad(
    3904             :       MVT::i64, DL, Chain, DescAddr,
    3905             :       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
    3906             :       /* Alignment = */ 8,
    3907             :       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
    3908          54 :           MachineMemOperand::MODereferenceable);
    3909          27 :   Chain = FuncTLVGet.getValue(1);
    3910             : 
    3911          27 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    3912             :   MFI.setAdjustsStack(true);
    3913             : 
    3914             :   // TLS calls preserve all registers except those that absolutely must be
    3915             :   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
    3916             :   // silly).
    3917             :   const uint32_t *Mask =
    3918          54 :       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
    3919             : 
    3920             :   // Finally, we can make the call. This is just a degenerate version of a
    3921             :   // normal AArch64 call node: x0 takes the address of the descriptor, and
    3922             :   // returns the address of the variable in this thread.
    3923          27 :   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
    3924          27 :   Chain =
    3925          54 :       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
    3926             :                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
    3927         108 :                   DAG.getRegisterMask(Mask), Chain.getValue(1));
    3928          54 :   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
    3929             : }
    3930             : 
    3931             : /// When accessing thread-local variables under either the general-dynamic or
    3932             : /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
    3933             : /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
    3934             : /// is a function pointer to carry out the resolution.
    3935             : ///
    3936             : /// The sequence is:
    3937             : ///    adrp  x0, :tlsdesc:var
    3938             : ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
    3939             : ///    add   x0, x0, #:tlsdesc_lo12:var
    3940             : ///    .tlsdesccall var
    3941             : ///    blr   x1
    3942             : ///    (TPIDR_EL0 offset now in x0)
    3943             : ///
    3944             : ///  The above sequence must be produced unscheduled, to enable the linker to
    3945             : ///  optimize/relax this sequence.
    3946             : ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
    3947             : ///  above sequence, and expanded really late in the compilation flow, to ensure
    3948             : ///  the sequence is produced as per above.
    3949          26 : SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
    3950             :                                                       const SDLoc &DL,
    3951             :                                                       SelectionDAG &DAG) const {
    3952          26 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3953             : 
    3954          26 :   SDValue Chain = DAG.getEntryNode();
    3955          26 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    3956             : 
    3957          26 :   Chain =
    3958          78 :       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
    3959          26 :   SDValue Glue = Chain.getValue(1);
    3960             : 
    3961          26 :   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
    3962             : }
    3963             : 
    3964             : SDValue
    3965          34 : AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
    3966             :                                                 SelectionDAG &DAG) const {
    3967             :   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
    3968             :   assert(Subtarget->useSmallAddressing() &&
    3969             :          "ELF TLS only supported in small memory model");
    3970             :   // Different choices can be made for the maximum size of the TLS area for a
    3971             :   // module. For the small address model, the default TLS size is 16MiB and the
    3972             :   // maximum TLS size is 4GiB.
    3973             :   // FIXME: add -mtls-size command line option and make it control the 16MiB
    3974             :   // vs. 4GiB code sequence generation.
    3975             :   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
    3976             : 
    3977          34 :   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
    3978             : 
    3979          34 :   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
    3980          22 :     if (Model == TLSModel::LocalDynamic)
    3981             :       Model = TLSModel::GeneralDynamic;
    3982             :   }
    3983             : 
    3984          34 :   SDValue TPOff;
    3985          34 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3986             :   SDLoc DL(Op);
    3987          34 :   const GlobalValue *GV = GA->getGlobal();
    3988             : 
    3989          34 :   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
    3990             : 
    3991          34 :   if (Model == TLSModel::LocalExec) {
    3992             :     SDValue HiVar = DAG.getTargetGlobalAddress(
    3993           4 :         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
    3994             :     SDValue LoVar = DAG.getTargetGlobalAddress(
    3995             :         GV, DL, PtrVT, 0,
    3996           4 :         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    3997             : 
    3998             :     SDValue TPWithOff_lo =
    3999           4 :         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
    4000             :                                    HiVar,
    4001             :                                    DAG.getTargetConstant(0, DL, MVT::i32)),
    4002             :                 0);
    4003             :     SDValue TPWithOff =
    4004           4 :         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
    4005             :                                    LoVar,
    4006             :                                    DAG.getTargetConstant(0, DL, MVT::i32)),
    4007             :                 0);
    4008           4 :     return TPWithOff;
    4009          30 :   } else if (Model == TLSModel::InitialExec) {
    4010           4 :     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    4011           4 :     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
    4012          26 :   } else if (Model == TLSModel::LocalDynamic) {
    4013             :     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
    4014             :     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
    4015             :     // the beginning of the module's TLS region, followed by a DTPREL offset
    4016             :     // calculation.
    4017             : 
    4018             :     // These accesses will need deduplicating if there's more than one.
    4019             :     AArch64FunctionInfo *MFI =
    4020           8 :         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    4021             :     MFI->incNumLocalDynamicTLSAccesses();
    4022             : 
    4023             :     // The call needs a relocation too for linker relaxation. It doesn't make
    4024             :     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
    4025             :     // the address.
    4026             :     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
    4027           8 :                                                   AArch64II::MO_TLS);
    4028             : 
    4029             :     // Now we can calculate the offset from TPIDR_EL0 to this module's
    4030             :     // thread-local area.
    4031           8 :     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
    4032             : 
    4033             :     // Now use :dtprel_whatever: operations to calculate this variable's offset
    4034             :     // in its thread-storage area.
    4035             :     SDValue HiVar = DAG.getTargetGlobalAddress(
    4036           8 :         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
    4037             :     SDValue LoVar = DAG.getTargetGlobalAddress(
    4038             :         GV, DL, MVT::i64, 0,
    4039           8 :         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    4040             : 
    4041           8 :     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
    4042             :                                        DAG.getTargetConstant(0, DL, MVT::i32)),
    4043             :                     0);
    4044           8 :     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
    4045             :                                        DAG.getTargetConstant(0, DL, MVT::i32)),
    4046             :                     0);
    4047          18 :   } else if (Model == TLSModel::GeneralDynamic) {
    4048             :     // The call needs a relocation too for linker relaxation. It doesn't make
    4049             :     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
    4050             :     // the address.
    4051             :     SDValue SymAddr =
    4052          18 :         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    4053             : 
    4054             :     // Finally we can make a call to calculate the offset from tpidr_el0.
    4055          18 :     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
    4056             :   } else
    4057           0 :     llvm_unreachable("Unsupported ELF TLS access model");
    4058             : 
    4059          30 :   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
    4060             : }
    4061             : 
    4062             : SDValue
    4063           5 : AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
    4064             :                                                     SelectionDAG &DAG) const {
    4065             :   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
    4066             : 
    4067           5 :   SDValue Chain = DAG.getEntryNode();
    4068           5 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    4069             :   SDLoc DL(Op);
    4070             : 
    4071           5 :   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
    4072             : 
    4073             :   // Load the ThreadLocalStoragePointer from the TEB
    4074             :   // A pointer to the TLS array is located at offset 0x58 from the TEB.
    4075             :   SDValue TLSArray =
    4076           5 :       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
    4077           5 :   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
    4078           5 :   Chain = TLSArray.getValue(1);
    4079             : 
    4080             :   // Load the TLS index from the C runtime;
    4081             :   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
    4082             :   // This also does the same as LOADgot, but using a generic i32 load,
    4083             :   // while LOADgot only loads i64.
    4084             :   SDValue TLSIndexHi =
    4085           5 :       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
    4086             :   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
    4087           5 :       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    4088           5 :   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
    4089             :   SDValue TLSIndex =
    4090           5 :       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
    4091           5 :   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
    4092           5 :   Chain = TLSIndex.getValue(1);
    4093             : 
    4094             :   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
    4095             :   // offset into the TLSArray.
    4096           5 :   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
    4097             :   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
    4098           5 :                              DAG.getConstant(3, DL, PtrVT));
    4099             :   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
    4100             :                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
    4101           5 :                             MachinePointerInfo());
    4102             :   Chain = TLS.getValue(1);
    4103             : 
    4104             :   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
    4105           5 :   const GlobalValue *GV = GA->getGlobal();
    4106             :   SDValue TGAHi = DAG.getTargetGlobalAddress(
    4107           5 :       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
    4108             :   SDValue TGALo = DAG.getTargetGlobalAddress(
    4109             :       GV, DL, PtrVT, 0,
    4110           5 :       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    4111             : 
    4112             :   // Add the offset from the start of the .tls section (section base).
    4113             :   SDValue Addr =
    4114           5 :       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
    4115             :                                  DAG.getTargetConstant(0, DL, MVT::i32)),
    4116             :               0);
    4117           5 :   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
    4118          10 :   return Addr;
    4119             : }
    4120             : 
    4121         104 : SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
    4122             :                                                      SelectionDAG &DAG) const {
    4123             :   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
    4124         104 :   if (DAG.getTarget().useEmulatedTLS())
    4125          38 :     return LowerToTLSEmulatedModel(GA, DAG);
    4126             : 
    4127          66 :   if (Subtarget->isTargetDarwin())
    4128          27 :     return LowerDarwinGlobalTLSAddress(Op, DAG);
    4129          39 :   if (Subtarget->isTargetELF())
    4130          34 :     return LowerELFGlobalTLSAddress(Op, DAG);
    4131           5 :   if (Subtarget->isTargetWindows())
    4132           5 :     return LowerWindowsGlobalTLSAddress(Op, DAG);
    4133             : 
    4134           0 :   llvm_unreachable("Unexpected platform trying to use TLS");
    4135             : }
    4136             : 
    4137         952 : SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
    4138         952 :   SDValue Chain = Op.getOperand(0);
    4139         952 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
    4140         952 :   SDValue LHS = Op.getOperand(2);
    4141         952 :   SDValue RHS = Op.getOperand(3);
    4142         952 :   SDValue Dest = Op.getOperand(4);
    4143             :   SDLoc dl(Op);
    4144             : 
    4145             :   // Handle f128 first, since lowering it will result in comparing the return
    4146             :   // value of a libcall against zero, which is just what the rest of LowerBR_CC
    4147             :   // is expecting to deal with.
    4148         952 :   if (LHS.getValueType() == MVT::f128) {
    4149           2 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    4150             : 
    4151             :     // If softenSetCCOperands returned a scalar, we need to compare the result
    4152             :     // against zero to select between true and false values.
    4153           1 :     if (!RHS.getNode()) {
    4154           0 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    4155           0 :       CC = ISD::SETNE;
    4156             :     }
    4157             :   }
    4158             : 
    4159             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
    4160             :   // instruction.
    4161         980 :   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
    4162          14 :       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    4163             :     // Only lower legal XALUO ops.
    4164          14 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
    4165           0 :       return SDValue();
    4166             : 
    4167             :     // The actual operation with overflow check.
    4168             :     AArch64CC::CondCode OFCC;
    4169             :     SDValue Value, Overflow;
    4170          28 :     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
    4171             : 
    4172          14 :     if (CC == ISD::SETNE)
    4173          28 :       OFCC = getInvertedCondCode(OFCC);
    4174          14 :     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
    4175             : 
    4176             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
    4177          14 :                        Overflow);
    4178             :   }
    4179             : 
    4180        1876 :   if (LHS.getValueType().isInteger()) {
    4181             :     assert((LHS.getValueType() == RHS.getValueType()) &&
    4182             :            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
    4183             : 
    4184             :     // If the RHS of the comparison is zero, we can potentially fold this
    4185             :     // to a specialized branch.
    4186             :     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
    4187        1472 :     if (RHSC && RHSC->getZExtValue() == 0) {
    4188         509 :       if (CC == ISD::SETEQ) {
    4189             :         // See if we can use a TBZ to fold in an AND as well.
    4190             :         // TBZ has a smaller branch displacement than CBZ.  If the offset is
    4191             :         // out of bounds, a late MI-layer pass rewrites branches.
    4192             :         // 403.gcc is an example that hits this case.
    4193             :         if (LHS.getOpcode() == ISD::AND &&
    4194         197 :             isa<ConstantSDNode>(LHS.getOperand(1)) &&
    4195             :             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
    4196          78 :           SDValue Test = LHS.getOperand(0);
    4197             :           uint64_t Mask = LHS.getConstantOperandVal(1);
    4198             :           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
    4199             :                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
    4200         156 :                              Dest);
    4201             :         }
    4202             : 
    4203         119 :         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
    4204         312 :       } else if (CC == ISD::SETNE) {
    4205             :         // See if we can use a TBZ to fold in an AND as well.
    4206             :         // TBZ has a smaller branch displacement than CBZ.  If the offset is
    4207             :         // out of bounds, a late MI-layer pass rewrites branches.
    4208             :         // 403.gcc is an example that hits this case.
    4209             :         if (LHS.getOpcode() == ISD::AND &&
    4210         255 :             isa<ConstantSDNode>(LHS.getOperand(1)) &&
    4211             :             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
    4212          29 :           SDValue Test = LHS.getOperand(0);
    4213             :           uint64_t Mask = LHS.getConstantOperandVal(1);
    4214             :           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
    4215             :                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
    4216          58 :                              Dest);
    4217             :         }
    4218             : 
    4219         226 :         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
    4220          88 :       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
    4221             :         // Don't combine AND since emitComparison converts the AND to an ANDS
    4222             :         // (a.k.a. TST) and the test in the test bit and branch instruction
    4223             :         // becomes redundant.  This would also increase register pressure.
    4224          29 :         uint64_t Mask = LHS.getValueSizeInBits() - 1;
    4225             :         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
    4226          58 :                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
    4227             :       }
    4228             :     }
    4229         692 :     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
    4230             :         LHS.getOpcode() != ISD::AND) {
    4231             :       // Don't combine AND since emitComparison converts the AND to an ANDS
    4232             :       // (a.k.a. TST) and the test in the test bit and branch instruction
    4233             :       // becomes redundant.  This would also increase register pressure.
    4234          20 :       uint64_t Mask = LHS.getValueSizeInBits() - 1;
    4235             :       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
    4236          40 :                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
    4237             :     }
    4238             : 
    4239         395 :     SDValue CCVal;
    4240         395 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    4241             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
    4242         395 :                        Cmp);
    4243             :   }
    4244             : 
    4245             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4246             :          LHS.getValueType() == MVT::f64);
    4247             : 
    4248             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    4249             :   // clean.  Some of them require two branches to implement.
    4250          42 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4251             :   AArch64CC::CondCode CC1, CC2;
    4252          42 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4253          42 :   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4254             :   SDValue BR1 =
    4255          42 :       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
    4256          42 :   if (CC2 != AArch64CC::AL) {
    4257           5 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4258             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
    4259           5 :                        Cmp);
    4260             :   }
    4261             : 
    4262          37 :   return BR1;
    4263             : }
    4264             : 
    4265          29 : SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
    4266             :                                               SelectionDAG &DAG) const {
    4267          29 :   EVT VT = Op.getValueType();
    4268             :   SDLoc DL(Op);
    4269             : 
    4270          29 :   SDValue In1 = Op.getOperand(0);
    4271          29 :   SDValue In2 = Op.getOperand(1);
    4272          58 :   EVT SrcVT = In2.getValueType();
    4273             : 
    4274          29 :   if (SrcVT.bitsLT(VT))
    4275           7 :     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
    4276          22 :   else if (SrcVT.bitsGT(VT))
    4277          10 :     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
    4278             : 
    4279          29 :   EVT VecVT;
    4280             :   uint64_t EltMask;
    4281          29 :   SDValue VecVal1, VecVal2;
    4282             : 
    4283          29 :   auto setVecVal = [&] (int Idx) {
    4284          58 :     if (!VT.isVector()) {
    4285         145 :       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
    4286          48 :                                           DAG.getUNDEF(VecVT), In1);
    4287          29 :       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
    4288          48 :                                           DAG.getUNDEF(VecVT), In2);
    4289             :     } else {
    4290          20 :       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
    4291          20 :       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
    4292             :     }
    4293          58 :   };
    4294             : 
    4295             :   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
    4296          15 :     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
    4297             :     EltMask = 0x80000000ULL;
    4298          15 :     setVecVal(AArch64::ssub);
    4299             :   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
    4300          10 :     VecVT = MVT::v2i64;
    4301             : 
    4302             :     // We want to materialize a mask with the high bit set, but the AdvSIMD
    4303             :     // immediate moves cannot materialize that in a single instruction for
    4304             :     // 64-bit elements. Instead, materialize zero and then negate it.
    4305             :     EltMask = 0;
    4306             : 
    4307          10 :     setVecVal(AArch64::dsub);
    4308             :   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
    4309           4 :     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
    4310             :     EltMask = 0x8000ULL;
    4311           4 :     setVecVal(AArch64::hsub);
    4312             :   } else {
    4313           0 :     llvm_unreachable("Invalid type for copysign!");
    4314             :   }
    4315             : 
    4316          29 :   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
    4317             : 
    4318             :   // If we couldn't materialize the mask above, then the mask vector will be
    4319             :   // the zero vector, and we need to negate it here.
    4320             :   if (VT == MVT::f64 || VT == MVT::v2f64) {
    4321          10 :     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
    4322          10 :     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
    4323          10 :     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
    4324             :   }
    4325             : 
    4326             :   SDValue Sel =
    4327          29 :       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
    4328             : 
    4329             :   if (VT == MVT::f16)
    4330           4 :     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
    4331             :   if (VT == MVT::f32)
    4332          11 :     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
    4333             :   else if (VT == MVT::f64)
    4334           4 :     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
    4335             :   else
    4336          10 :     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
    4337             : }
    4338             : 
    4339          34 : SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
    4340          68 :   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
    4341             :           Attribute::NoImplicitFloat))
    4342           4 :     return SDValue();
    4343             : 
    4344          30 :   if (!Subtarget->hasNEON())
    4345           3 :     return SDValue();
    4346             : 
    4347             :   // While there is no integer popcount instruction, it can
    4348             :   // be more efficiently lowered to the following sequence that uses
    4349             :   // AdvSIMD registers/instructions as long as the copies to/from
    4350             :   // the AdvSIMD registers are cheap.
    4351             :   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
    4352             :   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
    4353             :   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
    4354             :   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
    4355          27 :   SDValue Val = Op.getOperand(0);
    4356             :   SDLoc DL(Op);
    4357             :   EVT VT = Op.getValueType();
    4358             : 
    4359             :   if (VT == MVT::i32)
    4360          23 :     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
    4361          27 :   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
    4362             : 
    4363          27 :   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
    4364             :   SDValue UaddLV = DAG.getNode(
    4365             :       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
    4366          54 :       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
    4367             : 
    4368             :   if (VT == MVT::i64)
    4369           4 :     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
    4370          27 :   return UaddLV;
    4371             : }
    4372             : 
    4373         670 : SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
    4374             : 
    4375        1340 :   if (Op.getValueType().isVector())
    4376         529 :     return LowerVSETCC(Op, DAG);
    4377             : 
    4378         141 :   SDValue LHS = Op.getOperand(0);
    4379         141 :   SDValue RHS = Op.getOperand(1);
    4380         141 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    4381             :   SDLoc dl(Op);
    4382             : 
    4383             :   // We chose ZeroOrOneBooleanContents, so use zero and one.
    4384         141 :   EVT VT = Op.getValueType();
    4385         141 :   SDValue TVal = DAG.getConstant(1, dl, VT);
    4386         141 :   SDValue FVal = DAG.getConstant(0, dl, VT);
    4387             : 
    4388             :   // Handle f128 first, since one possible outcome is a normal integer
    4389             :   // comparison which gets picked up by the next if statement.
    4390         141 :   if (LHS.getValueType() == MVT::f128) {
    4391          10 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    4392             : 
    4393             :     // If softenSetCCOperands returned a scalar, use it.
    4394           5 :     if (!RHS.getNode()) {
    4395             :       assert(LHS.getValueType() == Op.getValueType() &&
    4396             :              "Unexpected setcc expansion!");
    4397           1 :       return LHS;
    4398             :     }
    4399             :   }
    4400             : 
    4401         280 :   if (LHS.getValueType().isInteger()) {
    4402         101 :     SDValue CCVal;
    4403             :     SDValue Cmp =
    4404         101 :         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
    4405             : 
    4406             :     // Note that we inverted the condition above, so we reverse the order of
    4407             :     // the true and false operands here.  This will allow the setcc to be
    4408             :     // matched to a single CSINC instruction.
    4409         101 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
    4410             :   }
    4411             : 
    4412             :   // Now we know we're dealing with FP values.
    4413             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4414             :          LHS.getValueType() == MVT::f64);
    4415             : 
    4416             :   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
    4417             :   // and do the comparison.
    4418          39 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4419             : 
    4420             :   AArch64CC::CondCode CC1, CC2;
    4421          39 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4422          39 :   if (CC2 == AArch64CC::AL) {
    4423          35 :     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
    4424          35 :     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4425             : 
    4426             :     // Note that we inverted the condition above, so we reverse the order of
    4427             :     // the true and false operands here.  This will allow the setcc to be
    4428             :     // matched to a single CSINC instruction.
    4429          35 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
    4430             :   } else {
    4431             :     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
    4432             :     // totally clean.  Some of them require two CSELs to implement.  As is in
    4433             :     // this case, we emit the first CSEL and then emit a second using the output
    4434             :     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
    4435             : 
    4436             :     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
    4437           4 :     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4438             :     SDValue CS1 =
    4439           4 :         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
    4440             : 
    4441           4 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4442           4 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
    4443             :   }
    4444             : }
    4445             : 
    4446         559 : SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
    4447             :                                               SDValue RHS, SDValue TVal,
    4448             :                                               SDValue FVal, const SDLoc &dl,
    4449             :                                               SelectionDAG &DAG) const {
    4450             :   // Handle f128 first, because it will result in a comparison of some RTLIB
    4451             :   // call result against zero.
    4452         559 :   if (LHS.getValueType() == MVT::f128) {
    4453           0 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    4454             : 
    4455             :     // If softenSetCCOperands returned a scalar, we need to compare the result
    4456             :     // against zero to select between true and false values.
    4457           0 :     if (!RHS.getNode()) {
    4458           0 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    4459           0 :       CC = ISD::SETNE;
    4460             :     }
    4461             :   }
    4462             : 
    4463             :   // Also handle f16, for which we need to do a f32 comparison.
    4464         853 :   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
    4465         114 :     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
    4466         114 :     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
    4467             :   }
    4468             : 
    4469             :   // Next, handle integers.
    4470        1118 :   if (LHS.getValueType().isInteger()) {
    4471             :     assert((LHS.getValueType() == RHS.getValueType()) &&
    4472             :            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
    4473             : 
    4474             :     unsigned Opcode = AArch64ISD::CSEL;
    4475             : 
    4476             :     // If both the TVal and the FVal are constants, see if we can swap them in
    4477             :     // order to for a CSINV or CSINC out of them.
    4478             :     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
    4479             :     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
    4480             : 
    4481          95 :     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
    4482             :       std::swap(TVal, FVal);
    4483             :       std::swap(CTVal, CFVal);
    4484           8 :       CC = ISD::getSetCCInverse(CC, true);
    4485         287 :     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
    4486             :       std::swap(TVal, FVal);
    4487             :       std::swap(CTVal, CFVal);
    4488           0 :       CC = ISD::getSetCCInverse(CC, true);
    4489         209 :     } else if (TVal.getOpcode() == ISD::XOR) {
    4490             :       // If TVal is a NOT we want to swap TVal and FVal so that we can match
    4491             :       // with a CSINV rather than a CSEL.
    4492           5 :       if (isAllOnesConstant(TVal.getOperand(1))) {
    4493             :         std::swap(TVal, FVal);
    4494             :         std::swap(CTVal, CFVal);
    4495           5 :         CC = ISD::getSetCCInverse(CC, true);
    4496             :       }
    4497         204 :     } else if (TVal.getOpcode() == ISD::SUB) {
    4498             :       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
    4499             :       // that we can match with a CSNEG rather than a CSEL.
    4500           6 :       if (isNullConstant(TVal.getOperand(0))) {
    4501             :         std::swap(TVal, FVal);
    4502             :         std::swap(CTVal, CFVal);
    4503           6 :         CC = ISD::getSetCCInverse(CC, true);
    4504             :       }
    4505         198 :     } else if (CTVal && CFVal) {
    4506          30 :       const int64_t TrueVal = CTVal->getSExtValue();
    4507          30 :       const int64_t FalseVal = CFVal->getSExtValue();
    4508             :       bool Swap = false;
    4509             : 
    4510             :       // If both TVal and FVal are constants, see if FVal is the
    4511             :       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
    4512             :       // instead of a CSEL in that case.
    4513          30 :       if (TrueVal == ~FalseVal) {
    4514             :         Opcode = AArch64ISD::CSINV;
    4515          28 :       } else if (TrueVal == -FalseVal) {
    4516             :         Opcode = AArch64ISD::CSNEG;
    4517             :       } else if (TVal.getValueType() == MVT::i32) {
    4518             :         // If our operands are only 32-bit wide, make sure we use 32-bit
    4519             :         // arithmetic for the check whether we can use CSINC. This ensures that
    4520             :         // the addition in the check will wrap around properly in case there is
    4521             :         // an overflow (which would not be the case if we do the check with
    4522             :         // 64-bit arithmetic).
    4523          20 :         const uint32_t TrueVal32 = CTVal->getZExtValue();
    4524          20 :         const uint32_t FalseVal32 = CFVal->getZExtValue();
    4525             : 
    4526          10 :         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
    4527             :           Opcode = AArch64ISD::CSINC;
    4528             : 
    4529           2 :           if (TrueVal32 > FalseVal32) {
    4530             :             Swap = true;
    4531             :           }
    4532             :         }
    4533             :         // 64-bit check whether we can use CSINC.
    4534          28 :       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
    4535             :         Opcode = AArch64ISD::CSINC;
    4536             : 
    4537           4 :         if (TrueVal > FalseVal) {
    4538             :           Swap = true;
    4539             :         }
    4540             :       }
    4541             : 
    4542             :       // Swap TVal and FVal if necessary.
    4543             :       if (Swap) {
    4544             :         std::swap(TVal, FVal);
    4545             :         std::swap(CTVal, CFVal);
    4546           3 :         CC = ISD::getSetCCInverse(CC, true);
    4547             :       }
    4548             : 
    4549          30 :       if (Opcode != AArch64ISD::CSEL) {
    4550             :         // Drop FVal since we can get its value by simply inverting/negating
    4551             :         // TVal.
    4552             :         FVal = TVal;
    4553             :       }
    4554             :     }
    4555             : 
    4556             :     // Avoid materializing a constant when possible by reusing a known value in
    4557             :     // a register.  However, don't perform this optimization if the known value
    4558             :     // is one, zero or negative one in the case of a CSEL.  We can always
    4559             :     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
    4560             :     // FVal, respectively.
    4561             :     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
    4562         566 :     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
    4563         249 :         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
    4564          27 :       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    4565             :       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
    4566             :       // "a != C ? x : a" to avoid materializing C.
    4567          27 :       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
    4568           4 :         TVal = LHS;
    4569          23 :       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
    4570           2 :         FVal = LHS;
    4571         196 :     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
    4572             :       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
    4573             :       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
    4574             :       // avoid materializing C.
    4575           1 :       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    4576           1 :       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
    4577             :         Opcode = AArch64ISD::CSINV;
    4578           1 :         TVal = LHS;
    4579           1 :         FVal = DAG.getConstant(0, dl, FVal.getValueType());
    4580             :       }
    4581             :     }
    4582             : 
    4583         217 :     SDValue CCVal;
    4584         217 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    4585         217 :     EVT VT = TVal.getValueType();
    4586         217 :     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
    4587             :   }
    4588             : 
    4589             :   // Now we know we're dealing with FP values.
    4590             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4591             :          LHS.getValueType() == MVT::f64);
    4592             :   assert(LHS.getValueType() == RHS.getValueType());
    4593         342 :   EVT VT = TVal.getValueType();
    4594         342 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4595             : 
    4596             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    4597             :   // clean.  Some of them require two CSELs to implement.
    4598             :   AArch64CC::CondCode CC1, CC2;
    4599         342 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4600             : 
    4601         342 :   if (DAG.getTarget().Options.UnsafeFPMath) {
    4602             :     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
    4603             :     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
    4604             :     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
    4605          26 :     if (RHSVal && RHSVal->isZero()) {
    4606             :       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
    4607             :       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
    4608             : 
    4609          19 :       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
    4610          23 :           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
    4611             :         TVal = LHS;
    4612          16 :       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
    4613          17 :                CFVal && CFVal->isZero() &&
    4614           4 :                FVal.getValueType() == LHS.getValueType())
    4615             :         FVal = LHS;
    4616             :     }
    4617             :   }
    4618             : 
    4619             :   // Emit first, and possibly only, CSEL.
    4620         342 :   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4621         342 :   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
    4622             : 
    4623             :   // If we need a second CSEL, emit it, using the output of the first as the
    4624             :   // RHS.  We're effectively OR'ing the two CC's together.
    4625         342 :   if (CC2 != AArch64CC::AL) {
    4626          50 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4627          50 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
    4628             :   }
    4629             : 
    4630             :   // Otherwise, return the output of the first CSEL.
    4631         292 :   return CS1;
    4632             : }
    4633             : 
    4634         213 : SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
    4635             :                                               SelectionDAG &DAG) const {
    4636         213 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    4637         213 :   SDValue LHS = Op.getOperand(0);
    4638         213 :   SDValue RHS = Op.getOperand(1);
    4639         213 :   SDValue TVal = Op.getOperand(2);
    4640         213 :   SDValue FVal = Op.getOperand(3);
    4641             :   SDLoc DL(Op);
    4642         426 :   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
    4643             : }
    4644             : 
    4645         359 : SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
    4646             :                                            SelectionDAG &DAG) const {
    4647         359 :   SDValue CCVal = Op->getOperand(0);
    4648         359 :   SDValue TVal = Op->getOperand(1);
    4649         359 :   SDValue FVal = Op->getOperand(2);
    4650             :   SDLoc DL(Op);
    4651             : 
    4652             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
    4653             :   // instruction.
    4654             :   if (isOverflowIntrOpRes(CCVal)) {
    4655             :     // Only lower legal XALUO ops.
    4656          13 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
    4657           0 :       return SDValue();
    4658             : 
    4659             :     AArch64CC::CondCode OFCC;
    4660             :     SDValue Value, Overflow;
    4661          26 :     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
    4662          13 :     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
    4663             : 
    4664             :     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
    4665          13 :                        CCVal, Overflow);
    4666             :   }
    4667             : 
    4668             :   // Lower it the same way as we would lower a SELECT_CC node.
    4669             :   ISD::CondCode CC;
    4670         346 :   SDValue LHS, RHS;
    4671         346 :   if (CCVal.getOpcode() == ISD::SETCC) {
    4672         280 :     LHS = CCVal.getOperand(0);
    4673         280 :     RHS = CCVal.getOperand(1);
    4674         280 :     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
    4675             :   } else {
    4676          66 :     LHS = CCVal;
    4677          66 :     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
    4678             :     CC = ISD::SETNE;
    4679             :   }
    4680         346 :   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
    4681             : }
    4682             : 
    4683          27 : SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
    4684             :                                               SelectionDAG &DAG) const {
    4685             :   // Jump table entries as PC relative offsets. No additional tweaking
    4686             :   // is necessary here. Just get the address of the jump table.
    4687             :   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
    4688             : 
    4689          28 :   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    4690           1 :       !Subtarget->isTargetMachO()) {
    4691           1 :     return getAddrLarge(JT, DAG);
    4692             :   }
    4693          26 :   return getAddr(JT, DAG);
    4694             : }
    4695             : 
    4696         145 : SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
    4697             :                                                  SelectionDAG &DAG) const {
    4698             :   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
    4699             : 
    4700         145 :   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
    4701             :     // Use the GOT for the large code model on iOS.
    4702           8 :     if (Subtarget->isTargetMachO()) {
    4703           0 :       return getGOT(CP, DAG);
    4704             :     }
    4705           4 :     return getAddrLarge(CP, DAG);
    4706             :   } else {
    4707         141 :     return getAddr(CP, DAG);
    4708             :   }
    4709             : }
    4710             : 
    4711           6 : SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
    4712             :                                                SelectionDAG &DAG) const {
    4713             :   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
    4714           8 :   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    4715           2 :       !Subtarget->isTargetMachO()) {
    4716           2 :     return getAddrLarge(BA, DAG);
    4717             :   } else {
    4718           4 :     return getAddr(BA, DAG);
    4719             :   }
    4720             : }
    4721             : 
    4722           8 : SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
    4723             :                                                  SelectionDAG &DAG) const {
    4724             :   AArch64FunctionInfo *FuncInfo =
    4725           8 :       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    4726             : 
    4727             :   SDLoc DL(Op);
    4728             :   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
    4729          16 :                                  getPointerTy(DAG.getDataLayout()));
    4730           8 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4731             :   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
    4732          16 :                       MachinePointerInfo(SV));
    4733             : }
    4734             : 
    4735          12 : SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
    4736             :                                                   SelectionDAG &DAG) const {
    4737             :   AArch64FunctionInfo *FuncInfo =
    4738          12 :       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    4739             : 
    4740             :   SDLoc DL(Op);
    4741          12 :   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
    4742             :                                      ? FuncInfo->getVarArgsGPRIndex()
    4743             :                                      : FuncInfo->getVarArgsStackIndex(),
    4744          24 :                                  getPointerTy(DAG.getDataLayout()));
    4745          12 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4746             :   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
    4747          24 :                       MachinePointerInfo(SV));
    4748             : }
    4749             : 
    4750           5 : SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
    4751             :                                                 SelectionDAG &DAG) const {
    4752             :   // The layout of the va_list struct is specified in the AArch64 Procedure Call
    4753             :   // Standard, section B.3.
    4754           5 :   MachineFunction &MF = DAG.getMachineFunction();
    4755           5 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    4756           5 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    4757             :   SDLoc DL(Op);
    4758             : 
    4759           5 :   SDValue Chain = Op.getOperand(0);
    4760           5 :   SDValue VAList = Op.getOperand(1);
    4761           5 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4762             :   SmallVector<SDValue, 4> MemOps;
    4763             : 
    4764             :   // void *__stack at offset 0
    4765           5 :   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
    4766           5 :   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
    4767           5 :                                 MachinePointerInfo(SV), /* Alignment = */ 8));
    4768             : 
    4769             :   // void *__gr_top at offset 8
    4770           5 :   int GPRSize = FuncInfo->getVarArgsGPRSize();
    4771           5 :   if (GPRSize > 0) {
    4772             :     SDValue GRTop, GRTopAddr;
    4773             : 
    4774           3 :     GRTopAddr =
    4775           9 :         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
    4776             : 
    4777           3 :     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
    4778           3 :     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
    4779           6 :                         DAG.getConstant(GPRSize, DL, PtrVT));
    4780             : 
    4781           3 :     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
    4782             :                                   MachinePointerInfo(SV, 8),
    4783           3 :                                   /* Alignment = */ 8));
    4784             :   }
    4785             : 
    4786             :   // void *__vr_top at offset 16
    4787           5 :   int FPRSize = FuncInfo->getVarArgsFPRSize();
    4788           5 :   if (FPRSize > 0) {
    4789             :     SDValue VRTop, VRTopAddr;
    4790           4 :     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4791           8 :                             DAG.getConstant(16, DL, PtrVT));
    4792             : 
    4793           4 :     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
    4794           4 :     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
    4795           8 :                         DAG.getConstant(FPRSize, DL, PtrVT));
    4796             : 
    4797           4 :     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
    4798             :                                   MachinePointerInfo(SV, 16),
    4799           4 :                                   /* Alignment = */ 8));
    4800             :   }
    4801             : 
    4802             :   // int __gr_offs at offset 24
    4803             :   SDValue GROffsAddr =
    4804          10 :       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
    4805           5 :   MemOps.push_back(DAG.getStore(
    4806           5 :       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
    4807          10 :       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
    4808             : 
    4809             :   // int __vr_offs at offset 28
    4810             :   SDValue VROffsAddr =
    4811          10 :       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
    4812           5 :   MemOps.push_back(DAG.getStore(
    4813           5 :       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
    4814          10 :       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
    4815             : 
    4816          10 :   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
    4817             : }
    4818             : 
    4819          25 : SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
    4820             :                                             SelectionDAG &DAG) const {
    4821          25 :   MachineFunction &MF = DAG.getMachineFunction();
    4822             : 
    4823          46 :   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
    4824          12 :     return LowerWin64_VASTART(Op, DAG);
    4825             :   else if (Subtarget->isTargetDarwin())
    4826           8 :     return LowerDarwin_VASTART(Op, DAG);
    4827             :   else
    4828           5 :     return LowerAAPCS_VASTART(Op, DAG);
    4829             : }
    4830             : 
    4831           2 : SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
    4832             :                                            SelectionDAG &DAG) const {
    4833             :   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
    4834             :   // pointer.
    4835             :   SDLoc DL(Op);
    4836             :   unsigned VaListSize =
    4837           4 :       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
    4838           2 :   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
    4839           2 :   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
    4840             : 
    4841             :   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
    4842             :                        Op.getOperand(2),
    4843             :                        DAG.getConstant(VaListSize, DL, MVT::i32),
    4844             :                        8, false, false, false, MachinePointerInfo(DestSV),
    4845           6 :                        MachinePointerInfo(SrcSV));
    4846             : }
    4847             : 
    4848          16 : SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
    4849             :   assert(Subtarget->isTargetDarwin() &&
    4850             :          "automatic va_arg instruction only works on Darwin");
    4851             : 
    4852          16 :   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4853          16 :   EVT VT = Op.getValueType();
    4854             :   SDLoc DL(Op);
    4855          16 :   SDValue Chain = Op.getOperand(0);
    4856          16 :   SDValue Addr = Op.getOperand(1);
    4857          16 :   unsigned Align = Op.getConstantOperandVal(3);
    4858          16 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    4859             : 
    4860          16 :   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
    4861          16 :   Chain = VAList.getValue(1);
    4862             : 
    4863          16 :   if (Align > 8) {
    4864             :     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
    4865           1 :     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4866           2 :                          DAG.getConstant(Align - 1, DL, PtrVT));
    4867           1 :     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
    4868           2 :                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
    4869             :   }
    4870             : 
    4871          16 :   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
    4872          32 :   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
    4873             : 
    4874             :   // Scalar integer and FP values smaller than 64 bits are implicitly extended
    4875             :   // up to 64 bits.  At the very least, we have to increase the striding of the
    4876             :   // vaargs list to match this, and for FP values we need to introduce
    4877             :   // FP_ROUND nodes as well.
    4878          31 :   if (VT.isInteger() && !VT.isVector())
    4879             :     ArgSize = 8;
    4880             :   bool NeedFPTrunc = false;
    4881          17 :   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
    4882             :     ArgSize = 8;
    4883             :     NeedFPTrunc = true;
    4884             :   }
    4885             : 
    4886             :   // Increment the pointer, VAList, to the next vaarg
    4887             :   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4888          32 :                                DAG.getConstant(ArgSize, DL, PtrVT));
    4889             :   // Store the incremented VAList to the legalized pointer
    4890             :   SDValue APStore =
    4891          16 :       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
    4892             : 
    4893             :   // Load the actual argument out of the pointer VAList
    4894          16 :   if (NeedFPTrunc) {
    4895             :     // Load the value as an f64.
    4896             :     SDValue WideFP =
    4897           1 :         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
    4898             :     // Round the value down to an f32.
    4899             :     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
    4900           1 :                                    DAG.getIntPtrConstant(1, DL));
    4901           1 :     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
    4902             :     // Merge the rounded value with the chain output of the load.
    4903           1 :     return DAG.getMergeValues(Ops, DL);
    4904             :   }
    4905             : 
    4906          15 :   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
    4907             : }
    4908             : 
    4909           4 : SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
    4910             :                                               SelectionDAG &DAG) const {
    4911           4 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    4912             :   MFI.setFrameAddressIsTaken(true);
    4913             : 
    4914           4 :   EVT VT = Op.getValueType();
    4915             :   SDLoc DL(Op);
    4916           8 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    4917             :   SDValue FrameAddr =
    4918           4 :       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
    4919          16 :   while (Depth--)
    4920           6 :     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
    4921           6 :                             MachinePointerInfo());
    4922           8 :   return FrameAddr;
    4923             : }
    4924             : 
    4925             : // FIXME? Maybe this could be a TableGen attribute on some registers and
    4926             : // this table could be generated automatically from RegInfo.
    4927          10 : unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
    4928             :                                                   SelectionDAG &DAG) const {
    4929          10 :   unsigned Reg = StringSwitch<unsigned>(RegName)
    4930             :                        .Case("sp", AArch64::SP)
    4931             :                        .Case("x18", AArch64::X18)
    4932             :                        .Case("w18", AArch64::W18)
    4933             :                        .Case("x20", AArch64::X20)
    4934             :                        .Case("w20", AArch64::W20)
    4935             :                        .Default(0);
    4936          12 :   if (((Reg == AArch64::X18 || Reg == AArch64::W18) &&
    4937          20 :       !Subtarget->isX18Reserved()) ||
    4938          10 :       ((Reg == AArch64::X20 || Reg == AArch64::W20) &&
    4939           0 :       !Subtarget->isX20Reserved()))
    4940             :     Reg = 0;
    4941          10 :   if (Reg)
    4942           6 :     return Reg;
    4943           4 :   report_fatal_error(Twine("Invalid register name \""
    4944             :                               + StringRef(RegName)  + "\"."));
    4945             : }
    4946             : 
    4947           6 : SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
    4948             :                                                SelectionDAG &DAG) const {
    4949           6 :   MachineFunction &MF = DAG.getMachineFunction();
    4950           6 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    4951             :   MFI.setReturnAddressIsTaken(true);
    4952             : 
    4953           6 :   EVT VT = Op.getValueType();
    4954             :   SDLoc DL(Op);
    4955          12 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    4956           6 :   if (Depth) {
    4957           2 :     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
    4958           4 :     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
    4959             :     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
    4960             :                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
    4961           4 :                        MachinePointerInfo());
    4962             :   }
    4963             : 
    4964             :   // Return LR, which contains the return address. Mark it an implicit live-in.
    4965           4 :   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
    4966           4 :   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
    4967             : }
    4968             : 
    4969             : /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
    4970             : /// i64 values and take a 2 x i64 value to shift plus a shift amount.
    4971           2 : SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
    4972             :                                                     SelectionDAG &DAG) const {
    4973             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    4974           2 :   EVT VT = Op.getValueType();
    4975           2 :   unsigned VTBits = VT.getSizeInBits();
    4976             :   SDLoc dl(Op);
    4977           2 :   SDValue ShOpLo = Op.getOperand(0);
    4978           2 :   SDValue ShOpHi = Op.getOperand(1);
    4979           2 :   SDValue ShAmt = Op.getOperand(2);
    4980           2 :   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
    4981             : 
    4982             :   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
    4983             : 
    4984             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
    4985           4 :                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
    4986           2 :   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
    4987             : 
    4988             :   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
    4989             :   // is "undef". We wanted 0, so CSEL it directly.
    4990             :   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
    4991           2 :                                ISD::SETEQ, dl, DAG);
    4992           2 :   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
    4993           2 :   HiBitsForLo =
    4994           4 :       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
    4995           4 :                   HiBitsForLo, CCVal, Cmp);
    4996             : 
    4997             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
    4998           4 :                                    DAG.getConstant(VTBits, dl, MVT::i64));
    4999             : 
    5000           2 :   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
    5001             :   SDValue LoForNormalShift =
    5002           2 :       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
    5003             : 
    5004           2 :   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
    5005           4 :                        dl, DAG);
    5006           2 :   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
    5007           2 :   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
    5008             :   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
    5009           2 :                            LoForNormalShift, CCVal, Cmp);
    5010             : 
    5011             :   // AArch64 shifts larger than the register width are wrapped rather than
    5012             :   // clamped, so we can't just emit "hi >> x".
    5013           2 :   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
    5014             :   SDValue HiForBigShift =
    5015             :       Opc == ISD::SRA
    5016             :           ? DAG.getNode(Opc, dl, VT, ShOpHi,
    5017           3 :                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
    5018           3 :           : DAG.getConstant(0, dl, VT);
    5019             :   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
    5020           2 :                            HiForNormalShift, CCVal, Cmp);
    5021             : 
    5022           2 :   SDValue Ops[2] = { Lo, Hi };
    5023           4 :   return DAG.getMergeValues(Ops, dl);
    5024             : }
    5025             : 
    5026             : /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
    5027             : /// i64 values and take a 2 x i64 value to shift plus a shift amount.
    5028           1 : SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
    5029             :                                                    SelectionDAG &DAG) const {
    5030             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    5031           1 :   EVT VT = Op.getValueType();
    5032           1 :   unsigned VTBits = VT.getSizeInBits();
    5033             :   SDLoc dl(Op);
    5034           1 :   SDValue ShOpLo = Op.getOperand(0);
    5035           1 :   SDValue ShOpHi = Op.getOperand(1);
    5036           1 :   SDValue ShAmt = Op.getOperand(2);
    5037             : 
    5038             :   assert(Op.getOpcode() == ISD::SHL_PARTS);
    5039             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
    5040           2 :                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
    5041           1 :   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
    5042             : 
    5043             :   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
    5044             :   // is "undef". We wanted 0, so CSEL it directly.
    5045             :   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
    5046           1 :                                ISD::SETEQ, dl, DAG);
    5047           1 :   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
    5048           1 :   LoBitsForHi =
    5049           2 :       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
    5050           2 :                   LoBitsForHi, CCVal, Cmp);
    5051             : 
    5052             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
    5053           2 :                                    DAG.getConstant(VTBits, dl, MVT::i64));
    5054           1 :   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
    5055             :   SDValue HiForNormalShift =
    5056           1 :       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
    5057             : 
    5058           1 :   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
    5059             : 
    5060           1 :   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
    5061           2 :                        dl, DAG);
    5062           1 :   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
    5063             :   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
    5064           1 :                            HiForNormalShift, CCVal, Cmp);
    5065             : 
    5066             :   // AArch64 shifts of larger than register sizes are wrapped rather than
    5067             :   // clamped, so we can't just emit "lo << a" if a is too big.
    5068           1 :   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
    5069           1 :   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
    5070             :   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
    5071           1 :                            LoForNormalShift, CCVal, Cmp);
    5072             : 
    5073           1 :   SDValue Ops[2] = { Lo, Hi };
    5074           2 :   return DAG.getMergeValues(Ops, dl);
    5075             : }
    5076             : 
    5077        1249 : bool AArch64TargetLowering::isOffsetFoldingLegal(
    5078             :     const GlobalAddressSDNode *GA) const {
    5079             :   // Offsets are folded in the DAG combine rather than here so that we can
    5080             :   // intelligently choose an offset based on the uses.
    5081        1249 :   return false;
    5082             : }
    5083             : 
    5084         586 : bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
    5085             :   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
    5086             :   // FIXME: We should be able to handle f128 as well with a clever lowering.
    5087         586 :   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
    5088          22 :                           (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
    5089             :     LLVM_DEBUG(
    5090             :         dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
    5091             :     return true;
    5092             :   }
    5093             : 
    5094             :   StringRef FPType;
    5095             :   bool IsLegal = false;
    5096             :   SmallString<128> ImmStrVal;
    5097         375 :   Imm.toString(ImmStrVal);
    5098             : 
    5099             :   if (VT == MVT::f64) {
    5100             :     FPType = "f64";
    5101         115 :     IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
    5102             :   } else if (VT == MVT::f32) {
    5103             :     FPType = "f32";
    5104         214 :     IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
    5105          36 :   } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
    5106             :     FPType = "f16";
    5107          22 :     IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
    5108             :   }
    5109             : 
    5110         351 :   if (IsLegal) {
    5111             :     LLVM_DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal
    5112             :                       << "\n");
    5113             :     return true;
    5114             :   }
    5115             : 
    5116             :   if (!FPType.empty())
    5117             :     LLVM_DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal
    5118             :                       << "\n");
    5119             :   else
    5120             :     LLVM_DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal
    5121             :                       << ": unsupported fp type\n");
    5122             : 
    5123          90 :   return false;
    5124             : }
    5125             : 
    5126             : //===----------------------------------------------------------------------===//
    5127             : //                          AArch64 Optimization Hooks
    5128             : //===----------------------------------------------------------------------===//
    5129             : 
    5130          37 : static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
    5131             :                            SDValue Operand, SelectionDAG &DAG,
    5132             :                            int &ExtraSteps) {
    5133          37 :   EVT VT = Operand.getValueType();
    5134          37 :   if (ST->hasNEON() &&
    5135             :       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
    5136             :        VT == MVT::f32 || VT == MVT::v1f32 ||
    5137             :        VT == MVT::v2f32 || VT == MVT::v4f32)) {
    5138          29 :     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
    5139             :       // For the reciprocal estimates, convergence is quadratic, so the number
    5140             :       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
    5141             :       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
    5142             :       // the result for float (23 mantissa bits) is 2 and for double (52
    5143             :       // mantissa bits) is 3.
    5144          58 :       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
    5145             : 
    5146          58 :     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
    5147             :   }
    5148             : 
    5149           8 :   return SDValue();
    5150             : }
    5151             : 
    5152          61 : SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
    5153             :                                                SelectionDAG &DAG, int Enabled,
    5154             :                                                int &ExtraSteps,
    5155             :                                                bool &UseOneConst,
    5156             :                                                bool Reciprocal) const {
    5157          61 :   if (Enabled == ReciprocalEstimate::Enabled ||
    5158          61 :       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
    5159          52 :     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
    5160          26 :                                        DAG, ExtraSteps)) {
    5161             :       SDLoc DL(Operand);
    5162          20 :       EVT VT = Operand.getValueType();
    5163             : 
    5164             :       SDNodeFlags Flags;
    5165             :       Flags.setAllowReassociation(true);
    5166             : 
    5167             :       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
    5168             :       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
    5169          69 :       for (int i = ExtraSteps; i > 0; --i) {
    5170             :         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
    5171          49 :                                    Flags);
    5172          49 :         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
    5173          49 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
    5174             :       }
    5175          20 :       if (!Reciprocal) {
    5176          11 :         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    5177          33 :                                       VT);
    5178          11 :         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
    5179          11 :         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
    5180             : 
    5181          11 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
    5182             :         // Correct the result if the operand is 0.0.
    5183          11 :         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
    5184          22 :                                VT, Eq, Operand, Estimate);
    5185             :       }
    5186             : 
    5187          20 :       ExtraSteps = 0;
    5188          20 :       return Estimate;
    5189             :     }
    5190             : 
    5191          41 :   return SDValue();
    5192             : }
    5193             : 
    5194          56 : SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
    5195             :                                                 SelectionDAG &DAG, int Enabled,
    5196             :                                                 int &ExtraSteps) const {
    5197          56 :   if (Enabled == ReciprocalEstimate::Enabled)
    5198          22 :     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
    5199          11 :                                        DAG, ExtraSteps)) {
    5200             :       SDLoc DL(Operand);
    5201           9 :       EVT VT = Operand.getValueType();
    5202             : 
    5203             :       SDNodeFlags Flags;
    5204             :       Flags.setAllowReassociation(true);
    5205             : 
    5206             :       // Newton reciprocal iteration: E * (2 - X * E)
    5207             :       // AArch64 reciprocal iteration instruction: (2 - M * N)
    5208          31 :       for (int i = ExtraSteps; i > 0; --i) {
    5209             :         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
    5210          22 :                                    Estimate, Flags);
    5211          22 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
    5212             :       }
    5213             : 
    5214           9 :       ExtraSteps = 0;
    5215           9 :       return Estimate;
    5216             :     }
    5217             : 
    5218          47 :   return SDValue();
    5219             : }
    5220             : 
    5221             : //===----------------------------------------------------------------------===//
    5222             : //                          AArch64 Inline Assembly Support
    5223             : //===----------------------------------------------------------------------===//
    5224             : 
    5225             : // Table of Constraints
    5226             : // TODO: This is the current set of constraints supported by ARM for the
    5227             : // compiler, not all of them may make sense.
    5228             : //
    5229             : // r - A general register
    5230             : // w - An FP/SIMD register of some size in the range v0-v31
    5231             : // x - An FP/SIMD register of some size in the range v0-v15
    5232             : // I - Constant that can be used with an ADD instruction
    5233             : // J - Constant that can be used with a SUB instruction
    5234             : // K - Constant that can be used with a 32-bit logical instruction
    5235             : // L - Constant that can be used with a 64-bit logical instruction
    5236             : // M - Constant that can be used as a 32-bit MOV immediate
    5237             : // N - Constant that can be used as a 64-bit MOV immediate
    5238             : // Q - A memory reference with base register and no offset
    5239             : // S - A symbolic address
    5240             : // Y - Floating point constant zero
    5241             : // Z - Integer constant zero
    5242             : //
    5243             : //   Note that general register operands will be output using their 64-bit x
    5244             : // register name, whatever the size of the variable, unless the asm operand
    5245             : // is prefixed by the %w modifier. Floating-point and SIMD register operands
    5246             : // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
    5247             : // %q modifier.
    5248          22 : const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
    5249             :   // At this point, we have to lower this constraint to something else, so we
    5250             :   // lower it to an "r" or "w". However, by doing this we will force the result
    5251             :   // to be in register, while the X constraint is much more permissive.
    5252             :   //
    5253             :   // Although we are correct (we are free to emit anything, without
    5254             :   // constraints), we might break use cases that would expect us to be more
    5255             :   // efficient and emit something else.
    5256          22 :   if (!Subtarget->hasFPARMv8())
    5257             :     return "r";
    5258             : 
    5259          19 :   if (ConstraintVT.isFloatingPoint())
    5260             :     return "w";
    5261             : 
    5262          20 :   if (ConstraintVT.isVector() &&
    5263           4 :      (ConstraintVT.getSizeInBits() == 64 ||
    5264             :       ConstraintVT.getSizeInBits() == 128))
    5265             :     return "w";
    5266             : 
    5267             :   return "r";
    5268             : }
    5269             : 
    5270             : /// getConstraintType - Given a constraint letter, return the type of
    5271             : /// constraint it is for this target.
    5272             : AArch64TargetLowering::ConstraintType
    5273       15294 : AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
    5274       15294 :   if (Constraint.size() == 1) {
    5275        1132 :     switch (Constraint[0]) {
    5276             :     default:
    5277             :       break;
    5278             :     case 'z':
    5279             :       return C_Other;
    5280          68 :     case 'x':
    5281             :     case 'w':
    5282          68 :       return C_RegisterClass;
    5283             :     // An address with a single base register. Due to the way we
    5284             :     // currently handle addresses it is the same as 'r'.
    5285           6 :     case 'Q':
    5286           6 :       return C_Memory;
    5287             :     case 'S': // A symbolic address
    5288             :       return C_Other;
    5289             :     }
    5290             :   }
    5291       15176 :   return TargetLowering::getConstraintType(Constraint);
    5292             : }
    5293             : 
    5294             : /// Examine constraint type and operand type and determine a weight value.
    5295             : /// This object must already have been set up with the operand type
    5296             : /// and the current alternative constraint selected.
    5297             : TargetLowering::ConstraintWeight
    5298           0 : AArch64TargetLowering::getSingleConstraintMatchWeight(
    5299             :     AsmOperandInfo &info, const char *constraint) const {
    5300             :   ConstraintWeight weight = CW_Invalid;
    5301           0 :   Value *CallOperandVal = info.CallOperandVal;
    5302             :   // If we don't have a value, we can't do a match,
    5303             :   // but allow it at the lowest weight.
    5304           0 :   if (!CallOperandVal)
    5305             :     return CW_Default;
    5306           0 :   Type *type = CallOperandVal->getType();
    5307             :   // Look at the constraint type.
    5308           0 :   switch (*constraint) {
    5309           0 :   default:
    5310           0 :     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
    5311           0 :     break;
    5312             :   case 'x':
    5313             :   case 'w':
    5314           0 :     if (type->isFloatingPointTy() || type->isVectorTy())
    5315             :       weight = CW_Register;
    5316             :     break;
    5317             :   case 'z':
    5318             :     weight = CW_Constant;
    5319             :     break;
    5320             :   }
    5321             :   return weight;
    5322             : }
    5323             : 
    5324             : std::pair<unsigned, const TargetRegisterClass *>
    5325        5878 : AArch64TargetLowering::getRegForInlineAsmConstraint(
    5326             :     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
    5327        5878 :   if (Constraint.size() == 1) {
    5328         156 :     switch (Constraint[0]) {
    5329          62 :     case 'r':
    5330          62 :       if (VT.getSizeInBits() == 64)
    5331          21 :         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
    5332          41 :       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
    5333          15 :     case 'w':
    5334          15 :       if (VT.getSizeInBits() == 16)
    5335           3 :         return std::make_pair(0U, &AArch64::FPR16RegClass);
    5336          12 :       if (VT.getSizeInBits() == 32)
    5337           2 :         return std::make_pair(0U, &AArch64::FPR32RegClass);
    5338          10 :       if (VT.getSizeInBits() == 64)
    5339           8 :         return std::make_pair(0U, &AArch64::FPR64RegClass);
    5340           2 :       if (VT.getSizeInBits() == 128)
    5341           2 :         return std::make_pair(0U, &AArch64::FPR128RegClass);
    5342             :       break;
    5343             :     // The instructions that this constraint is designed for can
    5344             :     // only take 128-bit registers so just use that regclass.
    5345           1 :     case 'x':
    5346           1 :       if (VT.getSizeInBits() == 128)
    5347           1 :         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
    5348             :       break;
    5349             :     }
    5350             :   }
    5351        5800 :   if (StringRef("{cc}").equals_lower(Constraint))
    5352           0 :     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
    5353             : 
    5354             :   // Use the default implementation in TargetLowering to convert the register
    5355             :   // constraint into a member of a register class.
    5356             :   std::pair<unsigned, const TargetRegisterClass *> Res;
    5357       11600 :   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
    5358             : 
    5359             :   // Not found as a standard register?
    5360        5800 :   if (!Res.second) {
    5361         904 :     unsigned Size = Constraint.size();
    5362        3490 :     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
    5363        3438 :         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
    5364             :       int RegNo;
    5365        1672 :       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
    5366         836 :       if (!Failed && RegNo >= 0 && RegNo <= 31) {
    5367             :         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
    5368             :         // By default we'll emit v0-v31 for this unless there's a modifier where
    5369             :         // we'll emit the correct register as well.
    5370         836 :         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
    5371           1 :           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
    5372             :           Res.second = &AArch64::FPR64RegClass;
    5373             :         } else {
    5374         835 :           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
    5375             :           Res.second = &AArch64::FPR128RegClass;
    5376             :         }
    5377             :       }
    5378             :     }
    5379             :   }
    5380             : 
    5381        5800 :   return Res;
    5382             : }
    5383             : 
    5384             : /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
    5385             : /// vector.  If it is invalid, don't add anything to Ops.
    5386          55 : void AArch64TargetLowering::LowerAsmOperandForConstraint(
    5387             :     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
    5388             :     SelectionDAG &DAG) const {
    5389          55 :   SDValue Result;
    5390             : 
    5391             :   // Currently only support length 1 constraints.
    5392          55 :   if (Constraint.length() != 1)
    5393             :     return;
    5394             : 
    5395          55 :   char ConstraintLetter = Constraint[0];
    5396          55 :   switch (ConstraintLetter) {
    5397             :   default:
    5398             :     break;
    5399             : 
    5400             :   // This set of constraints deal with valid constants for various instructions.
    5401             :   // Validate and return a target constant for them if we can.
    5402           9 :   case 'z': {
    5403             :     // 'z' maps to xzr or wzr so it needs an input of 0.
    5404           9 :     if (!isNullConstant(Op))
    5405             :       return;
    5406             : 
    5407             :     if (Op.getValueType() == MVT::i64)
    5408           0 :       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
    5409             :     else
    5410           7 :       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
    5411             :     break;
    5412             :   }
    5413             :   case 'S': {
    5414             :     // An absolute symbolic address or label reference.
    5415             :     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
    5416           4 :       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
    5417           4 :                                           GA->getValueType(0));
    5418             :     } else if (const BlockAddressSDNode *BA =
    5419             :                    dyn_cast<BlockAddressSDNode>(Op)) {
    5420           1 :       Result =
    5421           2 :           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
    5422             :     } else if (const ExternalSymbolSDNode *ES =
    5423             :                    dyn_cast<ExternalSymbolSDNode>(Op)) {
    5424           0 :       Result =
    5425           0 :           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
    5426             :     } else
    5427             :       return;
    5428             :     break;
    5429             :   }
    5430             : 
    5431             :   case 'I':
    5432             :   case 'J':
    5433             :   case 'K':
    5434             :   case 'L':
    5435             :   case 'M':
    5436             :   case 'N':
    5437             :     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
    5438             :     if (!C)
    5439             :       return;
    5440             : 
    5441             :     // Grab the value and do some validation.
    5442          28 :     uint64_t CVal = C->getZExtValue();
    5443          28 :     switch (ConstraintLetter) {
    5444             :     // The I constraint applies only to simple ADD or SUB immediate operands:
    5445             :     // i.e. 0 to 4095 with optional shift by 12
    5446             :     // The J constraint applies only to ADD or SUB immediates that would be
    5447             :     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
    5448             :     // instruction [or vice versa], in other words -1 to -4095 with optional
    5449             :     // left shift by 12.
    5450             :     case 'I':
    5451           4 :       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
    5452             :         break;
    5453             :       return;
    5454           5 :     case 'J': {
    5455           5 :       uint64_t NVal = -C->getSExtValue();
    5456           5 :       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
    5457           4 :         CVal = C->getSExtValue();
    5458           4 :         break;
    5459             :       }
    5460             :       return;
    5461             :     }
    5462             :     // The K and L constraints apply *only* to logical immediates, including
    5463             :     // what used to be the MOVI alias for ORR (though the MOVI alias has now
    5464             :     // been removed and MOV should be used). So these constraints have to
    5465             :     // distinguish between bit patterns that are valid 32-bit or 64-bit
    5466             :     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
    5467             :     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
    5468             :     // versa.
    5469             :     case 'K':
    5470           4 :       if (AArch64_AM::isLogicalImmediate(CVal, 32))
    5471             :         break;
    5472             :       return;
    5473             :     case 'L':
    5474           3 :       if (AArch64_AM::isLogicalImmediate(CVal, 64))
    5475             :         break;
    5476             :       return;
    5477             :     // The M and N constraints are a superset of K and L respectively, for use
    5478             :     // with the MOV (immediate) alias. As well as the logical immediates they
    5479             :     // also match 32 or 64-bit immediates that can be loaded either using a
    5480             :     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
    5481             :     // (M) or 64-bit 0x1234000000000000 (N) etc.
    5482             :     // As a note some of this code is liberally stolen from the asm parser.
    5483             :     case 'M': {
    5484           6 :       if (!isUInt<32>(CVal))
    5485             :         return;
    5486           6 :       if (AArch64_AM::isLogicalImmediate(CVal, 32))
    5487             :         break;
    5488           4 :       if ((CVal & 0xFFFF) == CVal)
    5489             :         break;
    5490           3 :       if ((CVal & 0xFFFF0000ULL) == CVal)
    5491             :         break;
    5492           2 :       uint64_t NCVal = ~(uint32_t)CVal;
    5493           2 :       if ((NCVal & 0xFFFFULL) == NCVal)
    5494             :         break;
    5495           1 :       if ((NCVal & 0xFFFF0000ULL) == NCVal)
    5496             :         break;
    5497             :       return;
    5498             :     }
    5499             :     case 'N': {
    5500           6 :       if (AArch64_AM::isLogicalImmediate(CVal, 64))
    5501             :         break;
    5502           5 :       if ((CVal & 0xFFFFULL) == CVal)
    5503             :         break;
    5504           3 :       if ((CVal & 0xFFFF0000ULL) == CVal)
    5505             :         break;
    5506           3 :       if ((CVal & 0xFFFF00000000ULL) == CVal)
    5507             :         break;
    5508           3 :       if ((CVal & 0xFFFF000000000000ULL) == CVal)
    5509             :         break;
    5510           2 :       uint64_t NCVal = ~CVal;
    5511           2 :       if ((NCVal & 0xFFFFULL) == NCVal)
    5512             :         break;
    5513           1 :       if ((NCVal & 0xFFFF0000ULL) == NCVal)
    5514             :         break;
    5515           1 :       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
    5516             :         break;
    5517           1 :       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
    5518             :         break;
    5519             :       return;
    5520             :     }
    5521             :     default:
    5522             :       return;
    5523          12 :     }
    5524             : 
    5525             :     // All assembler immediates are 64-bit integers.
    5526          36 :     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
    5527          18 :     break;
    5528             :   }
    5529             : 
    5530          43 :   if (Result.getNode()) {
    5531          28 :     Ops.push_back(Result);
    5532          28 :     return;
    5533             :   }
    5534             : 
    5535          15 :   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
    5536             : }
    5537             : 
    5538             : //===----------------------------------------------------------------------===//
    5539             : //                     AArch64 Advanced SIMD Support
    5540             : //===----------------------------------------------------------------------===//
    5541             : 
    5542             : /// WidenVector - Given a value in the V64 register class, produce the
    5543             : /// equivalent value in the V128 register class.
    5544        1491 : static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
    5545        1491 :   EVT VT = V64Reg.getValueType();
    5546        1491 :   unsigned NarrowSize = VT.getVectorNumElements();
    5547        1491 :   MVT EltTy = VT.getVectorElementType().getSimpleVT();
    5548        1491 :   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
    5549             :   SDLoc DL(V64Reg);
    5550             : 
    5551             :   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
    5552        5964 :                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
    5553             : }
    5554             : 
    5555             : /// getExtFactor - Determine the adjustment factor for the position when
    5556             : /// generating an "extract from vector registers" instruction.
    5557          98 : static unsigned getExtFactor(SDValue &V) {
    5558         196 :   EVT EltType = V.getValueType().getVectorElementType();
    5559          98 :   return EltType.getSizeInBits() / 8;
    5560             : }
    5561             : 
    5562             : /// NarrowVector - Given a value in the V128 register class, produce the
    5563             : /// equivalent value in the V64 register class.
    5564         246 : static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
    5565         246 :   EVT VT = V128Reg.getValueType();
    5566         246 :   unsigned WideSize = VT.getVectorNumElements();
    5567         246 :   MVT EltTy = VT.getVectorElementType().getSimpleVT();
    5568         246 :   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
    5569             :   SDLoc DL(V128Reg);
    5570             : 
    5571         492 :   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
    5572             : }
    5573             : 
    5574             : // Gather data to see if the operation can be modelled as a
    5575             : // shuffle in combination with VEXTs.
    5576         132 : SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
    5577             :                                                   SelectionDAG &DAG) const {
    5578             :   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
    5579             :   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
    5580             :   SDLoc dl(Op);
    5581         132 :   EVT VT = Op.getValueType();
    5582         132 :   unsigned NumElts = VT.getVectorNumElements();
    5583             : 
    5584             :   struct ShuffleSourceInfo {
    5585             :     SDValue Vec;
    5586             :     unsigned MinElt;
    5587             :     unsigned MaxElt;
    5588             : 
    5589             :     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
    5590             :     // be compatible with the shuffle we intend to construct. As a result
    5591             :     // ShuffleVec will be some sliding window into the original Vec.
    5592             :     SDValue ShuffleVec;
    5593             : 
    5594             :     // Code should guarantee that element i in Vec starts at element "WindowBase
    5595             :     // + i * WindowScale in ShuffleVec".
    5596             :     int WindowBase;
    5597             :     int WindowScale;
    5598             : 
    5599             :     ShuffleSourceInfo(SDValue Vec)
    5600           4 :       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
    5601           4 :           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
    5602             : 
    5603             :     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
    5604             :   };
    5605             : 
    5606             :   // First gather all vectors used as an immediate source for this BUILD_VECTOR
    5607             :   // node.
    5608             :   SmallVector<ShuffleSourceInfo, 2> Sources;
    5609         156 :   for (unsigned i = 0; i < NumElts; ++i) {
    5610         141 :     SDValue V = Op.getOperand(i);
    5611         141 :     if (V.isUndef())
    5612           0 :       continue;
    5613         141 :     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
    5614             :              !isa<ConstantSDNode>(V.getOperand(1))) {
    5615             :       LLVM_DEBUG(
    5616             :           dbgs() << "Reshuffle failed: "
    5617             :                     "a shuffle can only come from building a vector from "
    5618             :                     "various elements of other vectors, provided their "
    5619             :                     "indices are constant\n");
    5620         129 :       return SDValue();
    5621             :     }
    5622             : 
    5623             :     // Add this element source to the list if it's not already there.
    5624          12 :     SDValue SourceVec = V.getOperand(0);
    5625             :     auto Source = find(Sources, SourceVec);
    5626          12 :     if (Source == Sources.end())
    5627           4 :       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
    5628             : 
    5629             :     // Update the minimum and maximum lane number seen.
    5630          24 :     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
    5631          24 :     Source->MinElt = std::min(Source->MinElt, EltNo);
    5632          24 :     Source->MaxElt = std::max(Source->MaxElt, EltNo);
    5633             :   }
    5634             : 
    5635           3 :   if (Sources.size() > 2) {
    5636             :     LLVM_DEBUG(
    5637             :         dbgs() << "Reshuffle failed: currently only do something sane when at "
    5638             :                   "most two source vectors are involved\n");
    5639           0 :     return SDValue();
    5640             :   }
    5641             : 
    5642             :   // Find out the smallest element size among result and two sources, and use
    5643             :   // it as element size to build the shuffle_vector.
    5644           3 :   EVT SmallestEltTy = VT.getVectorElementType();
    5645          11 :   for (auto &Source : Sources) {
    5646           8 :     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
    5647           4 :     if (SrcEltTy.bitsLT(SmallestEltTy)) {
    5648           2 :       SmallestEltTy = SrcEltTy;
    5649             :     }
    5650             :   }
    5651             :   unsigned ResMultiplier =
    5652           3 :       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
    5653           3 :   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
    5654           3 :   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
    5655             : 
    5656             :   // If the source vector is too wide or too narrow, we may nevertheless be able
    5657             :   // to construct a compatible shuffle either by concatenating it with UNDEF or
    5658             :   // extracting a suitable range of elements.
    5659          11 :   for (auto &Src : Sources) {
    5660           8 :     EVT SrcVT = Src.ShuffleVec.getValueType();
    5661             : 
    5662           4 :     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
    5663           4 :       continue;
    5664             : 
    5665             :     // This stage of the search produces a source with the same element type as
    5666             :     // the original, but with a total width matching the BUILD_VECTOR output.
    5667           2 :     EVT EltVT = SrcVT.getVectorElementType();
    5668           2 :     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
    5669           2 :     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
    5670             : 
    5671           2 :     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
    5672             :       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
    5673             :       // We can pad out the smaller vector for free, so if it's part of a
    5674             :       // shuffle...
    5675           0 :       Src.ShuffleVec =
    5676           0 :           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
    5677           0 :                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
    5678           0 :       continue;
    5679             :     }
    5680             : 
    5681             :     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
    5682             : 
    5683           2 :     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
    5684             :       LLVM_DEBUG(
    5685             :           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
    5686           0 :       return SDValue();
    5687             :     }
    5688             : 
    5689           2 :     if (Src.MinElt >= NumSrcElts) {
    5690             :       // The extraction can just take the second half
    5691           1 :       Src.ShuffleVec =
    5692           2 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5693           2 :                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
    5694           1 :       Src.WindowBase = -NumSrcElts;
    5695           1 :     } else if (Src.MaxElt < NumSrcElts) {
    5696             :       // The extraction can just take the first half
    5697           1 :       Src.ShuffleVec =
    5698           2 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5699           2 :                       DAG.getConstant(0, dl, MVT::i64));
    5700             :     } else {
    5701             :       // An actual VEXT is needed
    5702             :       SDValue VEXTSrc1 =
    5703             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5704           0 :                       DAG.getConstant(0, dl, MVT::i64));
    5705             :       SDValue VEXTSrc2 =
    5706             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5707           0 :                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
    5708           0 :       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
    5709             : 
    5710           0 :       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
    5711             :                                    VEXTSrc2,
    5712           0 :                                    DAG.getConstant(Imm, dl, MVT::i32));
    5713           0 :       Src.WindowBase = -Src.MinElt;
    5714             :     }
    5715             :   }
    5716             : 
    5717             :   // Another possible incompatibility occurs from the vector element types. We
    5718             :   // can fix this by bitcasting the source vectors to the same type we intend
    5719             :   // for the shuffle.
    5720          11 :   for (auto &Src : Sources) {
    5721           8 :     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
    5722           4 :     if (SrcEltTy == SmallestEltTy)
    5723           3 :       continue;
    5724             :     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
    5725           1 :     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
    5726           1 :     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
    5727           1 :     Src.WindowBase *= Src.WindowScale;
    5728             :   }
    5729             : 
    5730             :   // Final sanity check before we try to actually produce a shuffle.
    5731             :   LLVM_DEBUG(for (auto Src
    5732             :                   : Sources)
    5733             :                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
    5734             : 
    5735             :   // The stars all align, our next step is to produce the mask for the shuffle.
    5736           6 :   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
    5737           3 :   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
    5738          27 :   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
    5739          12 :     SDValue Entry = Op.getOperand(i);
    5740          12 :     if (Entry.isUndef())
    5741           0 :       continue;
    5742             : 
    5743             :     auto Src = find(Sources, Entry.getOperand(0));
    5744          24 :     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
    5745             : 
    5746             :     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
    5747             :     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
    5748             :     // segment.
    5749          24 :     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
    5750             :     int BitsDefined =
    5751          24 :         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
    5752          12 :     int LanesDefined = BitsDefined / BitsPerShuffleLane;
    5753             : 
    5754             :     // This source is expected to fill ResMultiplier lanes of the final shuffle,
    5755             :     // starting at the appropriate offset.
    5756          12 :     int *LaneMask = &Mask[i * ResMultiplier];
    5757             : 
    5758          12 :     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
    5759          24 :     ExtractBase += NumElts * (Src - Sources.begin());
    5760          36 :     for (int j = 0; j < LanesDefined; ++j)
    5761          12 :       LaneMask[j] = ExtractBase + j;
    5762             :   }
    5763             : 
    5764             :   // Final check before we try to produce nonsense...
    5765           6 :   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
    5766             :     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
    5767           0 :     return SDValue();
    5768             :   }
    5769             : 
    5770           3 :   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
    5771          18 :   for (unsigned i = 0; i < Sources.size(); ++i)
    5772           4 :     ShuffleOps[i] = Sources[i].ShuffleVec;
    5773             : 
    5774             :   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
    5775           3 :                                          ShuffleOps[1], Mask);
    5776           3 :   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
    5777             : 
    5778             :   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
    5779             :              dbgs() << "Reshuffle, creating node: "; V.dump(););
    5780             : 
    5781           3 :   return V;
    5782             : }
    5783             : 
    5784             : // check if an EXT instruction can handle the shuffle mask when the
    5785             : // vector sources of the shuffle are the same.
    5786         172 : static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
    5787         172 :   unsigned NumElts = VT.getVectorNumElements();
    5788             : 
    5789             :   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
    5790         172 :   if (M[0] < 0)
    5791             :     return false;
    5792             : 
    5793         172 :   Imm = M[0];
    5794             : 
    5795             :   // If this is a VEXT shuffle, the immediate value is the index of the first
    5796             :   // element.  The other shuffle indices must be the successive elements after
    5797             :   // the first one.
    5798             :   unsigned ExpectedElt = Imm;
    5799         482 :   for (unsigned i = 1; i < NumElts; ++i) {
    5800             :     // Increment the expected index.  If it wraps around, just follow it
    5801             :     // back to index zero and keep going.
    5802         307 :     ++ExpectedElt;
    5803         307 :     if (ExpectedElt == NumElts)
    5804             :       ExpectedElt = 0;
    5805             : 
    5806         614 :     if (M[i] < 0)
    5807             :       continue; // ignore UNDEF indices
    5808         276 :     if (ExpectedElt != static_cast<unsigned>(M[i]))
    5809             :       return false;
    5810             :   }
    5811             : 
    5812             :   return true;
    5813             : }
    5814             : 
    5815             : // check if an EXT instruction can handle the shuffle mask when the
    5816             : // vector sources of the shuffle are different.
    5817         637 : static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
    5818             :                       unsigned &Imm) {
    5819             :   // Look for the first non-undef element.
    5820             :   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
    5821             : 
    5822             :   // Benefit form APInt to handle overflow when calculating expected element.
    5823         637 :   unsigned NumElts = VT.getVectorNumElements();
    5824        1274 :   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
    5825         637 :   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
    5826             :   // The following shuffle indices must be the successive elements after the
    5827             :   // first real element.
    5828         637 :   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
    5829        3393 :       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
    5830         637 :   if (FirstWrongElt != M.end())
    5831             :     return false;
    5832             : 
    5833             :   // The index of an EXT is the first element if it is not UNDEF.
    5834             :   // Watch out for the beginning UNDEFs. The EXT index should be the expected
    5835             :   // value of the first element.  E.g.
    5836             :   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
    5837             :   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
    5838             :   // ExpectedElt is the last mask index plus 1.
    5839          68 :   Imm = ExpectedElt.getZExtValue();
    5840             : 
    5841             :   // There are two difference cases requiring to reverse input vectors.
    5842             :   // For example, for vector <4 x i32> we have the following cases,
    5843             :   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
    5844             :   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
    5845             :   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
    5846             :   // to reverse two input vectors.
    5847          68 :   if (Imm < NumElts)
    5848          23 :     ReverseEXT = true;
    5849             :   else
    5850          45 :     Imm -= NumElts;
    5851             : 
    5852             :   return true;
    5853             : }
    5854             : 
    5855             : /// isREVMask - Check if a vector shuffle corresponds to a REV
    5856             : /// instruction with the specified blocksize.  (The order of the elements
    5857             : /// within each block of the vector is reversed.)
    5858        1987 : static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
    5859             :   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
    5860             :          "Only possible block sizes for REV are: 16, 32, 64");
    5861             : 
    5862             :   unsigned EltSz = VT.getScalarSizeInBits();
    5863        1987 :   if (EltSz == 64)
    5864             :     return false;
    5865             : 
    5866        1846 :   unsigned NumElts = VT.getVectorNumElements();
    5867        1846 :   unsigned BlockElts = M[0] + 1;
    5868             :   // If the first shuffle index is UNDEF, be optimistic.
    5869        1846 :   if (M[0] < 0)
    5870          55 :     BlockElts = BlockSize / EltSz;
    5871             : 
    5872        1846 :   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
    5873             :     return false;
    5874             : 
    5875        1513 :   for (unsigned i = 0; i < NumElts; ++i) {
    5876        1702 :     if (M[i] < 0)
    5877             :       continue; // ignore UNDEF indices
    5878         683 :     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
    5879             :       return false;
    5880             :   }
    5881             : 
    5882             :   return true;
    5883             : }
    5884             : 
    5885         525 : static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5886         525 :   unsigned NumElts = VT.getVectorNumElements();
    5887         525 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5888         525 :   unsigned Idx = WhichResult * NumElts / 2;
    5889        1649 :   for (unsigned i = 0; i != NumElts; i += 2) {
    5890        2528 :     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
    5891        2008 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
    5892             :       return false;
    5893         562 :     Idx += 1;
    5894             :   }
    5895             : 
    5896             :   return true;
    5897             : }
    5898             : 
    5899         345 : static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5900         345 :   unsigned NumElts = VT.getVectorNumElements();
    5901         345 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5902        2717 :   for (unsigned i = 0; i != NumElts; ++i) {
    5903        2838 :     if (M[i] < 0)
    5904             :       continue; // ignore UNDEF indices
    5905        1287 :     if ((unsigned)M[i] != 2 * i + WhichResult)
    5906             :       return false;
    5907             :   }
    5908             : 
    5909             :   return true;
    5910             : }
    5911             : 
    5912         257 : static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5913         257 :   unsigned NumElts = VT.getVectorNumElements();
    5914         257 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5915         997 :   for (unsigned i = 0; i < NumElts; i += 2) {
    5916        1513 :     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
    5917        1443 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
    5918             :       return false;
    5919             :   }
    5920             :   return true;
    5921             : }
    5922             : 
    5923             : /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
    5924             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5925             : /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
    5926         144 : static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5927         144 :   unsigned NumElts = VT.getVectorNumElements();
    5928         144 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5929         144 :   unsigned Idx = WhichResult * NumElts / 2;
    5930         424 :   for (unsigned i = 0; i != NumElts; i += 2) {
    5931         697 :     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
    5932         567 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
    5933             :       return false;
    5934         140 :     Idx += 1;
    5935             :   }
    5936             : 
    5937             :   return true;
    5938             : }
    5939             : 
    5940             : /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
    5941             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5942             : /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
    5943         114 : static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5944         114 :   unsigned Half = VT.getVectorNumElements() / 2;
    5945         114 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5946         248 :   for (unsigned j = 0; j != 2; ++j) {
    5947             :     unsigned Idx = WhichResult;
    5948         775 :     for (unsigned i = 0; i != Half; ++i) {
    5949         792 :       int MIdx = M[i + j * Half];
    5950         396 :       if (MIdx >= 0 && (unsigned)MIdx != Idx)
    5951             :         return false;
    5952         312 :       Idx += 2;
    5953             :     }
    5954             :   }
    5955             : 
    5956             :   return true;
    5957             : }
    5958             : 
    5959             : /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
    5960             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5961             : /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
    5962          84 : static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5963          84 :   unsigned NumElts = VT.getVectorNumElements();
    5964          84 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5965         334 :   for (unsigned i = 0; i < NumElts; i += 2) {
    5966         517 :     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
    5967         477 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
    5968             :       return false;
    5969             :   }
    5970             :   return true;
    5971             : }
    5972             : 
    5973          44 : static bool isINSMask(ArrayRef<int> M, int NumInputElements,
    5974             :                       bool &DstIsLeft, int &Anomaly) {
    5975          44 :   if (M.size() != static_cast<size_t>(NumInputElements))
    5976             :     return false;
    5977             : 
    5978             :   int NumLHSMatch = 0, NumRHSMatch = 0;
    5979             :   int LastLHSMismatch = -1, LastRHSMismatch = -1;
    5980             : 
    5981         700 :   for (int i = 0; i < NumInputElements; ++i) {
    5982         657 :     if (M[i] == -1) {
    5983           1 :       ++NumLHSMatch;
    5984           1 :       ++NumRHSMatch;
    5985           1 :       continue;
    5986             :     }
    5987             : 
    5988         327 :     if (M[i] == i)
    5989         101 :       ++NumLHSMatch;
    5990             :     else
    5991             :       LastLHSMismatch = i;
    5992             : 
    5993         327 :     if (M[i] == i + NumInputElements)
    5994          75 :       ++NumRHSMatch;
    5995             :     else
    5996             :       LastRHSMismatch = i;
    5997             :   }
    5998             : 
    5999          44 :   if (NumLHSMatch == NumInputElements - 1) {
    6000          10 :     DstIsLeft = true;
    6001          10 :     Anomaly = LastLHSMismatch;
    6002          10 :     return true;
    6003          34 :   } else if (NumRHSMatch == NumInputElements - 1) {
    6004           2 :     DstIsLeft = false;
    6005           2 :     Anomaly = LastRHSMismatch;
    6006           2 :     return true;
    6007             :   }
    6008             : 
    6009             :   return false;
    6010             : }
    6011             : 
    6012          52 : static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
    6013          52 :   if (VT.getSizeInBits() != 128)
    6014             :     return false;
    6015             : 
    6016          32 :   unsigned NumElts = VT.getVectorNumElements();
    6017             : 
    6018         111 :   for (int I = 0, E = NumElts / 2; I != E; I++) {
    6019         194 :     if (Mask[I] != I)
    6020             :       return false;
    6021             :   }
    6022             : 
    6023             :   int Offset = NumElts / 2;
    6024          72 :   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
    6025         122 :     if (Mask[I] != I + SplitLHS * Offset)
    6026             :       return false;
    6027             :   }
    6028             : 
    6029             :   return true;
    6030             : }
    6031             : 
    6032          39 : static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
    6033             :   SDLoc DL(Op);
    6034          39 :   EVT VT = Op.getValueType();
    6035          39 :   SDValue V0 = Op.getOperand(0);
    6036          39 :   SDValue V1 = Op.getOperand(1);
    6037          39 :   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
    6038             : 
    6039         117 :   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
    6040         117 :       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
    6041           0 :     return SDValue();
    6042             : 
    6043          39 :   bool SplitV0 = V0.getValueSizeInBits() == 128;
    6044             : 
    6045          39 :   if (!isConcatMask(Mask, VT, SplitV0))
    6046          29 :     return SDValue();
    6047             : 
    6048          10 :   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
    6049          20 :                                 VT.getVectorNumElements() / 2);
    6050          10 :   if (SplitV0) {
    6051          10 :     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
    6052          20 :                      DAG.getConstant(0, DL, MVT::i64));
    6053             :   }
    6054          10 :   if (V1.getValueSizeInBits() == 128) {
    6055          10 :     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
    6056          20 :                      DAG.getConstant(0, DL, MVT::i64));
    6057             :   }
    6058          10 :   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
    6059             : }
    6060             : 
    6061             : /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
    6062             : /// the specified operations to build the shuffle.
    6063          74 : static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
    6064             :                                       SDValue RHS, SelectionDAG &DAG,
    6065             :                                       const SDLoc &dl) {
    6066          74 :   unsigned OpNum = (PFEntry >> 26) & 0x0F;
    6067          74 :   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
    6068          74 :   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
    6069             : 
    6070             :   enum {
    6071             :     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
    6072             :     OP_VREV,
    6073             :     OP_VDUP0,
    6074             :     OP_VDUP1,
    6075             :     OP_VDUP2,
    6076             :     OP_VDUP3,
    6077             :     OP_VEXT1,
    6078             :     OP_VEXT2,
    6079             :     OP_VEXT3,
    6080             :     OP_VUZPL, // VUZP, left result
    6081             :     OP_VUZPR, // VUZP, right result
    6082             :     OP_VZIPL, // VZIP, left result
    6083             :     OP_VZIPR, // VZIP, right result
    6084             :     OP_VTRNL, // VTRN, left result
    6085             :     OP_VTRNR  // VTRN, right result
    6086             :   };
    6087             : 
    6088          74 :   if (OpNum == OP_COPY) {
    6089          43 :     if (LHSID == (1 * 9 + 2) * 9 + 3)
    6090          28 :       return LHS;
    6091             :     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
    6092          15 :     return RHS;
    6093             :   }
    6094             : 
    6095          31 :   SDValue OpLHS, OpRHS;
    6096          31 :   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
    6097          31 :   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
    6098          62 :   EVT VT = OpLHS.getValueType();
    6099             : 
    6100          31 :   switch (OpNum) {
    6101           0 :   default:
    6102           0 :     llvm_unreachable("Unknown shuffle opcode!");
    6103             :   case OP_VREV:
    6104             :     // VREV divides the vector in half and swaps within the half.
    6105           8 :     if (VT.getVectorElementType() == MVT::i32 ||
    6106           7 :         VT.getVectorElementType() == MVT::f32)
    6107           3 :       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
    6108             :     // vrev <4 x i16> -> REV32
    6109           2 :     if (VT.getVectorElementType() == MVT::i16 ||
    6110           1 :         VT.getVectorElementType() == MVT::f16)
    6111           1 :       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
    6112             :     // vrev <4 x i8> -> REV16
    6113             :     assert(VT.getVectorElementType() == MVT::i8);
    6114           0 :     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
    6115           8 :   case OP_VDUP0:
    6116             :   case OP_VDUP1:
    6117             :   case OP_VDUP2:
    6118             :   case OP_VDUP3: {
    6119           8 :     EVT EltTy = VT.getVectorElementType();
    6120             :     unsigned Opcode;
    6121             :     if (EltTy == MVT::i8)
    6122             :       Opcode = AArch64ISD::DUPLANE8;
    6123             :     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
    6124             :       Opcode = AArch64ISD::DUPLANE16;
    6125             :     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
    6126             :       Opcode = AArch64ISD::DUPLANE32;
    6127             :     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
    6128             :       Opcode = AArch64ISD::DUPLANE64;
    6129             :     else
    6130           0 :       llvm_unreachable("Invalid vector element type?");
    6131             : 
    6132           8 :     if (VT.getSizeInBits() == 64)
    6133           4 :       OpLHS = WidenVector(OpLHS, DAG);
    6134           8 :     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
    6135           8 :     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
    6136             :   }
    6137          14 :   case OP_VEXT1:
    6138             :   case OP_VEXT2:
    6139             :   case OP_VEXT3: {
    6140          14 :     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
    6141             :     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
    6142          14 :                        DAG.getConstant(Imm, dl, MVT::i32));
    6143             :   }
    6144           0 :   case OP_VUZPL:
    6145             :     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
    6146           0 :                        OpRHS);
    6147           0 :   case OP_VUZPR:
    6148             :     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
    6149           0 :                        OpRHS);
    6150           2 :   case OP_VZIPL:
    6151             :     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
    6152           2 :                        OpRHS);
    6153           0 :   case OP_VZIPR:
    6154             :     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
    6155           0 :                        OpRHS);
    6156           0 :   case OP_VTRNL:
    6157             :     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
    6158           0 :                        OpRHS);
    6159           3 :   case OP_VTRNR:
    6160             :     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
    6161           3 :                        OpRHS);
    6162             :   }
    6163             : }
    6164             : 
    6165           7 : static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
    6166             :                            SelectionDAG &DAG) {
    6167             :   // Check to see if we can use the TBL instruction.
    6168          14 :   SDValue V1 = Op.getOperand(0);
    6169           7 :   SDValue V2 = Op.getOperand(1);
    6170             :   SDLoc DL(Op);
    6171             : 
    6172          14 :   EVT EltVT = Op.getValueType().getVectorElementType();
    6173           7 :   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
    6174             : 
    6175             :   SmallVector<SDValue, 8> TBLMask;
    6176         135 :   for (int Val : ShuffleMask) {
    6177         224 :     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
    6178          80 :       unsigned Offset = Byte + Val * BytesPerElt;
    6179          80 :       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
    6180             :     }
    6181             :   }
    6182             : 
    6183             :   MVT IndexVT = MVT::v8i8;
    6184             :   unsigned IndexLen = 8;
    6185           7 :   if (Op.getValueSizeInBits() == 128) {
    6186             :     IndexVT = MVT::v16i8;
    6187             :     IndexLen = 16;
    6188             :   }
    6189             : 
    6190           7 :   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
    6191           7 :   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
    6192             : 
    6193           7 :   SDValue Shuffle;
    6194           7 :   if (V2.getNode()->isUndef()) {
    6195           1 :     if (IndexLen == 8)
    6196           0 :       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
    6197           1 :     Shuffle = DAG.getNode(
    6198             :         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    6199             :         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
    6200             :         DAG.getBuildVector(IndexVT, DL,
    6201           4 :                            makeArrayRef(TBLMask.data(), IndexLen)));
    6202             :   } else {
    6203           6 :     if (IndexLen == 8) {
    6204           4 :       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
    6205           4 :       Shuffle = DAG.getNode(
    6206             :           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    6207             :           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
    6208             :           DAG.getBuildVector(IndexVT, DL,
    6209          16 :                              makeArrayRef(TBLMask.data(), IndexLen)));
    6210             :     } else {
    6211             :       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
    6212             :       // cannot currently represent the register constraints on the input
    6213             :       // table registers.
    6214             :       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
    6215             :       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
    6216             :       //                   IndexLen));
    6217           2 :       Shuffle = DAG.getNode(
    6218             :           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    6219             :           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
    6220             :           V2Cst, DAG.getBuildVector(IndexVT, DL,
    6221           8 :                                     makeArrayRef(TBLMask.data(), IndexLen)));
    6222             :     }
    6223             :   }
    6224          21 :   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
    6225             : }
    6226             : 
    6227             : static unsigned getDUPLANEOp(EVT EltType) {
    6228             :   if (EltType == MVT::i8)
    6229             :     return AArch64ISD::DUPLANE8;
    6230             :   if (EltType == MVT::i16 || EltType == MVT::f16)
    6231             :     return AArch64ISD::DUPLANE16;
    6232             :   if (EltType == MVT::i32 || EltType == MVT::f32)
    6233             :     return AArch64ISD::DUPLANE32;
    6234             :   if (EltType == MVT::i64 || EltType == MVT::f64)
    6235             :     return AArch64ISD::DUPLANE64;
    6236             : 
    6237           0 :   llvm_unreachable("Invalid vector element type?");
    6238             : }
    6239             : 
    6240        1680 : SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
    6241             :                                                    SelectionDAG &DAG) const {
    6242             :   SDLoc dl(Op);
    6243        1680 :   EVT VT = Op.getValueType();
    6244             : 
    6245             :   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
    6246             : 
    6247             :   // Convert shuffles that are directly supported on NEON to target-specific
    6248             :   // DAG nodes, instead of keeping them as shuffles and matching them again
    6249             :   // during code selection.  This is more efficient and avoids the possibility
    6250             :   // of inconsistencies between legalization and selection.
    6251        1680 :   ArrayRef<int> ShuffleMask = SVN->getMask();
    6252             : 
    6253        1680 :   SDValue V1 = Op.getOperand(0);
    6254        1680 :   SDValue V2 = Op.getOperand(1);
    6255             : 
    6256        1680 :   if (SVN->isSplat()) {
    6257        1045 :     int Lane = SVN->getSplatIndex();
    6258             :     // If this is undef splat, generate it via "just" vdup, if possible.
    6259        1045 :     if (Lane == -1)
    6260             :       Lane = 0;
    6261             : 
    6262        1520 :     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
    6263             :       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
    6264           0 :                          V1.getOperand(0));
    6265             :     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
    6266             :     // constant. If so, we can just reference the lane's definition directly.
    6267        2090 :     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
    6268           0 :         !isa<ConstantSDNode>(V1.getOperand(Lane)))
    6269           0 :       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
    6270             : 
    6271             :     // Otherwise, duplicate from the lane of the input vector.
    6272        3135 :     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
    6273             : 
    6274             :     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
    6275             :     // to make a vector of the same size as this SHUFFLE. We can ignore the
    6276             :     // extract entirely, and canonicalise the concat using WidenVector.
    6277        2090 :     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
    6278         530 :       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
    6279         265 :       V1 = V1.getOperand(0);
    6280         780 :     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
    6281         123 :       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
    6282         123 :       Lane -= Idx * VT.getVectorNumElements() / 2;
    6283         123 :       V1 = WidenVector(V1.getOperand(Idx), DAG);
    6284         657 :     } else if (VT.getSizeInBits() == 64)
    6285         447 :       V1 = WidenVector(V1, DAG);
    6286             : 
    6287        1045 :     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
    6288             :   }
    6289             : 
    6290         635 :   if (isREVMask(ShuffleMask, VT, 64))
    6291          36 :     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
    6292         617 :   if (isREVMask(ShuffleMask, VT, 32))
    6293          32 :     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
    6294         601 :   if (isREVMask(ShuffleMask, VT, 16))
    6295          16 :     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
    6296             : 
    6297         593 :   bool ReverseEXT = false;
    6298             :   unsigned Imm;
    6299         593 :   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
    6300          64 :     if (ReverseEXT)
    6301             :       std::swap(V1, V2);
    6302          64 :     Imm *= getExtFactor(V1);
    6303             :     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
    6304         128 :                        DAG.getConstant(Imm, dl, MVT::i32));
    6305         529 :   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
    6306          20 :     Imm *= getExtFactor(V1);
    6307             :     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
    6308          40 :                        DAG.getConstant(Imm, dl, MVT::i32));
    6309             :   }
    6310             : 
    6311             :   unsigned WhichResult;
    6312         509 :   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
    6313         180 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
    6314         360 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6315             :   }
    6316         329 :   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
    6317         112 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
    6318         224 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6319             :   }
    6320         217 :   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
    6321          88 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
    6322         176 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6323             :   }
    6324             : 
    6325         129 :   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6326          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
    6327          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6328             :   }
    6329          99 :   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6330          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
    6331          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6332             :   }
    6333          69 :   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6334          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
    6335          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6336             :   }
    6337             : 
    6338          39 :   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
    6339          10 :     return Concat;
    6340             : 
    6341             :   bool DstIsLeft;
    6342             :   int Anomaly;
    6343          58 :   int NumInputElements = V1.getValueType().getVectorNumElements();
    6344          29 :   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
    6345          10 :     SDValue DstVec = DstIsLeft ? V1 : V2;
    6346          10 :     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
    6347             : 
    6348          10 :     SDValue SrcVec = V1;
    6349          20 :     int SrcLane = ShuffleMask[Anomaly];
    6350          10 :     if (SrcLane >= NumInputElements) {
    6351           8 :       SrcVec = V2;
    6352           8 :       SrcLane -= VT.getVectorNumElements();
    6353             :     }
    6354          10 :     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
    6355             : 
    6356          10 :     EVT ScalarVT = VT.getVectorElementType();
    6357             : 
    6358          10 :     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
    6359           4 :       ScalarVT = MVT::i32;
    6360             : 
    6361             :     return DAG.getNode(
    6362             :         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
    6363             :         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
    6364          10 :         DstLaneV);
    6365             :   }
    6366             : 
    6367             :   // If the shuffle is not directly supported and it has 4 elements, use
    6368             :   // the PerfectShuffle-generated table to synthesize it from other shuffles.
    6369          19 :   unsigned NumElts = VT.getVectorNumElements();
    6370          19 :   if (NumElts == 4) {
    6371             :     unsigned PFIndexes[4];
    6372         108 :     for (unsigned i = 0; i != 4; ++i) {
    6373          96 :       if (ShuffleMask[i] < 0)
    6374           1 :         PFIndexes[i] = 8;
    6375             :       else
    6376          47 :         PFIndexes[i] = ShuffleMask[i];
    6377             :     }
    6378             : 
    6379             :     // Compute the index in the perfect shuffle table.
    6380          36 :     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
    6381          24 :                             PFIndexes[2] * 9 + PFIndexes[3];
    6382          12 :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    6383             :     unsigned Cost = (PFEntry >> 30);
    6384             : 
    6385             :     if (Cost <= 4)
    6386          12 :       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
    6387             :   }
    6388             : 
    6389           7 :   return GenerateTBL(Op, ShuffleMask, DAG);
    6390             : }
    6391             : 
    6392        1567 : static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
    6393             :                                APInt &UndefBits) {
    6394        3134 :   EVT VT = BVN->getValueType(0);
    6395             :   APInt SplatBits, SplatUndef;
    6396             :   unsigned SplatBitSize;
    6397             :   bool HasAnyUndefs;
    6398        1567 :   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
    6399         927 :     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
    6400             : 
    6401       12747 :     for (unsigned i = 0; i < NumSplats; ++i) {
    6402        5910 :       CnstBits <<= SplatBitSize;
    6403        5910 :       UndefBits <<= SplatBitSize;
    6404       11820 :       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
    6405       23640 :       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
    6406             :     }
    6407             : 
    6408             :     return true;
    6409             :   }
    6410             : 
    6411             :   return false;
    6412             : }
    6413             : 
    6414             : // Try 64-bit splatted SIMD immediate.
    6415         584 : static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
    6416             :                                  const APInt &Bits) {
    6417        1752 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6418         996 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6419         498 :     EVT VT = Op.getValueType();
    6420         498 :     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
    6421             : 
    6422         498 :     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
    6423          76 :       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
    6424             : 
    6425             :       SDLoc dl(Op);
    6426             :       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
    6427         152 :                                 DAG.getConstant(Value, dl, MVT::i32));
    6428          76 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6429             :     }
    6430             :   }
    6431             : 
    6432         508 :   return SDValue();
    6433             : }
    6434             : 
    6435             : // Try 32-bit splatted SIMD immediate.
    6436        1070 : static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
    6437             :                                   const APInt &Bits,
    6438             :                                   const SDValue *LHS = nullptr) {
    6439        3210 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6440        1764 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6441         882 :     EVT VT = Op.getValueType();
    6442         882 :     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6443             :     bool isAdvSIMDModImm = false;
    6444             :     uint64_t Shift;
    6445             : 
    6446             :     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
    6447             :       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
    6448             :       Shift = 0;
    6449             :     }
    6450             :     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
    6451             :       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
    6452             :       Shift = 8;
    6453             :     }
    6454             :     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
    6455             :       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
    6456             :       Shift = 16;
    6457             :     }
    6458             :     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
    6459             :       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
    6460             :       Shift = 24;
    6461             :     }
    6462             : 
    6463         882 :     if (isAdvSIMDModImm) {
    6464             :       SDLoc dl(Op);
    6465         187 :       SDValue Mov;
    6466             : 
    6467         187 :       if (LHS)
    6468          78 :         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
    6469             :                           DAG.getConstant(Value, dl, MVT::i32),
    6470         234 :                           DAG.getConstant(Shift, dl, MVT::i32));
    6471             :       else
    6472         109 :         Mov = DAG.getNode(NewOp, dl, MovTy,
    6473             :                           DAG.getConstant(Value, dl, MVT::i32),
    6474         327 :                           DAG.getConstant(Shift, dl, MVT::i32));
    6475             : 
    6476         187 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6477             :     }
    6478             :   }
    6479             : 
    6480         883 :   return SDValue();
    6481             : }
    6482             : 
    6483             : // Try 16-bit splatted SIMD immediate.
    6484         853 : static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
    6485             :                                   const APInt &Bits,
    6486             :                                   const SDValue *LHS = nullptr) {
    6487        2559 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6488        1330 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6489         665 :     EVT VT = Op.getValueType();
    6490         665 :     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6491             :     bool isAdvSIMDModImm = false;
    6492             :     uint64_t Shift;
    6493             : 
    6494             :     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
    6495             :       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
    6496             :       Shift = 0;
    6497             :     }
    6498             :     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
    6499             :       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
    6500             :       Shift = 8;
    6501             :     }
    6502             : 
    6503         665 :     if (isAdvSIMDModImm) {
    6504             :       SDLoc dl(Op);
    6505         111 :       SDValue Mov;
    6506             : 
    6507         111 :       if (LHS)
    6508          48 :         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
    6509             :                           DAG.getConstant(Value, dl, MVT::i32),
    6510         144 :                           DAG.getConstant(Shift, dl, MVT::i32));
    6511             :       else
    6512          63 :         Mov = DAG.getNode(NewOp, dl, MovTy,
    6513             :                           DAG.getConstant(Value, dl, MVT::i32),
    6514         189 :                           DAG.getConstant(Shift, dl, MVT::i32));
    6515             : 
    6516         111 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6517             :     }
    6518             :   }
    6519             : 
    6520         742 :   return SDValue();
    6521             : }
    6522             : 
    6523             : // Try 32-bit splatted SIMD immediate with shifted ones.
    6524         649 : static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
    6525             :                                     SelectionDAG &DAG, const APInt &Bits) {
    6526        1947 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6527         954 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6528         477 :     EVT VT = Op.getValueType();
    6529         477 :     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6530             :     bool isAdvSIMDModImm = false;
    6531             :     uint64_t Shift;
    6532             : 
    6533             :     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
    6534             :       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
    6535             :       Shift = 264;
    6536             :     }
    6537             :     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
    6538             :       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
    6539             :       Shift = 272;
    6540             :     }
    6541             : 
    6542         477 :     if (isAdvSIMDModImm) {
    6543             :       SDLoc dl(Op);
    6544             :       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
    6545             :                                 DAG.getConstant(Value, dl, MVT::i32),
    6546          90 :                                 DAG.getConstant(Shift, dl, MVT::i32));
    6547          30 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6548             :     }
    6549             :   }
    6550             : 
    6551         619 :   return SDValue();
    6552             : }
    6553             : 
    6554             : // Try 8-bit splatted SIMD immediate.
    6555         334 : static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
    6556             :                                  const APInt &Bits) {
    6557        1002 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6558         496 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6559         248 :     EVT VT = Op.getValueType();
    6560         248 :     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
    6561             : 
    6562             :     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
    6563             :       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
    6564             : 
    6565             :       SDLoc dl(Op);
    6566             :       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
    6567          90 :                                 DAG.getConstant(Value, dl, MVT::i32));
    6568          45 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6569             :     }
    6570             :   }
    6571             : 
    6572         289 :   return SDValue();
    6573             : }
    6574             : 
    6575             : // Try FP splatted SIMD immediate.
    6576         289 : static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
    6577             :                                   const APInt &Bits) {
    6578         867 :   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
    6579         406 :     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
    6580         203 :     EVT VT = Op.getValueType();
    6581         203 :     bool isWide = (VT.getSizeInBits() == 128);
    6582             :     MVT MovTy;
    6583             :     bool isAdvSIMDModImm = false;
    6584             : 
    6585             :     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
    6586          24 :       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
    6587          24 :       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
    6588             :     }
    6589         179 :     else if (isWide &&
    6590             :              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
    6591          15 :       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
    6592             :       MovTy = MVT::v2f64;
    6593             :     }
    6594             : 
    6595         203 :     if (isAdvSIMDModImm) {
    6596             :       SDLoc dl(Op);
    6597             :       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
    6598          78 :                                 DAG.getConstant(Value, dl, MVT::i32));
    6599          39 :       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6600             :     }
    6601             :   }
    6602             : 
    6603         250 :   return SDValue();
    6604             : }
    6605             : 
    6606         868 : SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
    6607             :                                               SelectionDAG &DAG) const {
    6608         868 :   SDValue LHS = Op.getOperand(0);
    6609         868 :   EVT VT = Op.getValueType();
    6610             : 
    6611             :   BuildVectorSDNode *BVN =
    6612         868 :       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
    6613             :   if (!BVN) {
    6614             :     // AND commutes, so try swapping the operands.
    6615         717 :     LHS = Op.getOperand(1);
    6616         717 :     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
    6617             :   }
    6618         159 :   if (!BVN)
    6619         709 :     return Op;
    6620             : 
    6621         159 :   APInt DefBits(VT.getSizeInBits(), 0);
    6622         159 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6623         159 :   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
    6624             :     SDValue NewOp;
    6625             : 
    6626             :     // We only have BIC vector immediate instruction, which is and-not.
    6627         157 :     DefBits = ~DefBits;
    6628         314 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
    6629         276 :                                     DefBits, &LHS)) ||
    6630         276 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
    6631         276 :                                     DefBits, &LHS)))
    6632          64 :       return NewOp;
    6633             : 
    6634          93 :     UndefBits = ~UndefBits;
    6635         186 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, Op, DAG,
    6636         186 :                                     UndefBits, &LHS)) ||
    6637         186 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, Op, DAG,
    6638         186 :                                     UndefBits, &LHS)))
    6639           0 :       return NewOp;
    6640             :   }
    6641             : 
    6642             :   // We can always fall back to a non-immediate AND.
    6643          95 :   return Op;
    6644             : }
    6645             : 
    6646             : // Specialized code to quickly find if PotentialBVec is a BuildVector that
    6647             : // consists of only the same constant int value, returned in reference arg
    6648             : // ConstVal
    6649           8 : static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
    6650             :                                      uint64_t &ConstVal) {
    6651             :   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
    6652             :   if (!Bvec)
    6653             :     return false;
    6654           6 :   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
    6655             :   if (!FirstElt)
    6656             :     return false;
    6657          12 :   EVT VT = Bvec->getValueType(0);
    6658           6 :   unsigned NumElts = VT.getVectorNumElements();
    6659         186 :   for (unsigned i = 1; i < NumElts; ++i)
    6660          90 :     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
    6661             :       return false;
    6662          12 :   ConstVal = FirstElt->getZExtValue();
    6663           6 :   return true;
    6664             : }
    6665             : 
    6666             : static unsigned getIntrinsicID(const SDNode *N) {
    6667        6234 :   unsigned Opcode = N->getOpcode();
    6668        6290 :   switch (Opcode) {
    6669             :   default:
    6670             :     return Intrinsic::not_intrinsic;
    6671        6290 :   case ISD::INTRINSIC_WO_CHAIN: {
    6672       18870 :     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
    6673        6290 :     if (IID < Intrinsic::num_intrinsics)
    6674             :       return IID;
    6675             :     return Intrinsic::not_intrinsic;
    6676             :   }
    6677             :   }
    6678             : }
    6679             : 
    6680             : // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
    6681             : // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
    6682             : // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
    6683             : // Also, logical shift right -> sri, with the same structure.
    6684           8 : static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
    6685          16 :   EVT VT = N->getValueType(0);
    6686             : 
    6687           8 :   if (!VT.isVector())
    6688           0 :     return SDValue();
    6689             : 
    6690             :   SDLoc DL(N);
    6691             : 
    6692             :   // Is the first op an AND?
    6693           8 :   const SDValue And = N->getOperand(0);
    6694           8 :   if (And.getOpcode() != ISD::AND)
    6695           0 :     return SDValue();
    6696             : 
    6697             :   // Is the second op an shl or lshr?
    6698           8 :   SDValue Shift = N->getOperand(1);
    6699             :   // This will have been turned into: AArch64ISD::VSHL vector, #shift
    6700             :   // or AArch64ISD::VLSHR vector, #shift
    6701             :   unsigned ShiftOpc = Shift.getOpcode();
    6702           8 :   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
    6703           0 :     return SDValue();
    6704             :   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
    6705             : 
    6706             :   // Is the shift amount constant?
    6707             :   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
    6708             :   if (!C2node)
    6709           0 :     return SDValue();
    6710             : 
    6711             :   // Is the and mask vector all constant?
    6712             :   uint64_t C1;
    6713           8 :   if (!isAllConstantBuildVector(And.getOperand(1), C1))
    6714           2 :     return SDValue();
    6715             : 
    6716             :   // Is C1 == ~C2, taking into account how much one can shift elements of a
    6717             :   // particular size?
    6718           6 :   uint64_t C2 = C2node->getZExtValue();
    6719             :   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
    6720           6 :   if (C2 > ElemSizeInBits)
    6721           0 :     return SDValue();
    6722           6 :   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
    6723           6 :   if ((C1 & ElemMask) != (~C2 & ElemMask))
    6724           4 :     return SDValue();
    6725             : 
    6726           2 :   SDValue X = And.getOperand(0);
    6727           2 :   SDValue Y = Shift.getOperand(0);
    6728             : 
    6729             :   unsigned Intrin =
    6730           2 :       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
    6731             :   SDValue ResultSLI =
    6732             :       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    6733             :                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
    6734           2 :                   Shift.getOperand(1));
    6735             : 
    6736             :   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
    6737             :   LLVM_DEBUG(N->dump(&DAG));
    6738             :   LLVM_DEBUG(dbgs() << "into: \n");
    6739             :   LLVM_DEBUG(ResultSLI->dump(&DAG));
    6740             : 
    6741             :   ++NumShiftInserts;
    6742           2 :   return ResultSLI;
    6743             : }
    6744             : 
    6745         569 : SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
    6746             :                                              SelectionDAG &DAG) const {
    6747             :   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
    6748         569 :   if (EnableAArch64SlrGeneration) {
    6749           8 :     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
    6750           2 :       return Res;
    6751             :   }
    6752             : 
    6753         567 :   EVT VT = Op.getValueType();
    6754             : 
    6755         567 :   SDValue LHS = Op.getOperand(0);
    6756             :   BuildVectorSDNode *BVN =
    6757         567 :       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
    6758             :   if (!BVN) {
    6759             :     // OR commutes, so try swapping the operands.
    6760         505 :     LHS = Op.getOperand(1);
    6761         505 :     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
    6762             :   }
    6763          62 :   if (!BVN)
    6764         505 :     return Op;
    6765             : 
    6766          62 :   APInt DefBits(VT.getSizeInBits(), 0);
    6767          62 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6768          62 :   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
    6769             :     SDValue NewOp;
    6770             : 
    6771         124 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
    6772          84 :                                     DefBits, &LHS)) ||
    6773          84 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
    6774          84 :                                     DefBits, &LHS)))
    6775          62 :       return NewOp;
    6776             : 
    6777           0 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
    6778           0 :                                     UndefBits, &LHS)) ||
    6779           0 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
    6780           0 :                                     UndefBits, &LHS)))
    6781           0 :       return NewOp;
    6782             :   }
    6783             : 
    6784             :   // We can always fall back to a non-immediate OR.
    6785           0 :   return Op;
    6786             : }
    6787             : 
    6788             : // Normalize the operands of BUILD_VECTOR. The value of constant operands will
    6789             : // be truncated to fit element width.
    6790        1749 : static SDValue NormalizeBuildVector(SDValue Op,
    6791             :                                     SelectionDAG &DAG) {
    6792             :   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
    6793             :   SDLoc dl(Op);
    6794        1749 :   EVT VT = Op.getValueType();
    6795        1749 :   EVT EltTy= VT.getVectorElementType();
    6796             : 
    6797        1749 :   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
    6798        1095 :     return Op;
    6799             : 
    6800             :   SmallVector<SDValue, 16> Ops;
    6801       11118 :   for (SDValue Lane : Op->ops()) {
    6802             :     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
    6803             :       APInt LowBits(EltTy.getSizeInBits(),
    6804        7336 :                     CstLane->getZExtValue());
    6805        3668 :       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
    6806             :     }
    6807        5232 :     Ops.push_back(Lane);
    6808             :   }
    6809         654 :   return DAG.getBuildVector(VT, dl, Ops);
    6810             : }
    6811             : 
    6812        1111 : static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
    6813        1111 :   EVT VT = Op.getValueType();
    6814             : 
    6815        1111 :   APInt DefBits(VT.getSizeInBits(), 0);
    6816        1111 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6817             :   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
    6818        1111 :   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
    6819             :     SDValue NewOp;
    6820        1343 :     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
    6821        1643 :         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
    6822        1050 :         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
    6823         973 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
    6824        1347 :         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
    6825         651 :         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
    6826         334 :       return NewOp;
    6827             : 
    6828         139 :     DefBits = ~DefBits;
    6829         405 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
    6830         398 :         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
    6831         259 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
    6832          28 :       return NewOp;
    6833             : 
    6834         111 :     DefBits = UndefBits;
    6835         333 :     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
    6836         444 :         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
    6837         333 :         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
    6838         333 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
    6839         444 :         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
    6840         222 :         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
    6841           0 :       return NewOp;
    6842             : 
    6843         111 :     DefBits = ~UndefBits;
    6844         333 :     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
    6845         333 :         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
    6846         222 :         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
    6847           0 :       return NewOp;
    6848             :   }
    6849             : 
    6850         749 :   return SDValue();
    6851             : }
    6852             : 
    6853        1749 : SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
    6854             :                                                  SelectionDAG &DAG) const {
    6855        1749 :   EVT VT = Op.getValueType();
    6856             : 
    6857             :   // Try to build a simple constant vector.
    6858        1749 :   Op = NormalizeBuildVector(Op, DAG);
    6859        1749 :   if (VT.isInteger()) {
    6860             :     // Certain vector constants, used to express things like logical NOT and
    6861             :     // arithmetic NEG, are passed through unmodified.  This allows special
    6862             :     // patterns for these operations to match, which will lower these constants
    6863             :     // to whatever is proven necessary.
    6864             :     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
    6865        1469 :     if (BVN->isConstant())
    6866        1060 :       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
    6867         938 :         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
    6868             :         APInt Val(BitSize,
    6869        2814 :                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
    6870        1684 :         if (Val.isNullValue() || Val.isAllOnesValue())
    6871         687 :           return Op;
    6872             :       }
    6873             :   }
    6874             : 
    6875        1062 :   if (SDValue V = ConstantBuildVector(Op, DAG))
    6876         333 :     return V;
    6877             : 
    6878             :   // Scan through the operands to find some interesting properties we can
    6879             :   // exploit:
    6880             :   //   1) If only one value is used, we can use a DUP, or
    6881             :   //   2) if only the low element is not undef, we can just insert that, or
    6882             :   //   3) if only one constant value is used (w/ some non-constant lanes),
    6883             :   //      we can splat the constant value into the whole vector then fill
    6884             :   //      in the non-constant lanes.
    6885             :   //   4) FIXME: If different constant values are used, but we can intelligently
    6886             :   //             select the values we'll be overwriting for the non-constant
    6887             :   //             lanes such that we can directly materialize the vector
    6888             :   //             some other way (MOVI, e.g.), we can be sneaky.
    6889             :   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
    6890             :   SDLoc dl(Op);
    6891         729 :   unsigned NumElts = VT.getVectorNumElements();
    6892             :   bool isOnlyLowElement = true;
    6893             :   bool usesOnlyOneValue = true;
    6894             :   bool usesOnlyOneConstantValue = true;
    6895             :   bool isConstant = true;
    6896             :   bool AllLanesExtractElt = true;
    6897             :   unsigned NumConstantLanes = 0;
    6898         729 :   SDValue Value;
    6899             :   SDValue ConstantValue;
    6900        7545 :   for (unsigned i = 0; i < NumElts; ++i) {
    6901        3408 :     SDValue V = Op.getOperand(i);
    6902        3408 :     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
    6903             :       AllLanesExtractElt = false;
    6904        3408 :     if (V.isUndef())
    6905             :       continue;
    6906        2689 :     if (i > 0)
    6907             :       isOnlyLowElement = false;
    6908             :     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
    6909             :       isConstant = false;
    6910             : 
    6911             :     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
    6912         793 :       ++NumConstantLanes;
    6913         793 :       if (!ConstantValue.getNode())
    6914             :         ConstantValue = V;
    6915             :       else if (ConstantValue != V)
    6916             :         usesOnlyOneConstantValue = false;
    6917             :     }
    6918             : 
    6919        2689 :     if (!Value.getNode())
    6920         729 :       Value = V;
    6921             :     else if (V != Value)
    6922             :       usesOnlyOneValue = false;
    6923             :   }
    6924             : 
    6925         729 :   if (!Value.getNode()) {
    6926             :     LLVM_DEBUG(
    6927             :         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
    6928           0 :     return DAG.getUNDEF(VT);
    6929             :   }
    6930             : 
    6931         729 :   if (isOnlyLowElement) {
    6932             :     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
    6933             :                          "SCALAR_TO_VECTOR node\n");
    6934         227 :     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
    6935             :   }
    6936             : 
    6937         502 :   if (AllLanesExtractElt) {
    6938             :     SDNode *Vector = nullptr;
    6939             :     bool Even = false;
    6940             :     bool Odd = false;
    6941             :     // Check whether the extract elements match the Even pattern <0,2,4,...> or
    6942             :     // the Odd pattern <1,3,5,...>.
    6943          10 :     for (unsigned i = 0; i < NumElts; ++i) {
    6944          10 :       SDValue V = Op.getOperand(i);
    6945             :       const SDNode *N = V.getNode();
    6946          10 :       if (!isa<ConstantSDNode>(N->getOperand(1)))
    6947             :         break;
    6948           9 :       SDValue N0 = N->getOperand(0);
    6949             : 
    6950             :       // All elements are extracted from the same vector.
    6951           9 :       if (!Vector) {
    6952             :         Vector = N0.getNode();
    6953             :         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
    6954             :         // BUILD_VECTOR.
    6955          18 :         if (VT.getVectorElementType() !=
    6956          18 :             N0.getValueType().getVectorElementType())
    6957             :           break;
    6958           0 :       } else if (Vector != N0.getNode()) {
    6959             :         Odd = false;
    6960             :         Even = false;
    6961             :         break;
    6962             :       }
    6963             : 
    6964             :       // Extracted values are either at Even indices <0,2,4,...> or at Odd
    6965             :       // indices <1,3,5,...>.
    6966             :       uint64_t Val = N->getConstantOperandVal(1);
    6967           0 :       if (Val == 2 * i) {
    6968             :         Even = true;
    6969           0 :         continue;
    6970             :       }
    6971           0 :       if (Val - 1 == 2 * i) {
    6972             :         Odd = true;
    6973           0 :         continue;
    6974             :       }
    6975             : 
    6976             :       // Something does not match: abort.
    6977             :       Odd = false;
    6978             :       Even = false;
    6979             :       break;
    6980             :     }
    6981          10 :     if (Even || Odd) {
    6982             :       SDValue LHS =
    6983             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
    6984           0 :                       DAG.getConstant(0, dl, MVT::i64));
    6985             :       SDValue RHS =
    6986             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
    6987           0 :                       DAG.getConstant(NumElts, dl, MVT::i64));
    6988             : 
    6989           0 :       if (Even && !Odd)
    6990             :         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
    6991           0 :                            RHS);
    6992           0 :       if (Odd && !Even)
    6993             :         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
    6994           0 :                            RHS);
    6995             :     }
    6996             :   }
    6997             : 
    6998             :   // Use DUP for non-constant splats. For f32 constant splats, reduce to
    6999             :   // i32 and try again.
    7000         502 :   if (usesOnlyOneValue) {
    7001         183 :     if (!isConstant) {
    7002         320 :       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
    7003          18 :           Value.getValueType() != VT) {
    7004             :         LLVM_DEBUG(
    7005             :             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
    7006         160 :         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
    7007             :       }
    7008             : 
    7009             :       // This is actually a DUPLANExx operation, which keeps everything vectory.
    7010             : 
    7011           0 :       SDValue Lane = Value.getOperand(1);
    7012           0 :       Value = Value.getOperand(0);
    7013           0 :       if (Value.getValueSizeInBits() == 64) {
    7014             :         LLVM_DEBUG(
    7015             :             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
    7016             :                       "widening it\n");
    7017           0 :         Value = WidenVector(Value, DAG);
    7018             :       }
    7019             : 
    7020           0 :       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
    7021           0 :       return DAG.getNode(Opcode, dl, VT, Value, Lane);
    7022             :     }
    7023             : 
    7024          23 :     if (VT.getVectorElementType().isFloatingPoint()) {
    7025             :       SmallVector<SDValue, 8> Ops;
    7026           3 :       EVT EltTy = VT.getVectorElementType();
    7027             :       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
    7028             :               "Unsupported floating-point vector type");
    7029             :       LLVM_DEBUG(
    7030             :           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
    7031             :                     "BITCASTS, and try again\n");
    7032           3 :       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
    7033          23 :       for (unsigned i = 0; i < NumElts; ++i)
    7034          10 :         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
    7035           3 :       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
    7036           3 :       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
    7037             :       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
    7038             :                  Val.dump(););
    7039           3 :       Val = LowerBUILD_VECTOR(Val, DAG);
    7040           3 :       if (Val.getNode())
    7041           3 :         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
    7042             :     }
    7043             :   }
    7044             : 
    7045             :   // If there was only one constant value used and for more than one lane,
    7046             :   // start by splatting that value, then replace the non-constant lanes. This
    7047             :   // is better than the default, which will perform a separate initialization
    7048             :   // for each lane.
    7049         339 :   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
    7050             :     // Firstly, try to materialize the splat constant.
    7051          49 :     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
    7052          49 :             Val = ConstantBuildVector(Vec, DAG);
    7053          49 :     if (!Val) {
    7054             :       // Otherwise, materialize the constant and splat it.
    7055          20 :       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
    7056          20 :       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
    7057             :     }
    7058             : 
    7059             :     // Now insert the non-constant lanes.
    7060         517 :     for (unsigned i = 0; i < NumElts; ++i) {
    7061         234 :       SDValue V = Op.getOperand(i);
    7062         234 :       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
    7063             :       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
    7064             :         // Note that type legalization likely mucked about with the VT of the
    7065             :         // source operand, so we may have to convert it here before inserting.
    7066          29 :         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
    7067             :     }
    7068          49 :     return Val;
    7069             :   }
    7070             : 
    7071             :   // This will generate a load from the constant pool.
    7072         290 :   if (isConstant) {
    7073             :     LLVM_DEBUG(
    7074             :         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
    7075             :                   "expansion\n");
    7076          64 :     return SDValue();
    7077             :   }
    7078             : 
    7079             :   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
    7080         226 :   if (NumElts >= 4) {
    7081         132 :     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
    7082           3 :       return shuffle;
    7083             :   }
    7084             : 
    7085             :   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
    7086             :   // know the default expansion would otherwise fall back on something even
    7087             :   // worse. For a vector with one or two non-undef values, that's
    7088             :   // scalar_to_vector for the elements followed by a shuffle (provided the
    7089             :   // shuffle is valid for the target) and materialization element by element
    7090             :   // on the stack followed by a load for everything else.
    7091         223 :   if (!isConstant && !usesOnlyOneValue) {
    7092             :     LLVM_DEBUG(
    7093             :         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
    7094             :                   "of INSERT_VECTOR_ELT\n");
    7095             : 
    7096         223 :     SDValue Vec = DAG.getUNDEF(VT);
    7097         223 :     SDValue Op0 = Op.getOperand(0);
    7098             :     unsigned i = 0;
    7099             : 
    7100             :     // Use SCALAR_TO_VECTOR for lane zero to
    7101             :     // a) Avoid a RMW dependency on the full vector register, and
    7102             :     // b) Allow the register coalescer to fold away the copy if the
    7103             :     //    value is already in an S or D register, and we're forced to emit an
    7104             :     //    INSERT_SUBREG that we can't fold anywhere.
    7105             :     //
    7106             :     // We also allow types like i8 and i16 which are illegal scalar but legal
    7107             :     // vector element types. After type-legalization the inserted value is
    7108             :     // extended (i32) and it is safe to cast them to the vector type by ignoring
    7109             :     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
    7110         223 :     if (!Op0.isUndef()) {
    7111             :       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
    7112         223 :       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
    7113             :       ++i;
    7114             :     }
    7115             :     LLVM_DEBUG(if (i < NumElts) dbgs()
    7116             :                    << "Creating nodes for the other vector elements:\n";);
    7117        1737 :     for (; i < NumElts; ++i) {
    7118         757 :       SDValue V = Op.getOperand(i);
    7119         757 :       if (V.isUndef())
    7120           1 :         continue;
    7121         756 :       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
    7122         756 :       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
    7123             :     }
    7124         223 :     return Vec;
    7125             :   }
    7126             : 
    7127             :   LLVM_DEBUG(
    7128             :       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
    7129             :                 "better alternative\n");
    7130           0 :   return SDValue();
    7131             : }
    7132             : 
    7133        2102 : SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
    7134             :                                                       SelectionDAG &DAG) const {
    7135             :   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
    7136             : 
    7137             :   // Check for non-constant or out of range lane.
    7138        4204 :   EVT VT = Op.getOperand(0).getValueType();
    7139             :   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
    7140        4196 :   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
    7141           4 :     return SDValue();
    7142             : 
    7143             : 
    7144             :   // Insertion/extraction are legal for V128 types.
    7145             :   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
    7146             :       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
    7147             :       VT == MVT::v8f16)
    7148        1850 :     return Op;
    7149             : 
    7150             :   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
    7151             :       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
    7152           2 :     return SDValue();
    7153             : 
    7154             :   // For V64 types, we perform insertion by expanding the value
    7155             :   // to a V128 type and perform the insertion on that.
    7156             :   SDLoc DL(Op);
    7157         246 :   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
    7158         492 :   EVT WideTy = WideVec.getValueType();
    7159             : 
    7160             :   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
    7161         246 :                              Op.getOperand(1), Op.getOperand(2));
    7162             :   // Re-narrow the resultant vector.
    7163         246 :   return NarrowVector(Node, DAG);
    7164             : }
    7165             : 
    7166             : SDValue
    7167        5267 : AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
    7168             :                                                SelectionDAG &DAG) const {
    7169             :   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
    7170             : 
    7171             :   // Check for non-constant or out of range lane.
    7172       10534 :   EVT VT = Op.getOperand(0).getValueType();
    7173             :   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    7174       10528 :   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
    7175           3 :     return SDValue();
    7176             : 
    7177             : 
    7178             :   // Insertion/extraction are legal for V128 types.
    7179             :   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
    7180             :       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
    7181             :       VT == MVT::v8f16)
    7182        4540 :     return Op;
    7183             : 
    7184             :   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
    7185             :       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
    7186          66 :     return SDValue();
    7187             : 
    7188             :   // For V64 types, we perform extraction by expanding the value
    7189             :   // to a V128 type and perform the extraction on that.
    7190             :   SDLoc DL(Op);
    7191         658 :   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
    7192        1316 :   EVT WideTy = WideVec.getValueType();
    7193             : 
    7194         658 :   EVT ExtrTy = WideTy.getVectorElementType();
    7195             :   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
    7196             :     ExtrTy = MVT::i32;
    7197             : 
    7198             :   // For extractions, we just return the result directly.
    7199             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
    7200         658 :                      Op.getOperand(1));
    7201             : }
    7202             : 
    7203        1646 : SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
    7204             :                                                       SelectionDAG &DAG) const {
    7205        4938 :   EVT VT = Op.getOperand(0).getValueType();
    7206             :   SDLoc dl(Op);
    7207             :   // Just in case...
    7208        1646 :   if (!VT.isVector())
    7209           0 :     return SDValue();
    7210             : 
    7211        1646 :   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    7212             :   if (!Cst)
    7213           0 :     return SDValue();
    7214        3292 :   unsigned Val = Cst->getZExtValue();
    7215             : 
    7216        1646 :   unsigned Size = Op.getValueSizeInBits();
    7217             : 
    7218             :   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
    7219        1646 :   if (Val == 0)
    7220         288 :     return Op;
    7221             : 
    7222             :   // If this is extracting the upper 64-bits of a 128-bit vector, we match
    7223             :   // that directly.
    7224        2716 :   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
    7225        1358 :     return Op;
    7226             : 
    7227           0 :   return SDValue();
    7228             : }
    7229             : 
    7230          57 : bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
    7231          64 :   if (VT.getVectorNumElements() == 4 &&
    7232          11 :       (VT.is128BitVector() || VT.is64BitVector())) {
    7233             :     unsigned PFIndexes[4];
    7234             :     for (unsigned i = 0; i != 4; ++i) {
    7235             :       if (M[i] < 0)
    7236             :         PFIndexes[i] = 8;
    7237             :       else
    7238             :         PFIndexes[i] = M[i];
    7239             :     }
    7240             : 
    7241             :     // Compute the index in the perfect shuffle table.
    7242             :     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
    7243             :                             PFIndexes[2] * 9 + PFIndexes[3];
    7244             :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    7245             :     unsigned Cost = (PFEntry >> 30);
    7246             : 
    7247             :     if (Cost <= 4)
    7248             :       return true;
    7249             :   }
    7250             : 
    7251             :   bool DummyBool;
    7252             :   int DummyInt;
    7253             :   unsigned DummyUnsigned;
    7254             : 
    7255         140 :   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
    7256         133 :           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
    7257          84 :           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
    7258             :           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
    7259          72 :           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
    7260          31 :           isZIPMask(M, VT, DummyUnsigned) ||
    7261          30 :           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
    7262          30 :           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
    7263          30 :           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
    7264          78 :           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
    7265          13 :           isConcatMask(M, VT, VT.getSizeInBits() == 128));
    7266             : }
    7267             : 
    7268             : /// getVShiftImm - Check if this is a valid build_vector for the immediate
    7269             : /// operand of a vector shift operation, where all the elements of the
    7270             : /// build_vector must have the same constant integer value.
    7271         231 : static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
    7272             :   // Ignore bit_converts.
    7273         231 :   while (Op.getOpcode() == ISD::BITCAST)
    7274           0 :     Op = Op.getOperand(0);
    7275             :   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
    7276             :   APInt SplatBits, SplatUndef;
    7277             :   unsigned SplatBitSize;
    7278             :   bool HasAnyUndefs;
    7279         227 :   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
    7280         458 :                                     HasAnyUndefs, ElementBits) ||
    7281         227 :       SplatBitSize > ElementBits)
    7282             :     return false;
    7283         227 :   Cnt = SplatBits.getSExtValue();
    7284             :   return true;
    7285             : }
    7286             : 
    7287             : /// isVShiftLImm - Check if this is a valid build_vector for the immediate
    7288             : /// operand of a vector shift left operation.  That value must be in the range:
    7289             : ///   0 <= Value < ElementBits for a left shift; or
    7290             : ///   0 <= Value <= ElementBits for a long left shift.
    7291          53 : static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
    7292             :   assert(VT.isVector() && "vector shift count is not a vector type");
    7293          53 :   int64_t ElementBits = VT.getScalarSizeInBits();
    7294          53 :   if (!getVShiftImm(Op, ElementBits, Cnt))
    7295             :     return false;
    7296          53 :   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
    7297             : }
    7298             : 
    7299             : /// isVShiftRImm - Check if this is a valid build_vector for the immediate
    7300             : /// operand of a vector shift right operation. The value must be in the range:
    7301             : ///   1 <= Value <= ElementBits for a right shift; or
    7302         178 : static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
    7303             :   assert(VT.isVector() && "vector shift count is not a vector type");
    7304         178 :   int64_t ElementBits = VT.getScalarSizeInBits();
    7305         178 :   if (!getVShiftImm(Op, ElementBits, Cnt))
    7306             :     return false;
    7307         174 :   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
    7308             : }
    7309             : 
    7310         231 : SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
    7311             :                                                       SelectionDAG &DAG) const {
    7312         231 :   EVT VT = Op.getValueType();
    7313             :   SDLoc DL(Op);
    7314             :   int64_t Cnt;
    7315             : 
    7316         693 :   if (!Op.getOperand(1).getValueType().isVector())
    7317           0 :     return Op;
    7318             :   unsigned EltSize = VT.getScalarSizeInBits();
    7319             : 
    7320         231 :   switch (Op.getOpcode()) {
    7321           0 :   default:
    7322           0 :     llvm_unreachable("unexpected shift opcode");
    7323             : 
    7324          53 :   case ISD::SHL:
    7325          53 :     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
    7326             :       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
    7327         106 :                          DAG.getConstant(Cnt, DL, MVT::i32));
    7328             :     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    7329             :                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
    7330             :                                        MVT::i32),
    7331           0 :                        Op.getOperand(0), Op.getOperand(1));
    7332         178 :   case ISD::SRA:
    7333             :   case ISD::SRL:
    7334             :     // Right shift immediate
    7335         178 :     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
    7336             :       unsigned Opc =
    7337         174 :           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
    7338             :       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
    7339         348 :                          DAG.getConstant(Cnt, DL, MVT::i32));
    7340             :     }
    7341             : 
    7342             :     // Right shift register.  Note, there is not a shift right register
    7343             :     // instruction, but the shift left register instruction takes a signed
    7344             :     // value, where negative numbers specify a right shift.
    7345           4 :     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
    7346             :                                                 : Intrinsic::aarch64_neon_ushl;
    7347             :     // negate the shift amount
    7348           4 :     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
    7349             :     SDValue NegShiftLeft =
    7350             :         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    7351             :                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
    7352           4 :                     NegShift);
    7353           4 :     return NegShiftLeft;
    7354             :   }
    7355             : 
    7356             :   return SDValue();
    7357             : }
    7358             : 
    7359         520 : static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
    7360             :                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
    7361             :                                     const SDLoc &dl, SelectionDAG &DAG) {
    7362        1040 :   EVT SrcVT = LHS.getValueType();
    7363             :   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
    7364             :          "function only supposed to emit natural comparisons");
    7365             : 
    7366         520 :   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
    7367         520 :   APInt CnstBits(VT.getSizeInBits(), 0);
    7368         520 :   APInt UndefBits(VT.getSizeInBits(), 0);
    7369         520 :   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
    7370         235 :   bool IsZero = IsCnst && (CnstBits == 0);
    7371             : 
    7372         520 :   if (SrcVT.getVectorElementType().isFloatingPoint()) {
    7373         182 :     switch (CC) {
    7374           0 :     default:
    7375           0 :       return SDValue();
    7376           8 :     case AArch64CC::NE: {
    7377           8 :       SDValue Fcmeq;
    7378           8 :       if (IsZero)
    7379           3 :         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
    7380             :       else
    7381           5 :         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
    7382           8 :       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
    7383             :     }
    7384          33 :     case AArch64CC::EQ:
    7385          33 :       if (IsZero)
    7386          11 :         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
    7387          22 :       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
    7388          34 :     case AArch64CC::GE:
    7389          34 :       if (IsZero)
    7390          13 :         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
    7391          21 :       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
    7392          35 :     case AArch64CC::GT:
    7393          35 :       if (IsZero)
    7394          13 :         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
    7395          22 :       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
    7396          18 :     case AArch64CC::LS:
    7397          18 :       if (IsZero)
    7398           7 :         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
    7399          11 :       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
    7400           0 :     case AArch64CC::LT:
    7401           0 :       if (!NoNans)
    7402           0 :         return SDValue();
    7403             :       // If we ignore NaNs then we can use to the MI implementation.
    7404             :       LLVM_FALLTHROUGH;
    7405             :     case AArch64CC::MI:
    7406          54 :       if (IsZero)
    7407          20 :         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
    7408          34 :       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
    7409             :     }
    7410             :   }
    7411             : 
    7412         338 :   switch (CC) {
    7413           0 :   default:
    7414           0 :     return SDValue();
    7415          46 :   case AArch64CC::NE: {
    7416          46 :     SDValue Cmeq;
    7417          46 :     if (IsZero)
    7418          31 :       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
    7419             :     else
    7420          15 :       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
    7421          46 :     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
    7422             :   }
    7423          60 :   case AArch64CC::EQ:
    7424          60 :     if (IsZero)
    7425          19 :       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
    7426          41 :     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
    7427          30 :   case AArch64CC::GE:
    7428          30 :     if (IsZero)
    7429          15 :       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
    7430          15 :     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
    7431          29 :   case AArch64CC::GT:
    7432          29 :     if (IsZero)
    7433          15 :       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
    7434          14 :     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
    7435          29 :   case AArch64CC::LE:
    7436          29 :     if (IsZero)
    7437          15 :       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
    7438          14 :     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
    7439             :   case AArch64CC::LS:
    7440          28 :     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
    7441             :   case AArch64CC::LO:
    7442          28 :     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
    7443          30 :   case AArch64CC::LT:
    7444          30 :     if (IsZero)
    7445          15 :       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
    7446          15 :     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
    7447             :   case AArch64CC::HI:
    7448          29 :     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
    7449             :   case AArch64CC::HS:
    7450          29 :     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
    7451             :   }
    7452             : }
    7453             : 
    7454         529 : SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
    7455             :                                            SelectionDAG &DAG) const {
    7456         529 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    7457         529 :   SDValue LHS = Op.getOperand(0);
    7458         529 :   SDValue RHS = Op.getOperand(1);
    7459         529 :   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
    7460             :   SDLoc dl(Op);
    7461             : 
    7462         529 :   if (LHS.getValueType().getVectorElementType().isInteger()) {
    7463             :     assert(LHS.getValueType() == RHS.getValueType());
    7464         338 :     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    7465             :     SDValue Cmp =
    7466         338 :         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
    7467         338 :     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
    7468             :   }
    7469             : 
    7470             :   const bool FullFP16 =
    7471         382 :     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
    7472             : 
    7473             :   // Make v4f16 (only) fcmp operations utilise vector instructions
    7474             :   // v8f16 support will be a litle more complicated
    7475         326 :   if (LHS.getValueType().getVectorElementType() == MVT::f16) {
    7476          98 :     if (!FullFP16 && LHS.getValueType().getVectorNumElements() == 4) {
    7477          14 :       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
    7478          14 :       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
    7479          14 :       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
    7480          14 :       DAG.ReplaceAllUsesWith(Op, NewSetcc);
    7481          14 :       CmpVT = MVT::v4i32;
    7482             :     } else
    7483          42 :       return SDValue();
    7484             :   }
    7485             : 
    7486             :   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
    7487             :          LHS.getValueType().getVectorElementType() == MVT::f64);
    7488             : 
    7489             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    7490             :   // clean.  Some of them require two branches to implement.
    7491             :   AArch64CC::CondCode CC1, CC2;
    7492             :   bool ShouldInvert;
    7493         149 :   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
    7494             : 
    7495         149 :   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
    7496             :   SDValue Cmp =
    7497         149 :       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
    7498         149 :   if (!Cmp.getNode())
    7499           0 :     return SDValue();
    7500             : 
    7501         149 :   if (CC2 != AArch64CC::AL) {
    7502             :     SDValue Cmp2 =
    7503          33 :         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
    7504          33 :     if (!Cmp2.getNode())
    7505           0 :       return SDValue();
    7506             : 
    7507          33 :     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
    7508             :   }
    7509             : 
    7510         149 :   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
    7511             : 
    7512         149 :   if (ShouldInvert)
    7513          48 :     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
    7514             : 
    7515         101 :   return Cmp;
    7516             : }
    7517             : 
    7518          54 : static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
    7519             :                                   SelectionDAG &DAG) {
    7520          54 :   SDValue VecOp = ScalarOp.getOperand(0);
    7521          54 :   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
    7522             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
    7523         108 :                      DAG.getConstant(0, DL, MVT::i64));
    7524             : }
    7525             : 
    7526          58 : SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
    7527             :                                               SelectionDAG &DAG) const {
    7528             :   SDLoc dl(Op);
    7529          58 :   switch (Op.getOpcode()) {
    7530             :   case ISD::VECREDUCE_ADD:
    7531          28 :     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
    7532             :   case ISD::VECREDUCE_SMAX:
    7533          20 :     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
    7534             :   case ISD::VECREDUCE_SMIN:
    7535          20 :     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
    7536             :   case ISD::VECREDUCE_UMAX:
    7537          20 :     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
    7538             :   case ISD::VECREDUCE_UMIN:
    7539          20 :     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
    7540             :   case ISD::VECREDUCE_FMAX: {
    7541             :     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
    7542             :     return DAG.getNode(
    7543             :         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
    7544             :         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
    7545           4 :         Op.getOperand(0));
    7546             :   }
    7547             :   case ISD::VECREDUCE_FMIN: {
    7548             :     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
    7549             :     return DAG.getNode(
    7550             :         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
    7551             :         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
    7552           4 :         Op.getOperand(0));
    7553             :   }
    7554           0 :   default:
    7555           0 :     llvm_unreachable("Unhandled reduction");
    7556             :   }
    7557             : }
    7558             : 
    7559         176 : SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
    7560             :                                                     SelectionDAG &DAG) const {
    7561         176 :   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
    7562         176 :   if (!Subtarget.hasLSE())
    7563           0 :     return SDValue();
    7564             : 
    7565             :   // LSE has an atomic load-add instruction, but not a load-sub.
    7566             :   SDLoc dl(Op);
    7567             :   MVT VT = Op.getSimpleValueType();
    7568         176 :   SDValue RHS = Op.getOperand(2);
    7569             :   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
    7570         352 :   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
    7571             :   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
    7572             :                        Op.getOperand(0), Op.getOperand(1), RHS,
    7573         352 :                        AN->getMemOperand());
    7574             : }
    7575             : 
    7576         176 : SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
    7577             :                                                     SelectionDAG &DAG) const {
    7578         176 :   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
    7579         176 :   if (!Subtarget.hasLSE())
    7580           0 :     return SDValue();
    7581             : 
    7582             :   // LSE has an atomic load-clear instruction, but not a load-and.
    7583             :   SDLoc dl(Op);
    7584             :   MVT VT = Op.getSimpleValueType();
    7585         176 :   SDValue RHS = Op.getOperand(2);
    7586             :   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
    7587         352 :   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
    7588             :   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
    7589             :                        Op.getOperand(0), Op.getOperand(1), RHS,
    7590         352 :                        AN->getMemOperand());
    7591             : }
    7592             : 
    7593           3 : SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
    7594             :     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
    7595             :   SDLoc dl(Op);
    7596           3 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    7597           3 :   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
    7598             : 
    7599             :   const uint32_t *Mask =
    7600           6 :       Subtarget->getRegisterInfo()->getWindowsStackProbePreservedMask();
    7601             : 
    7602           3 :   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
    7603           6 :                      DAG.getConstant(4, dl, MVT::i64));
    7604           3 :   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
    7605           3 :   Chain =
    7606           6 :       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
    7607             :                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
    7608          12 :                   DAG.getRegisterMask(Mask), Chain.getValue(1));
    7609             :   // To match the actual intent better, we should read the output from X15 here
    7610             :   // again (instead of potentially spilling it to the stack), but rereading Size
    7611             :   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
    7612             :   // here.
    7613             : 
    7614           3 :   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
    7615           6 :                      DAG.getConstant(4, dl, MVT::i64));
    7616           6 :   return Chain;
    7617             : }
    7618             : 
    7619             : SDValue
    7620           4 : AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
    7621             :                                                SelectionDAG &DAG) const {
    7622             :   assert(Subtarget->isTargetWindows() &&
    7623             :          "Only Windows alloca probing supported");
    7624             :   SDLoc dl(Op);
    7625             :   // Get the inputs.
    7626             :   SDNode *Node = Op.getNode();
    7627           4 :   SDValue Chain = Op.getOperand(0);
    7628           4 :   SDValue Size = Op.getOperand(1);
    7629           8 :   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
    7630           8 :   EVT VT = Node->getValueType(0);
    7631             : 
    7632           8 :   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
    7633             :           "no-stack-arg-probe")) {
    7634           1 :     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
    7635             :     Chain = SP.getValue(1);
    7636           1 :     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
    7637           1 :     if (Align)
    7638           0 :       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
    7639           0 :                        DAG.getConstant(-(uint64_t)Align, dl, VT));
    7640           1 :     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
    7641           1 :     SDValue Ops[2] = {SP, Chain};
    7642           1 :     return DAG.getMergeValues(Ops, dl);
    7643             :   }
    7644             : 
    7645           3 :   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
    7646             : 
    7647           3 :   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
    7648             : 
    7649           3 :   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
    7650             :   Chain = SP.getValue(1);
    7651           3 :   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
    7652           3 :   if (Align)
    7653           0 :     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
    7654           0 :                      DAG.getConstant(-(uint64_t)Align, dl, VT));
    7655           3 :   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
    7656             : 
    7657           3 :   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
    7658           6 :                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
    7659             : 
    7660           3 :   SDValue Ops[2] = {SP, Chain};
    7661           3 :   return DAG.getMergeValues(Ops, dl);
    7662             : }
    7663             : 
    7664             : /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
    7665             : /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
    7666             : /// specified in the intrinsic calls.
    7667        4320 : bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
    7668             :                                                const CallInst &I,
    7669             :                                                MachineFunction &MF,
    7670             :                                                unsigned Intrinsic) const {
    7671        4320 :   auto &DL = I.getModule()->getDataLayout();
    7672        4320 :   switch (Intrinsic) {
    7673         434 :   case Intrinsic::aarch64_neon_ld2:
    7674             :   case Intrinsic::aarch64_neon_ld3:
    7675             :   case Intrinsic::aarch64_neon_ld4:
    7676             :   case Intrinsic::aarch64_neon_ld1x2:
    7677             :   case Intrinsic::aarch64_neon_ld1x3:
    7678             :   case Intrinsic::aarch64_neon_ld1x4:
    7679             :   case Intrinsic::aarch64_neon_ld2lane:
    7680             :   case Intrinsic::aarch64_neon_ld3lane:
    7681             :   case Intrinsic::aarch64_neon_ld4lane:
    7682             :   case Intrinsic::aarch64_neon_ld2r:
    7683             :   case Intrinsic::aarch64_neon_ld3r:
    7684             :   case Intrinsic::aarch64_neon_ld4r: {
    7685         434 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7686             :     // Conservatively set memVT to the entire set of vectors loaded.
    7687         434 :     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
    7688         868 :     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
    7689         868 :     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
    7690         434 :     Info.offset = 0;
    7691         434 :     Info.align = 0;
    7692             :     // volatile loads with NEON intrinsics not supported
    7693         434 :     Info.flags = MachineMemOperand::MOLoad;
    7694         434 :     return true;
    7695             :   }
    7696         401 :   case Intrinsic::aarch64_neon_st2:
    7697             :   case Intrinsic::aarch64_neon_st3:
    7698             :   case Intrinsic::aarch64_neon_st4:
    7699             :   case Intrinsic::aarch64_neon_st1x2:
    7700             :   case Intrinsic::aarch64_neon_st1x3:
    7701             :   case Intrinsic::aarch64_neon_st1x4:
    7702             :   case Intrinsic::aarch64_neon_st2lane:
    7703             :   case Intrinsic::aarch64_neon_st3lane:
    7704             :   case Intrinsic::aarch64_neon_st4lane: {
    7705         401 :     Info.opc = ISD::INTRINSIC_VOID;
    7706             :     // Conservatively set memVT to the entire set of vectors stored.
    7707             :     unsigned NumElts = 0;
    7708        2382 :     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
    7709        1191 :       Type *ArgTy = I.getArgOperand(ArgI)->getType();
    7710        1191 :       if (!ArgTy->isVectorTy())
    7711             :         break;
    7712         790 :       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
    7713             :     }
    7714         401 :     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
    7715         401 :     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
    7716         401 :     Info.offset = 0;
    7717         401 :     Info.align = 0;
    7718             :     // volatile stores with NEON intrinsics not supported
    7719         401 :     Info.flags = MachineMemOperand::MOStore;
    7720         401 :     return true;
    7721             :   }
    7722         112 :   case Intrinsic::aarch64_ldaxr:
    7723             :   case Intrinsic::aarch64_ldxr: {
    7724         224 :     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
    7725         112 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7726         112 :     Info.memVT = MVT::getVT(PtrTy->getElementType());
    7727             :     Info.ptrVal = I.getArgOperand(0);
    7728         112 :     Info.offset = 0;
    7729         112 :     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
    7730         112 :     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
    7731         112 :     return true;
    7732             :   }
    7733         111 :   case Intrinsic::aarch64_stlxr:
    7734             :   case Intrinsic::aarch64_stxr: {
    7735         222 :     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
    7736         111 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7737         111 :     Info.memVT = MVT::getVT(PtrTy->getElementType());
    7738             :     Info.ptrVal = I.getArgOperand(1);
    7739         111 :     Info.offset = 0;
    7740         111 :     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
    7741         111 :     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
    7742         111 :     return true;
    7743             :   }
    7744          16 :   case Intrinsic::aarch64_ldaxp:
    7745             :   case Intrinsic::aarch64_ldxp:
    7746          16 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7747          16 :     Info.memVT = MVT::i128;
    7748          16 :     Info.ptrVal = I.getArgOperand(0);
    7749          16 :     Info.offset = 0;
    7750          16 :     Info.align = 16;
    7751          16 :     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
    7752          16 :     return true;
    7753          16 :   case Intrinsic::aarch64_stlxp:
    7754             :   case Intrinsic::aarch64_stxp:
    7755          16 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7756          16 :     Info.memVT = MVT::i128;
    7757          16 :     Info.ptrVal = I.getArgOperand(2);
    7758          16 :     Info.offset = 0;
    7759          16 :     Info.align = 16;
    7760          16 :     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
    7761          16 :     return true;
    7762             :   default:
    7763             :     break;
    7764             :   }
    7765             : 
    7766             :   return false;
    7767             : }
    7768             : 
    7769          87 : bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
    7770             :                                                   ISD::LoadExtType ExtTy,
    7771             :                                                   EVT NewVT) const {
    7772             :   // If we're reducing the load width in order to avoid having to use an extra
    7773             :   // instruction to do extension then it's probably a good idea.
    7774          87 :   if (ExtTy != ISD::NON_EXTLOAD)
    7775             :     return true;
    7776             :   // Don't reduce load width if it would prevent us from combining a shift into
    7777             :   // the offset.
    7778             :   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
    7779             :   assert(Mem);
    7780             :   const SDValue &Base = Mem->getBasePtr();
    7781          60 :   if (Base.getOpcode() == ISD::ADD &&
    7782          56 :       Base.getOperand(1).getOpcode() == ISD::SHL &&
    7783          82 :       Base.getOperand(1).hasOneUse() &&
    7784          66 :       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
    7785             :     // The shift can be combined if it matches the size of the value being
    7786             :     // loaded (and so reducing the width would make it not match).
    7787             :     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
    7788          22 :     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
    7789          22 :     if (ShiftAmount == Log2_32(LoadBytes))
    7790             :       return false;
    7791             :   }
    7792             :   // We have no reason to disallow reducing the load width, so allow it.
    7793             :   return true;
    7794             : }
    7795             : 
    7796             : // Truncations from 64-bit GPR to 32-bit GPR is free.
    7797         806 : bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
    7798        1491 :   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
    7799             :     return false;
    7800         685 :   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
    7801         685 :   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
    7802         685 :   return NumBits1 > NumBits2;
    7803             : }
    7804         956 : bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
    7805        1910 :   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
    7806             :     return false;
    7807         954 :   unsigned NumBits1 = VT1.getSizeInBits();
    7808         954 :   unsigned NumBits2 = VT2.getSizeInBits();
    7809         954 :   return NumBits1 > NumBits2;
    7810             : }
    7811             : 
    7812             : /// Check if it is profitable to hoist instruction in then/else to if.
    7813             : /// Not profitable if I and it's user can form a FMA instruction
    7814             : /// because we prefer FMSUB/FMADD.
    7815          15 : bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
    7816          15 :   if (I->getOpcode() != Instruction::FMul)
    7817             :     return true;
    7818             : 
    7819           3 :   if (!I->hasOneUse())
    7820             :     return true;
    7821             : 
    7822             :   Instruction *User = I->user_back();
    7823             : 
    7824           6 :   if (User &&
    7825           3 :       !(User->getOpcode() == Instruction::FSub ||
    7826             :         User->getOpcode() == Instruction::FAdd))
    7827             :     return true;
    7828             : 
    7829           3 :   const TargetOptions &Options = getTargetMachine().Options;
    7830           3 :   const DataLayout &DL = I->getModule()->getDataLayout();
    7831           6 :   EVT VT = getValueType(DL, User->getOperand(0)->getType());
    7832             : 
    7833           6 :   return !(isFMAFasterThanFMulAndFAdd(VT) &&
    7834           3 :            isOperationLegalOrCustom(ISD::FMA, VT) &&
    7835           6 :            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
    7836           3 :             Options.UnsafeFPMath));
    7837             : }
    7838             : 
    7839             : // All 32-bit GPR operations implicitly zero the high-half of the corresponding
    7840             : // 64-bit GPR.
    7841         390 : bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
    7842         780 :   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
    7843             :     return false;
    7844         390 :   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
    7845         390 :   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
    7846         390 :   return NumBits1 == 32 && NumBits2 == 64;
    7847             : }
    7848        2941 : bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
    7849        5327 :   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
    7850             :     return false;
    7851        2254 :   unsigned NumBits1 = VT1.getSizeInBits();
    7852        2254 :   unsigned NumBits2 = VT2.getSizeInBits();
    7853        2254 :   return NumBits1 == 32 && NumBits2 == 64;
    7854             : }
    7855             : 
    7856        1962 : bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
    7857        3924 :   EVT VT1 = Val.getValueType();
    7858        1962 :   if (isZExtFree(VT1, VT2)) {
    7859             :     return true;
    7860             :   }
    7861             : 
    7862        1962 :   if (Val.getOpcode() != ISD::LOAD)
    7863             :     return false;
    7864             : 
    7865             :   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
    7866         562 :   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
    7867        1022 :           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
    7868         230 :           VT1.getSizeInBits() <= 32);
    7869             : }
    7870             : 
    7871         471 : bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
    7872         471 :   if (isa<FPExtInst>(Ext))
    7873             :     return false;
    7874             : 
    7875             :   // Vector types are not free.
    7876         942 :   if (Ext->getType()->isVectorTy())
    7877             :     return false;
    7878             : 
    7879         586 :   for (const Use &U : Ext->uses()) {
    7880             :     // The extension is free if we can fold it with a left shift in an
    7881             :     // addressing mode or an arithmetic operation: add, sub, and cmp.
    7882             : 
    7883             :     // Is there a shift?
    7884         484 :     const Instruction *Instr = cast<Instruction>(U.getUser());
    7885             : 
    7886             :     // Is this a constant shift?
    7887         484 :     switch (Instr->getOpcode()) {
    7888          28 :     case Instruction::Shl:
    7889          56 :       if (!isa<ConstantInt>(Instr->getOperand(1)))
    7890             :         return false;
    7891             :       break;
    7892         115 :     case Instruction::GetElementPtr: {
    7893         115 :       gep_type_iterator GTI = gep_type_begin(Instr);
    7894         115 :       auto &DL = Ext->getModule()->getDataLayout();
    7895         115 :       std::advance(GTI, U.getOperandNo()-1);
    7896         115 :       Type *IdxTy = GTI.getIndexedType();
    7897             :       // This extension will end up with a shift because of the scaling factor.
    7898             :       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
    7899             :       // Get the shift amount based on the scaling factor:
    7900             :       // log2(sizeof(IdxTy)) - log2(8).
    7901             :       uint64_t ShiftAmt =
    7902             :           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
    7903             :       // Is the constant foldable in the shift of the addressing mode?
    7904             :       // I.e., shift amount is between 1 and 4 inclusive.
    7905         115 :       if (ShiftAmt == 0 || ShiftAmt > 4)
    7906          28 :         return false;
    7907          87 :       break;
    7908             :     }
    7909           0 :     case Instruction::Trunc:
    7910             :       // Check if this is a noop.
    7911             :       // trunc(sext ty1 to ty2) to ty1.
    7912           0 :       if (Instr->getType() == Ext->getOperand(0)->getType())
    7913           0 :         continue;
    7914             :       LLVM_FALLTHROUGH;
    7915             :     default:
    7916             :       return false;
    7917             :     }
    7918             : 
    7919             :     // At this point we can use the bfm family, so this extension is free
    7920             :     // for that use.
    7921             :   }
    7922             :   return true;
    7923             : }
    7924             : 
    7925         622 : bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
    7926             :                                           unsigned &RequiredAligment) const {
    7927        1244 :   if (!LoadedType.isSimple() ||
    7928         654 :       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
    7929             :     return false;
    7930             :   // Cyclone supports unaligned accesses.
    7931         622 :   RequiredAligment = 0;
    7932         622 :   unsigned NumBits = LoadedType.getSizeInBits();
    7933         622 :   return NumBits == 32 || NumBits == 64;
    7934             : }
    7935             : 
    7936             : /// A helper function for determining the number of interleaved accesses we
    7937             : /// will generate when lowering accesses of the given type.
    7938             : unsigned
    7939          46 : AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
    7940             :                                                  const DataLayout &DL) const {
    7941          46 :   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
    7942             : }
    7943             : 
    7944             : MachineMemOperand::Flags
    7945        8787 : AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
    7946        8795 :   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
    7947             :       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
    7948             :     return MOStridedAccess;
    7949             :   return MachineMemOperand::MONone;
    7950             : }
    7951             : 
    7952          57 : bool AArch64TargetLowering::isLegalInterleavedAccessType(
    7953             :     VectorType *VecTy, const DataLayout &DL) const {
    7954             : 
    7955          57 :   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
    7956          57 :   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
    7957             : 
    7958             :   // Ensure the number of vector elements is greater than 1.
    7959          57 :   if (VecTy->getNumElements() < 2)
    7960             :     return false;
    7961             : 
    7962             :   // Ensure the element type is legal.
    7963          49 :   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
    7964             :     return false;
    7965             : 
    7966             :   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
    7967             :   // 128 will be split into multiple interleaved accesses.
    7968          48 :   return VecSize == 64 || VecSize % 128 == 0;
    7969             : }
    7970             : 
    7971             : /// Lower an interleaved load into a ldN intrinsic.
    7972             : ///
    7973             : /// E.g. Lower an interleaved load (Factor = 2):
    7974             : ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
    7975             : ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
    7976             : ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
    7977             : ///
    7978             : ///      Into:
    7979             : ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
    7980             : ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
    7981             : ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
    7982          35 : bool AArch64TargetLowering::lowerInterleavedLoad(
    7983             :     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
    7984             :     ArrayRef<unsigned> Indices, unsigned Factor) const {
    7985             :   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
    7986             :          "Invalid interleave factor");
    7987             :   assert(!Shuffles.empty() && "Empty shufflevector input");
    7988             :   assert(Shuffles.size() == Indices.size() &&
    7989             :          "Unmatched number of shufflevectors and indices");
    7990             : 
    7991          70 :   const DataLayout &DL = LI->getModule()->getDataLayout();
    7992             : 
    7993          35 :   VectorType *VecTy = Shuffles[0]->getType();
    7994             : 
    7995             :   // Skip if we do not have NEON and skip illegal vector types. We can
    7996             :   // "legalize" wide vector types into multiple interleaved accesses as long as
    7997             :   // the vector types are divisible by 128.
    7998          35 :   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
    7999             :     return false;
    8000             : 
    8001          16 :   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
    8002             : 
    8003             :   // A pointer vector can not be the return type of the ldN intrinsics. Need to
    8004             :   // load integer vectors first and then convert to pointer vectors.
    8005          16 :   Type *EltTy = VecTy->getVectorElementType();
    8006          16 :   if (EltTy->isPointerTy())
    8007           4 :     VecTy =
    8008           4 :         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
    8009             : 
    8010          16 :   IRBuilder<> Builder(LI);
    8011             : 
    8012             :   // The base address of the load.
    8013             :   Value *BaseAddr = LI->getPointerOperand();
    8014             : 
    8015          16 :   if (NumLoads > 1) {
    8016             :     // If we're going to generate more than one load, reset the sub-vector type
    8017             :     // to something legal.
    8018          10 :     VecTy = VectorType::get(VecTy->getVectorElementType(),
    8019             :                             VecTy->getVectorNumElements() / NumLoads);
    8020             : 
    8021             :     // We will compute the pointer operand of each load from the original base
    8022             :     // address using GEPs. Cast the base address to a pointer to the scalar
    8023             :     // element type.
    8024           5 :     BaseAddr = Builder.CreateBitCast(
    8025          10 :         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
    8026             :                       LI->getPointerAddressSpace()));
    8027             :   }
    8028             : 
    8029          32 :   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
    8030          16 :   Type *Tys[2] = {VecTy, PtrTy};
    8031             :   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
    8032             :                                             Intrinsic::aarch64_neon_ld3,
    8033             :                                             Intrinsic::aarch64_neon_ld4};
    8034             :   Function *LdNFunc =
    8035          32 :       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
    8036             : 
    8037             :   // Holds sub-vectors extracted from the load intrinsic return values. The
    8038             :   // sub-vectors are associated with the shufflevector instructions they will
    8039             :   // replace.
    8040             :   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
    8041             : 
    8042          60 :   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
    8043             : 
    8044             :     // If we're generating more than one load, compute the base address of
    8045             :     // subsequent loads as an offset from the previous.
    8046          22 :     if (LoadCount > 0)
    8047          12 :       BaseAddr = Builder.CreateConstGEP1_32(
    8048             :           BaseAddr, VecTy->getVectorNumElements() * Factor);
    8049             : 
    8050          22 :     CallInst *LdN = Builder.CreateCall(
    8051          44 :         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
    8052             : 
    8053             :     // Extract and store the sub-vectors returned by the load intrinsic.
    8054         136 :     for (unsigned i = 0; i < Shuffles.size(); i++) {
    8055          57 :       ShuffleVectorInst *SVI = Shuffles[i];
    8056         114 :       unsigned Index = Indices[i];
    8057             : 
    8058          57 :       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
    8059             : 
    8060             :       // Convert the integer vector to pointer vector if the element is pointer.
    8061          57 :       if (EltTy->isPointerTy())
    8062          26 :         SubVec = Builder.CreateIntToPtr(
    8063          39 :             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
    8064             :                                     VecTy->getVectorNumElements()));
    8065          57 :       SubVecs[SVI].push_back(SubVec);
    8066             :     }
    8067             :   }
    8068             : 
    8069             :   // Replace uses of the shufflevector instructions with the sub-vectors
    8070             :   // returned by the load intrinsic. If a shufflevector instruction is
    8071             :   // associated with more than one sub-vector, those sub-vectors will be
    8072             :   // concatenated into a single wide vector.
    8073         100 :   for (ShuffleVectorInst *SVI : Shuffles) {
    8074             :     auto &SubVec = SubVecs[SVI];
    8075             :     auto *WideVec =
    8076          55 :         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
    8077          42 :     SVI->replaceAllUsesWith(WideVec);
    8078             :   }
    8079             : 
    8080             :   return true;
    8081             : }
    8082             : 
    8083             : /// Lower an interleaved store into a stN intrinsic.
    8084             : ///
    8085             : /// E.g. Lower an interleaved store (Factor = 3):
    8086             : ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
    8087             : ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
    8088             : ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
    8089             : ///
    8090             : ///      Into:
    8091             : ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
    8092             : ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
    8093             : ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
    8094             : ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
    8095             : ///
    8096             : /// Note that the new shufflevectors will be removed and we'll only generate one
    8097             : /// st3 instruction in CodeGen.
    8098             : ///
    8099             : /// Example for a more general valid mask (Factor 3). Lower:
    8100             : ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
    8101             : ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
    8102             : ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
    8103             : ///
    8104             : ///      Into:
    8105             : ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
    8106             : ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
    8107             : ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
    8108             : ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
    8109          49 : bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
    8110             :                                                   ShuffleVectorInst *SVI,
    8111             :                                                   unsigned Factor) const {
    8112             :   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
    8113             :          "Invalid interleave factor");
    8114             : 
    8115             :   VectorType *VecTy = SVI->getType();
    8116             :   assert(VecTy->getVectorNumElements() % Factor == 0 &&
    8117             :          "Invalid interleaved store");
    8118             : 
    8119          49 :   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
    8120          49 :   Type *EltTy = VecTy->getVectorElementType();
    8121          49 :   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
    8122             : 
    8123          98 :   const DataLayout &DL = SI->getModule()->getDataLayout();
    8124             : 
    8125             :   // Skip if we do not have NEON and skip illegal vector types. We can
    8126             :   // "legalize" wide vector types into multiple interleaved accesses as long as
    8127             :   // the vector types are divisible by 128.
    8128          49 :   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
    8129             :     return false;
    8130             : 
    8131          20 :   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
    8132             : 
    8133             :   Value *Op0 = SVI->getOperand(0);
    8134             :   Value *Op1 = SVI->getOperand(1);
    8135          20 :   IRBuilder<> Builder(SI);
    8136             : 
    8137             :   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
    8138             :   // vectors to integer vectors.
    8139          20 :   if (EltTy->isPointerTy()) {
    8140           3 :     Type *IntTy = DL.getIntPtrType(EltTy);
    8141           3 :     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
    8142             : 
    8143             :     // Convert to the corresponding integer vector.
    8144           3 :     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
    8145           3 :     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
    8146           3 :     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
    8147             : 
    8148           3 :     SubVecTy = VectorType::get(IntTy, LaneLen);
    8149             :   }
    8150             : 
    8151             :   // The base address of the store.
    8152             :   Value *BaseAddr = SI->getPointerOperand();
    8153             : 
    8154          20 :   if (NumStores > 1) {
    8155             :     // If we're going to generate more than one store, reset the lane length
    8156             :     // and sub-vector type to something legal.
    8157           3 :     LaneLen /= NumStores;
    8158           6 :     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
    8159             : 
    8160             :     // We will compute the pointer operand of each store from the original base
    8161             :     // address using GEPs. Cast the base address to a pointer to the scalar
    8162             :     // element type.
    8163           3 :     BaseAddr = Builder.CreateBitCast(
    8164           6 :         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
    8165             :                       SI->getPointerAddressSpace()));
    8166             :   }
    8167             : 
    8168             :   auto Mask = SVI->getShuffleMask();
    8169             : 
    8170          40 :   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
    8171          20 :   Type *Tys[2] = {SubVecTy, PtrTy};
    8172             :   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
    8173             :                                              Intrinsic::aarch64_neon_st3,
    8174             :                                              Intrinsic::aarch64_neon_st4};
    8175             :   Function *StNFunc =
    8176          40 :       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
    8177             : 
    8178          66 :   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
    8179             : 
    8180             :     SmallVector<Value *, 5> Ops;
    8181             : 
    8182             :     // Split the shufflevector operands into sub vectors for the new stN call.
    8183         171 :     for (unsigned i = 0; i < Factor; i++) {
    8184          74 :       unsigned IdxI = StoreCount * LaneLen * Factor + i;
    8185         148 :       if (Mask[IdxI] >= 0) {
    8186          65 :         Ops.push_back(Builder.CreateShuffleVector(
    8187          65 :             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
    8188             :       } else {
    8189             :         unsigned StartMask = 0;
    8190          23 :         for (unsigned j = 1; j < LaneLen; j++) {
    8191          13 :           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
    8192          26 :           if (Mask[IdxJ * Factor + IdxI] >= 0) {
    8193           6 :             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
    8194           6 :             break;
    8195             :           }
    8196             :         }
    8197             :         // Note: Filling undef gaps with random elements is ok, since
    8198             :         // those elements were being written anyway (with undefs).
    8199             :         // In the case of all undefs we're defaulting to using elems from 0
    8200             :         // Note: StartMask cannot be negative, it's checked in
    8201             :         // isReInterleaveMask
    8202           9 :         Ops.push_back(Builder.CreateShuffleVector(
    8203           9 :             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
    8204             :       }
    8205             :     }
    8206             : 
    8207             :     // If we generating more than one store, we compute the base address of
    8208             :     // subsequent stores as an offset from the previous.
    8209          23 :     if (StoreCount > 0)
    8210           6 :       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
    8211             : 
    8212          23 :     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
    8213          23 :     Builder.CreateCall(StNFunc, Ops);
    8214             :   }
    8215             :   return true;
    8216             : }
    8217             : 
    8218             : static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
    8219             :                        unsigned AlignCheck) {
    8220          67 :   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
    8221          22 :           (DstAlign == 0 || DstAlign % AlignCheck == 0));
    8222             : }
    8223             : 
    8224          64 : EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
    8225             :                                                unsigned SrcAlign, bool IsMemset,
    8226             :                                                bool ZeroMemset,
    8227             :                                                bool MemcpyStrSrc,
    8228             :                                                MachineFunction &MF) const {
    8229             :   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
    8230             :   // instruction to materialize the v2i64 zero and one store (with restrictive
    8231             :   // addressing mode). Just do two i64 store of zero-registers.
    8232             :   bool Fast;
    8233          64 :   const Function &F = MF.getFunction();
    8234         160 :   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
    8235          64 :       !F.hasFnAttribute(Attribute::NoImplicitFloat) &&
    8236          27 :       (memOpAlign(SrcAlign, DstAlign, 16) ||
    8237         113 :        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
    8238          30 :     return MVT::f128;
    8239             : 
    8240          34 :   if (Size >= 8 &&
    8241          18 :       (memOpAlign(SrcAlign, DstAlign, 8) ||
    8242          57 :        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
    8243          30 :     return MVT::i64;
    8244             : 
    8245           4 :   if (Size >= 4 &&
    8246           4 :       (memOpAlign(SrcAlign, DstAlign, 4) ||
    8247          12 :        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
    8248           2 :     return MVT::i32;
    8249             : 
    8250           2 :   return MVT::Other;
    8251             : }
    8252             : 
    8253             : // 12-bit optionally shifted immediates are legal for adds.
    8254        2390 : bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
    8255        2390 :   if (Immed == std::numeric_limits<int64_t>::min()) {
    8256             :     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
    8257             :                       << ": avoid UB for INT64_MIN\n");
    8258             :     return false;
    8259             :   }
    8260             :   // Same encoding for add/sub, just flip the sign.
    8261             :   Immed = std::abs(Immed);
    8262        2494 :   bool IsLegal = ((Immed >> 12) == 0 ||
    8263         122 :                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
    8264             :   LLVM_DEBUG(dbgs() << "Is " << Immed
    8265             :                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
    8266             :   return IsLegal;
    8267             : }
    8268             : 
    8269             : // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
    8270             : // immediates is the same as for an add or a sub.
    8271        2067 : bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
    8272        2067 :   return isLegalAddImmediate(Immed);
    8273             : }
    8274             : 
    8275             : /// isLegalAddressingMode - Return true if the addressing mode represented
    8276             : /// by AM is legal for this target, for a load/store of the specified type.
    8277       28656 : bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
    8278             :                                                   const AddrMode &AM, Type *Ty,
    8279             :                                                   unsigned AS, Instruction *I) const {
    8280             :   // AArch64 has five basic addressing modes:
    8281             :   //  reg
    8282             :   //  reg + 9-bit signed offset
    8283             :   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
    8284             :   //  reg1 + reg2
    8285             :   //  reg + SIZE_IN_BYTES * reg
    8286             : 
    8287             :   // No global is ever allowed as a base.
    8288       28656 :   if (AM.BaseGV)
    8289             :     return false;
    8290             : 
    8291             :   // No reg+reg+imm addressing.
    8292       25119 :   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
    8293             :     return false;
    8294             : 
    8295             :   // check reg + imm case:
    8296             :   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
    8297             :   uint64_t NumBytes = 0;
    8298       23126 :   if (Ty->isSized()) {
    8299       23096 :     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
    8300       23096 :     NumBytes = NumBits / 8;
    8301             :     if (!isPowerOf2_64(NumBits))
    8302             :       NumBytes = 0;
    8303             :   }
    8304             : 
    8305       23126 :   if (!AM.Scale) {
    8306       16878 :     int64_t Offset = AM.BaseOffs;
    8307             : 
    8308             :     // 9-bit signed offset
    8309       16878 :     if (isInt<9>(Offset))
    8310             :       return true;
    8311             : 
    8312             :     // 12-bit unsigned offset
    8313             :     unsigned shift = Log2_64(NumBytes);
    8314         802 :     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
    8315             :         // Must be a multiple of NumBytes (NumBytes is a power of 2)
    8316         350 :         (Offset >> shift) << shift == Offset)
    8317             :       return true;
    8318         109 :     return false;
    8319             :   }
    8320             : 
    8321             :   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
    8322             : 
    8323        6248 :   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
    8324             : }
    8325             : 
    8326          56 : bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
    8327             :   // Consider splitting large offset of struct or array.
    8328          56 :   return true;
    8329             : }
    8330             : 
    8331        1254 : int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
    8332             :                                                 const AddrMode &AM, Type *Ty,
    8333             :                                                 unsigned AS) const {
    8334             :   // Scaling factors are not free at all.
    8335             :   // Operands                     | Rt Latency
    8336             :   // -------------------------------------------
    8337             :   // Rt, [Xn, Xm]                 | 4
    8338             :   // -------------------------------------------
    8339             :   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
    8340             :   // Rt, [Xn, Wm, <extend> #imm]  |
    8341        1254 :   if (isLegalAddressingMode(DL, AM, Ty, AS))
    8342             :     // Scale represents reg2 * scale, thus account for 1 if
    8343             :     // it is not equal to 0 or 1.
    8344        1254 :     return AM.Scale != 0 && AM.Scale != 1;
    8345             :   return -1;
    8346             : }
    8347             : 
    8348        1813 : bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
    8349        1813 :   VT = VT.getScalarType();
    8350             : 
    8351        1813 :   if (!VT.isSimple())
    8352             :     return false;
    8353             : 
    8354        1813 :   switch (VT.getSimpleVT().SimpleTy) {
    8355             :   case MVT::f32:
    8356             :   case MVT::f64:
    8357             :     return true;
    8358             :   default:
    8359             :     break;
    8360             :   }
    8361             : 
    8362         195 :   return false;
    8363             : }
    8364             : 
    8365             : const MCPhysReg *
    8366          64 : AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
    8367             :   // LR is a callee-save register, but we must treat it as clobbered by any call
    8368             :   // site. Hence we include LR in the scratch registers, which are in turn added
    8369             :   // as implicit-defs for stackmaps and patchpoints.
    8370             :   static const MCPhysReg ScratchRegs[] = {
    8371             :     AArch64::X16, AArch64::X17, AArch64::LR, 0
    8372             :   };
    8373          64 :   return ScratchRegs;
    8374             : }
    8375             : 
    8376             : bool
    8377           2 : AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
    8378           2 :   EVT VT = N->getValueType(0);
    8379             :     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
    8380             :     // it with shift to let it be lowered to UBFX.
    8381           2 :   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
    8382           2 :       isa<ConstantSDNode>(N->getOperand(1))) {
    8383             :     uint64_t TruncMask = N->getConstantOperandVal(1);
    8384           2 :     if (isMask_64(TruncMask) &&
    8385           2 :       N->getOperand(0).getOpcode() == ISD::SRL &&
    8386           2 :       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
    8387             :       return false;
    8388             :   }
    8389             :   return true;
    8390             : }
    8391             : 
    8392           8 : bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
    8393             :                                                               Type *Ty) const {
    8394             :   assert(Ty->isIntegerTy());
    8395             : 
    8396           8 :   unsigned BitSize = Ty->getPrimitiveSizeInBits();
    8397           8 :   if (BitSize == 0)
    8398             :     return false;
    8399             : 
    8400             :   int64_t Val = Imm.getSExtValue();
    8401          15 :   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
    8402             :     return true;
    8403             : 
    8404           6 :   if ((int64_t)Val < 0)
    8405           0 :     Val = ~Val;
    8406           6 :   if (BitSize == 32)
    8407           2 :     Val &= (1LL << 32) - 1;
    8408             : 
    8409          12 :   unsigned LZ = countLeadingZeros((uint64_t)Val);
    8410           6 :   unsigned Shift = (63 - LZ) / 16;
    8411             :   // MOVZ is free so return true for one or fewer MOVK.
    8412           6 :   return Shift < 3;
    8413             : }
    8414             : 
    8415          14 : bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
    8416             :                                                     unsigned Index) const {
    8417          14 :   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
    8418             :     return false;
    8419             : 
    8420          12 :   return (Index == 0 || Index == ResVT.getVectorNumElements());
    8421             : }
    8422             : 
    8423             : /// Turn vector tests of the signbit in the form of:
    8424             : ///   xor (sra X, elt_size(X)-1), -1
    8425             : /// into:
    8426             : ///   cmge X, X, #0
    8427         971 : static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
    8428             :                                          const AArch64Subtarget *Subtarget) {
    8429        1942 :   EVT VT = N->getValueType(0);
    8430        1939 :   if (!Subtarget->hasNEON() || !VT.isVector())
    8431         415 :     return SDValue();
    8432             : 
    8433             :   // There must be a shift right algebraic before the xor, and the xor must be a
    8434             :   // 'not' operation.
    8435         556 :   SDValue Shift = N->getOperand(0);
    8436         556 :   SDValue Ones = N->getOperand(1);
    8437         574 :   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
    8438           7 :       !ISD::isBuildVectorAllOnes(Ones.getNode()))
    8439         549 :     return SDValue();
    8440             : 
    8441             :   // The shift should be smearing the sign bit across each vector element.
    8442             :   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
    8443           7 :   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
    8444          14 :   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
    8445           0 :     return SDValue();
    8446             : 
    8447          14 :   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
    8448             : }
    8449             : 
    8450             : // Generate SUBS and CSEL for integer abs.
    8451         964 : static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
    8452        1928 :   EVT VT = N->getValueType(0);
    8453             : 
    8454         964 :   SDValue N0 = N->getOperand(0);
    8455         964 :   SDValue N1 = N->getOperand(1);
    8456             :   SDLoc DL(N);
    8457             : 
    8458             :   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
    8459             :   // and change it to SUB and CSEL.
    8460        2892 :   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
    8461           7 :       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
    8462         964 :       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
    8463             :     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
    8464           6 :       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
    8465             :         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
    8466           3 :                                   N0.getOperand(0));
    8467             :         // Generate SUBS & CSEL.
    8468             :         SDValue Cmp =
    8469             :             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
    8470           6 :                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
    8471             :         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
    8472             :                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
    8473           9 :                            SDValue(Cmp.getNode(), 1));
    8474             :       }
    8475         961 :   return SDValue();
    8476             : }
    8477             : 
    8478        1774 : static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
    8479             :                                  TargetLowering::DAGCombinerInfo &DCI,
    8480             :                                  const AArch64Subtarget *Subtarget) {
    8481        3548 :   if (DCI.isBeforeLegalizeOps())
    8482         803 :     return SDValue();
    8483             : 
    8484         971 :   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
    8485           7 :     return Cmp;
    8486             : 
    8487         964 :   return performIntegerAbsCombine(N, DAG);
    8488             : }
    8489             : 
    8490             : SDValue
    8491          16 : AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
    8492             :                                      SelectionDAG &DAG,
    8493             :                                      std::vector<SDNode *> *Created) const {
    8494          16 :   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
    8495          32 :   if (isIntDivCheap(N->getValueType(0), Attr))
    8496           2 :     return SDValue(N,0); // Lower SDIV as SDIV
    8497             : 
    8498             :   // fold (sdiv X, pow2)
    8499          28 :   EVT VT = N->getValueType(0);
    8500          27 :   if ((VT != MVT::i32 && VT != MVT::i64) ||
    8501          45 :       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
    8502           1 :     return SDValue();
    8503             : 
    8504             :   SDLoc DL(N);
    8505          13 :   SDValue N0 = N->getOperand(0);
    8506          13 :   unsigned Lg2 = Divisor.countTrailingZeros();
    8507          13 :   SDValue Zero = DAG.getConstant(0, DL, VT);
    8508          13 :   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
    8509             : 
    8510             :   // Add (N0 < 0) ? Pow2 - 1 : 0;
    8511          13 :   SDValue CCVal;
    8512          13 :   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
    8513          13 :   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
    8514          13 :   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
    8515             : 
    8516          13 :   if (Created) {
    8517          26 :     Created->push_back(Cmp.getNode());
    8518          26 :     Created->push_back(Add.getNode());
    8519          26 :     Created->push_back(CSel.getNode());
    8520             :   }
    8521             : 
    8522             :   // Divide by pow2.
    8523             :   SDValue SRA =
    8524          13 :       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
    8525             : 
    8526             :   // If we're dividing by a positive value, we're done.  Otherwise, we must
    8527             :   // negate the result.
    8528          13 :   if (Divisor.isNonNegative())
    8529           9 :     return SRA;
    8530             : 
    8531           4 :   if (Created)
    8532           8 :     Created->push_back(SRA.getNode());
    8533           4 :   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
    8534             : }
    8535             : 
    8536        1200 : static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
    8537             :                                  TargetLowering::DAGCombinerInfo &DCI,
    8538             :                                  const AArch64Subtarget *Subtarget) {
    8539        2400 :   if (DCI.isBeforeLegalizeOps())
    8540         587 :     return SDValue();
    8541             : 
    8542             :   // The below optimizations require a constant RHS.
    8543         613 :   if (!isa<ConstantSDNode>(N->getOperand(1)))
    8544         480 :     return SDValue();
    8545             : 
    8546             :   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
    8547         133 :   const APInt &ConstValue = C->getAPIntValue();
    8548             : 
    8549             :   // Multiplication of a power of two plus/minus one can be done more
    8550             :   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
    8551             :   // future CPUs have a cheaper MADD instruction, this may need to be
    8552             :   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
    8553             :   // 64-bit is 5 cycles, so this is always a win.
    8554             :   // More aggressively, some multiplications N0 * C can be lowered to
    8555             :   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
    8556             :   // e.g. 6=3*2=(2+1)*2.
    8557             :   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
    8558             :   // which equals to (1+2)*16-(1+2).
    8559         133 :   SDValue N0 = N->getOperand(0);
    8560             :   // TrailingZeroes is used to test if the mul can be lowered to
    8561             :   // shift+add+shift.
    8562         133 :   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
    8563         133 :   if (TrailingZeroes) {
    8564             :     // Conservatively do not lower to shift+add+shift if the mul might be
    8565             :     // folded into smul or umul.
    8566          82 :     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
    8567             :                             isZeroExtended(N0.getNode(), DAG)))
    8568          12 :       return SDValue();
    8569             :     // Conservatively do not lower to shift+add+shift if the mul might be
    8570             :     // folded into madd or msub.
    8571         140 :     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
    8572             :                            N->use_begin()->getOpcode() == ISD::SUB))
    8573          59 :       return SDValue();
    8574             :   }
    8575             :   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
    8576             :   // and shift+add+shift.
    8577          62 :   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
    8578             : 
    8579             :   unsigned ShiftAmt, AddSubOpc;
    8580             :   // Is the shifted value the LHS operand of the add/sub?
    8581             :   bool ShiftValUseIsN0 = true;
    8582             :   // Do we need to negate the result?
    8583             :   bool NegateResult = false;
    8584             : 
    8585          62 :   if (ConstValue.isNonNegative()) {
    8586             :     // (mul x, 2^N + 1) => (add (shl x, N), x)
    8587             :     // (mul x, 2^N - 1) => (sub (shl x, N), x)
    8588             :     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
    8589          50 :     APInt SCVMinus1 = ShiftedConstValue - 1;
    8590          50 :     APInt CVPlus1 = ConstValue + 1;
    8591          50 :     if (SCVMinus1.isPowerOf2()) {
    8592             :       ShiftAmt = SCVMinus1.logBase2();
    8593             :       AddSubOpc = ISD::ADD;
    8594          39 :     } else if (CVPlus1.isPowerOf2()) {
    8595             :       ShiftAmt = CVPlus1.logBase2();
    8596             :       AddSubOpc = ISD::SUB;
    8597             :     } else
    8598          35 :       return SDValue();
    8599             :   } else {
    8600             :     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
    8601             :     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
    8602          24 :     APInt CVNegPlus1 = -ConstValue + 1;
    8603          24 :     APInt CVNegMinus1 = -ConstValue - 1;
    8604          12 :     if (CVNegPlus1.isPowerOf2()) {
    8605             :       ShiftAmt = CVNegPlus1.logBase2();
    8606             :       AddSubOpc = ISD::SUB;
    8607             :       ShiftValUseIsN0 = false;
    8608           9 :     } else if (CVNegMinus1.isPowerOf2()) {
    8609             :       ShiftAmt = CVNegMinus1.logBase2();
    8610             :       AddSubOpc = ISD::ADD;
    8611             :       NegateResult = true;
    8612             :     } else
    8613           7 :       return SDValue();
    8614             :   }
    8615             : 
    8616             :   SDLoc DL(N);
    8617          40 :   EVT VT = N->getValueType(0);
    8618             :   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
    8619          20 :                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
    8620             : 
    8621          20 :   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
    8622          20 :   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
    8623          20 :   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
    8624             :   assert(!(NegateResult && TrailingZeroes) &&
    8625             :          "NegateResult and TrailingZeroes cannot both be true for now.");
    8626             :   // Negate the result.
    8627          20 :   if (NegateResult)
    8628           2 :     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
    8629             :   // Shift the result.
    8630          18 :   if (TrailingZeroes)
    8631             :     return DAG.getNode(ISD::SHL, DL, VT, Res,
    8632           4 :                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
    8633          14 :   return Res;
    8634             : }
    8635             : 
    8636         749 : static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
    8637             :                                                          SelectionDAG &DAG) {
    8638             :   // Take advantage of vector comparisons producing 0 or -1 in each lane to
    8639             :   // optimize away operation when it's from a constant.
    8640             :   //
    8641             :   // The general transformation is:
    8642             :   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
    8643             :   //       AND(VECTOR_CMP(x,y), constant2)
    8644             :   //    constant2 = UNARYOP(constant)
    8645             : 
    8646             :   // Early exit if this isn't a vector operation, the operand of the
    8647             :   // unary operation isn't a bitwise AND, or if the sizes of the operations
    8648             :   // aren't the same.
    8649        1498 :   EVT VT = N->getValueType(0);
    8650         394 :   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
    8651         765 :       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
    8652         755 :       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
    8653         747 :     return SDValue();
    8654             : 
    8655             :   // Now check that the other operand of the AND is a constant. We could
    8656             :   // make the transformation for non-constant splats as well, but it's unclear
    8657             :   // that would be a benefit as it would not eliminate any operations, just
    8658             :   // perform one more step in scalar code before moving to the vector unit.
    8659             :   if (BuildVectorSDNode *BV =
    8660             :           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
    8661             :     // Bail out if the vector isn't a constant.
    8662           2 :     if (!BV->isConstant())
    8663           0 :       return SDValue();
    8664             : 
    8665             :     // Everything checks out. Build up the new and improved node.
    8666             :     SDLoc DL(N);
    8667           4 :     EVT IntVT = BV->getValueType(0);
    8668             :     // Create a new constant of the appropriate type for the transformed
    8669             :     // DAG.
    8670           4 :     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
    8671             :     // The AND node needs bitcasts to/from an integer vector type around it.
    8672           2 :     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
    8673             :     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
    8674           4 :                                  N->getOperand(0)->getOperand(0), MaskConst);
    8675           2 :     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
    8676           2 :     return Res;
    8677             :   }
    8678             : 
    8679           0 :   return SDValue();
    8680             : }
    8681             : 
    8682         749 : static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
    8683             :                                      const AArch64Subtarget *Subtarget) {
    8684             :   // First try to optimize away the conversion when it's conditionally from
    8685             :   // a constant. Vectors only.
    8686         749 :   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
    8687           2 :     return Res;
    8688             : 
    8689        1494 :   EVT VT = N->getValueType(0);
    8690             :   if (VT != MVT::f32 && VT != MVT::f64)
    8691         431 :     return SDValue();
    8692             : 
    8693             :   // Only optimize when the source and destination types have the same width.
    8694         632 :   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
    8695         186 :     return SDValue();
    8696             : 
    8697             :   // If the result of an integer load is only used by an integer-to-float
    8698             :   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
    8699             :   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
    8700         130 :   SDValue N0 = N->getOperand(0);
    8701         196 :   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
    8702             :       // Do not change the width of a volatile load.
    8703             :       !cast<LoadSDNode>(N0)->isVolatile()) {
    8704             :     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
    8705          33 :     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
    8706          33 :                                LN0->getPointerInfo(), LN0->getAlignment(),
    8707          99 :                                LN0->getMemOperand()->getFlags());
    8708             : 
    8709             :     // Make sure successors of the original load stay after it by updating them
    8710             :     // to use the new Chain.
    8711          66 :     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
    8712             : 
    8713             :     unsigned Opcode =
    8714          33 :         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
    8715          66 :     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
    8716             :   }
    8717             : 
    8718          97 :   return SDValue();
    8719             : }
    8720             : 
    8721             : /// Fold a floating-point multiply by power of two into floating-point to
    8722             : /// fixed-point conversion.
    8723         446 : static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
    8724             :                                      TargetLowering::DAGCombinerInfo &DCI,
    8725             :                                      const AArch64Subtarget *Subtarget) {
    8726         446 :   if (!Subtarget->hasNEON())
    8727           0 :     return SDValue();
    8728             : 
    8729         446 :   SDValue Op = N->getOperand(0);
    8730        1118 :   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
    8731             :       Op.getOpcode() != ISD::FMUL)
    8732         427 :     return SDValue();
    8733             : 
    8734          19 :   SDValue ConstVec = Op->getOperand(1);
    8735          19 :   if (!isa<BuildVectorSDNode>(ConstVec))
    8736           4 :     return SDValue();
    8737             : 
    8738          15 :   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
    8739          15 :   uint32_t FloatBits = FloatTy.getSizeInBits();
    8740          15 :   if (FloatBits != 32 && FloatBits != 64)
    8741           0 :     return SDValue();
    8742             : 
    8743          15 :   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
    8744          15 :   uint32_t IntBits = IntTy.getSizeInBits();
    8745          15 :   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
    8746           1 :     return SDValue();
    8747             : 
    8748             :   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
    8749          14 :   if (IntBits > FloatBits)
    8750           1 :     return SDValue();
    8751             : 
    8752             :   BitVector UndefElements;
    8753             :   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
    8754          13 :   int32_t Bits = IntBits == 64 ? 64 : 32;
    8755          13 :   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
    8756          13 :   if (C == -1 || C == 0 || C > Bits)
    8757           4 :     return SDValue();
    8758             : 
    8759             :   MVT ResTy;
    8760           9 :   unsigned NumLanes = Op.getValueType().getVectorNumElements();
    8761           9 :   switch (NumLanes) {
    8762           0 :   default:
    8763           0 :     return SDValue();
    8764           7 :   case 2:
    8765           7 :     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
    8766           7 :     break;
    8767           2 :   case 4:
    8768           2 :     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
    8769           2 :     break;
    8770             :   }
    8771             : 
    8772           9 :   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
    8773           0 :     return SDValue();
    8774             : 
    8775             :   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
    8776             :          "Illegal vector type after legalization");
    8777             : 
    8778             :   SDLoc DL(N);
    8779           9 :   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
    8780           9 :   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
    8781             :                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
    8782             :   SDValue FixConv =
    8783             :       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
    8784             :                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
    8785          27 :                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
    8786             :   // We can handle smaller integers by generating an extra trunc.
    8787           9 :   if (IntBits < FloatBits)
    8788           4 :     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
    8789             : 
    8790           9 :   return FixConv;
    8791             : }
    8792             : 
    8793             : /// Fold a floating-point divide by power of two into fixed-point to
    8794             : /// floating-point conversion.
    8795         189 : static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
    8796             :                                   TargetLowering::DAGCombinerInfo &DCI,
    8797             :                                   const AArch64Subtarget *Subtarget) {
    8798         189 :   if (!Subtarget->hasNEON())
    8799           0 :     return SDValue();
    8800             : 
    8801         189 :   SDValue Op = N->getOperand(0);
    8802         189 :   unsigned Opc = Op->getOpcode();
    8803         549 :   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
    8804         359 :       !Op.getOperand(0).getValueType().isSimple() ||
    8805          85 :       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
    8806         166 :     return SDValue();
    8807             : 
    8808          23 :   SDValue ConstVec = N->getOperand(1);
    8809          23 :   if (!isa<BuildVectorSDNode>(ConstVec))
    8810           2 :     return SDValue();
    8811             : 
    8812          21 :   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
    8813          21 :   int32_t IntBits = IntTy.getSizeInBits();
    8814          21 :   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
    8815           0 :     return SDValue();
    8816             : 
    8817          21 :   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
    8818          21 :   int32_t FloatBits = FloatTy.getSizeInBits();
    8819          21 :   if (FloatBits != 32 && FloatBits != 64)
    8820           0 :     return SDValue();
    8821             : 
    8822             :   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
    8823          21 :   if (IntBits > FloatBits)
    8824           1 :     return SDValue();
    8825             : 
    8826             :   BitVector UndefElements;
    8827             :   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
    8828          20 :   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
    8829          20 :   if (C == -1 || C == 0 || C > FloatBits)
    8830           2 :     return SDValue();
    8831             : 
    8832             :   MVT ResTy;
    8833          18 :   unsigned NumLanes = Op.getValueType().getVectorNumElements();
    8834          18 :   switch (NumLanes) {
    8835           0 :   default:
    8836           0 :     return SDValue();
    8837          14 :   case 2:
    8838          14 :     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
    8839          14 :     break;
    8840           4 :   case 4:
    8841           4 :     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
    8842           4 :     break;
    8843             :   }
    8844             : 
    8845          19 :   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
    8846           1 :     return SDValue();
    8847             : 
    8848             :   SDLoc DL(N);
    8849          17 :   SDValue ConvInput = Op.getOperand(0);
    8850             :   bool IsSigned = Opc == ISD::SINT_TO_FP;
    8851          17 :   if (IntBits < FloatBits)
    8852          10 :     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
    8853          20 :                             ResTy, ConvInput);
    8854             : 
    8855          17 :   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
    8856             :                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
    8857             :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
    8858             :                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
    8859          51 :                      DAG.getConstant(C, DL, MVT::i32));
    8860             : }
    8861             : 
    8862             : /// An EXTR instruction is made up of two shifts, ORed together. This helper
    8863             : /// searches for and classifies those shifts.
    8864         623 : static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
    8865             :                          bool &FromHi) {
    8866         623 :   if (N.getOpcode() == ISD::SHL)
    8867          75 :     FromHi = false;
    8868         548 :   else if (N.getOpcode() == ISD::SRL)
    8869          19 :     FromHi = true;
    8870             :   else
    8871             :     return false;
    8872             : 
    8873             :   if (!isa<ConstantSDNode>(N.getOperand(1)))
    8874             :     return false;
    8875             : 
    8876          90 :   ShiftAmount = N->getConstantOperandVal(1);
    8877          90 :   Src = N->getOperand(0);
    8878             :   return true;
    8879             : }
    8880             : 
    8881             : /// EXTR instruction extracts a contiguous chunk of bits from two existing
    8882             : /// registers viewed as a high/low pair. This function looks for the pattern:
    8883             : /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
    8884             : /// with an EXTR. Can't quite be done in TableGen because the two immediates
    8885             : /// aren't independent.
    8886        1069 : static SDValue tryCombineToEXTR(SDNode *N,
    8887             :                                 TargetLowering::DAGCombinerInfo &DCI) {
    8888        1069 :   SelectionDAG &DAG = DCI.DAG;
    8889             :   SDLoc DL(N);
    8890        2138 :   EVT VT = N->getValueType(0);
    8891             : 
    8892             :   assert(N->getOpcode() == ISD::OR && "Unexpected root");
    8893             : 
    8894             :   if (VT != MVT::i32 && VT != MVT::i64)
    8895         507 :     return SDValue();
    8896             : 
    8897         562 :   SDValue LHS;
    8898         562 :   uint32_t ShiftLHS = 0;
    8899         562 :   bool LHSFromHi = false;
    8900         562 :   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
    8901         501 :     return SDValue();
    8902             : 
    8903          61 :   SDValue RHS;
    8904          61 :   uint32_t ShiftRHS = 0;
    8905          61 :   bool RHSFromHi = false;
    8906          61 :   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
    8907          32 :     return SDValue();
    8908             : 
    8909             :   // If they're both trying to come from the high part of the register, they're
    8910             :   // not really an EXTR.
    8911          29 :   if (LHSFromHi == RHSFromHi)
    8912          16 :     return SDValue();
    8913             : 
    8914          13 :   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
    8915           4 :     return SDValue();
    8916             : 
    8917           9 :   if (LHSFromHi) {
    8918             :     std::swap(LHS, RHS);
    8919             :     std::swap(ShiftLHS, ShiftRHS);
    8920             :   }
    8921             : 
    8922             :   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
    8923           9 :                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
    8924             : }
    8925             : 
    8926        1060 : static SDValue tryCombineToBSL(SDNode *N,
    8927             :                                 TargetLowering::DAGCombinerInfo &DCI) {
    8928        2120 :   EVT VT = N->getValueType(0);
    8929        1060 :   SelectionDAG &DAG = DCI.DAG;
    8930             :   SDLoc DL(N);
    8931             : 
    8932        1060 :   if (!VT.isVector())
    8933         553 :     return SDValue();
    8934             : 
    8935         507 :   SDValue N0 = N->getOperand(0);
    8936         507 :   if (N0.getOpcode() != ISD::AND)
    8937         265 :     return SDValue();
    8938             : 
    8939         242 :   SDValue N1 = N->getOperand(1);
    8940         242 :   if (N1.getOpcode() != ISD::AND)
    8941          16 :     return SDValue();
    8942             : 
    8943             :   // We only have to look for constant vectors here since the general, variable
    8944             :   // case can be handled in TableGen.
    8945             :   unsigned Bits = VT.getScalarSizeInBits();
    8946         226 :   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
    8947        1098 :   for (int i = 1; i >= 0; --i)
    8948        2188 :     for (int j = 1; j >= 0; --j) {
    8949         880 :       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
    8950         880 :       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
    8951         880 :       if (!BVN0 || !BVN1)
    8952             :         continue;
    8953             : 
    8954             :       bool FoundMatch = true;
    8955         101 :       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
    8956          48 :         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
    8957          48 :         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
    8958          96 :         if (!CN0 || !CN1 ||
    8959         144 :             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
    8960             :           FoundMatch = false;
    8961             :           break;
    8962             :         }
    8963             :       }
    8964             : 
    8965          11 :       if (FoundMatch)
    8966             :         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
    8967          24 :                            N0->getOperand(1 - i), N1->getOperand(1 - j));
    8968             :     }
    8969             : 
    8970         218 :   return SDValue();
    8971             : }
    8972             : 
    8973        1139 : static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
    8974             :                                 const AArch64Subtarget *Subtarget) {
    8975             :   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
    8976        1139 :   SelectionDAG &DAG = DCI.DAG;
    8977        1139 :   EVT VT = N->getValueType(0);
    8978             : 
    8979        1139 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
    8980          70 :     return SDValue();
    8981             : 
    8982        1069 :   if (SDValue Res = tryCombineToEXTR(N, DCI))
    8983           9 :     return Res;
    8984             : 
    8985        1060 :   if (SDValue Res = tryCombineToBSL(N, DCI))
    8986           8 :     return Res;
    8987             : 
    8988        1052 :   return SDValue();
    8989             : }
    8990             : 
    8991         679 : static SDValue performSRLCombine(SDNode *N,
    8992             :                                  TargetLowering::DAGCombinerInfo &DCI) {
    8993         679 :   SelectionDAG &DAG = DCI.DAG;
    8994        1358 :   EVT VT = N->getValueType(0);
    8995             :   if (VT != MVT::i32 && VT != MVT::i64)
    8996         182 :     return SDValue();
    8997             : 
    8998             :   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
    8999             :   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
    9000             :   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
    9001         497 :   SDValue N0 = N->getOperand(0);
    9002         497 :   if (N0.getOpcode() == ISD::BSWAP) {
    9003             :     SDLoc DL(N);
    9004           2 :     SDValue N1 = N->getOperand(1);
    9005           2 :     SDValue N00 = N0.getOperand(0);
    9006             :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
    9007           2 :       uint64_t ShiftAmt = C->getZExtValue();
    9008           4 :       if (VT == MVT::i32 && ShiftAmt == 16 &&
    9009           4 :           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
    9010           1 :         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
    9011           3 :       if (VT == MVT::i64 && ShiftAmt == 32 &&
    9012           2 :           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
    9013           1 :         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
    9014             :     }
    9015             :   }
    9016         495 :   return SDValue();
    9017             : }
    9018             : 
    9019        9805 : static SDValue performBitcastCombine(SDNode *N,
    9020             :                                      TargetLowering::DAGCombinerInfo &DCI,
    9021             :                                      SelectionDAG &DAG) {
    9022             :   // Wait 'til after everything is legalized to try this. That way we have
    9023             :   // legal vector types and such.
    9024       19610 :   if (DCI.isBeforeLegalizeOps())
    9025        4578 :     return SDValue();
    9026             : 
    9027             :   // Remove extraneous bitcasts around an extract_subvector.
    9028             :   // For example,
    9029             :   //    (v4i16 (bitconvert
    9030             :   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
    9031             :   //  becomes
    9032             :   //    (extract_subvector ((v8i16 ...), (i64 4)))
    9033             : 
    9034             :   // Only interested in 64-bit vectors as the ultimate result.
    9035       10454 :   EVT VT = N->getValueType(0);
    9036        5227 :   if (!VT.isVector())
    9037         525 :     return SDValue();
    9038        4702 :   if (VT.getSimpleVT().getSizeInBits() != 64)
    9039        3039 :     return SDValue();
    9040             :   // Is the operand an extract_subvector starting at the beginning or halfway
    9041             :   // point of the vector? A low half may also come through as an
    9042             :   // EXTRACT_SUBREG, so look for that, too.
    9043        1663 :   SDValue Op0 = N->getOperand(0);
    9044        3326 :   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
    9045          37 :       !(Op0->isMachineOpcode() &&
    9046             :         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
    9047        1564 :     return SDValue();
    9048         198 :   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
    9049          99 :   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
    9050         124 :     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
    9051           0 :       return SDValue();
    9052          37 :   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
    9053          37 :     if (idx != AArch64::dsub)
    9054           0 :       return SDValue();
    9055             :     // The dsub reference is equivalent to a lane zero subvector reference.
    9056             :     idx = 0;
    9057             :   }
    9058             :   // Look through the bitcast of the input to the extract.
    9059          99 :   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
    9060          38 :     return SDValue();
    9061          61 :   SDValue Source = Op0->getOperand(0)->getOperand(0);
    9062             :   // If the source type has twice the number of elements as our destination
    9063             :   // type, we know this is an extract of the high or low half of the vector.
    9064         122 :   EVT SVT = Source->getValueType(0);
    9065         120 :   if (!SVT.isVector() ||
    9066          59 :       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
    9067           7 :     return SDValue();
    9068             : 
    9069             :   LLVM_DEBUG(
    9070             :       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
    9071             : 
    9072             :   // Create the simplified form to just extract the low or high half of the
    9073             :   // vector directly rather than bothering with the bitcasts.
    9074             :   SDLoc dl(N);
    9075          54 :   unsigned NumElements = VT.getVectorNumElements();
    9076          54 :   if (idx) {
    9077          52 :     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
    9078          52 :     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
    9079             :   } else {
    9080           2 :     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
    9081           2 :     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
    9082             :                                       Source, SubReg),
    9083           2 :                    0);
    9084             :   }
    9085             : }
    9086             : 
    9087         817 : static SDValue performConcatVectorsCombine(SDNode *N,
    9088             :                                            TargetLowering::DAGCombinerInfo &DCI,
    9089             :                                            SelectionDAG &DAG) {
    9090             :   SDLoc dl(N);
    9091        1634 :   EVT VT = N->getValueType(0);
    9092         817 :   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
    9093             : 
    9094             :   // Optimize concat_vectors of truncated vectors, where the intermediate
    9095             :   // type is illegal, to avoid said illegality,  e.g.,
    9096             :   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
    9097             :   //                          (v2i16 (truncate (v2i64)))))
    9098             :   // ->
    9099             :   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
    9100             :   //                                    (v4i32 (bitcast (v2i64))),
    9101             :   //                                    <0, 2, 4, 6>)))
    9102             :   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
    9103             :   // on both input and result type, so we might generate worse code.
    9104             :   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
    9105        1599 :   if (N->getNumOperands() == 2 &&
    9106         859 :       N0->getOpcode() == ISD::TRUNCATE &&
    9107          42 :       N1->getOpcode() == ISD::TRUNCATE) {
    9108          41 :     SDValue N00 = N0->getOperand(0);
    9109          41 :     SDValue N10 = N1->getOperand(0);
    9110          41 :     EVT N00VT = N00.getValueType();
    9111             : 
    9112             :     if (N00VT == N10.getValueType() &&
    9113          39 :         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
    9114          39 :         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
    9115             :       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
    9116           4 :       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
    9117          26 :       for (size_t i = 0; i < Mask.size(); ++i)
    9118          24 :         Mask[i] = i * 2;
    9119             :       return DAG.getNode(ISD::TRUNCATE, dl, VT,
    9120             :                          DAG.getVectorShuffle(
    9121             :                              MidVT, dl,
    9122             :                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
    9123           6 :                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
    9124             :     }
    9125             :   }
    9126             : 
    9127             :   // Wait 'til after everything is legalized to try this. That way we have
    9128             :   // legal vector types and such.
    9129        1630 :   if (DCI.isBeforeLegalizeOps())
    9130         439 :     return SDValue();
    9131             : 
    9132             :   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
    9133             :   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
    9134             :   // canonicalise to that.
    9135          25 :   if (N0 == N1 && VT.getVectorNumElements() == 2) {
    9136             :     assert(VT.getScalarSizeInBits() == 64);
    9137             :     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
    9138          13 :                        DAG.getConstant(0, dl, MVT::i64));
    9139             :   }
    9140             : 
    9141             :   // Canonicalise concat_vectors so that the right-hand vector has as few
    9142             :   // bit-casts as possible before its real operation. The primary matching
    9143             :   // destination for these operations will be the narrowing "2" instructions,
    9144             :   // which depend on the operation being performed on this right-hand vector.
    9145             :   // For example,
    9146             :   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
    9147             :   // becomes
    9148             :   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
    9149             : 
    9150         363 :   if (N1->getOpcode() != ISD::BITCAST)
    9151         302 :     return SDValue();
    9152          61 :   SDValue RHS = N1->getOperand(0);
    9153          61 :   MVT RHSTy = RHS.getValueType().getSimpleVT();
    9154             :   // If the RHS is not a vector, this is not the pattern we're looking for.
    9155          61 :   if (!RHSTy.isVector())
    9156           0 :     return SDValue();
    9157             : 
    9158             :   LLVM_DEBUG(
    9159             :       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
    9160             : 
    9161             :   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
    9162          61 :                                   RHSTy.getVectorNumElements() * 2);
    9163             :   return DAG.getNode(ISD::BITCAST, dl, VT,
    9164             :                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
    9165             :                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
    9166         122 :                                  RHS));
    9167             : }
    9168             : 
    9169          89 : static SDValue tryCombineFixedPointConvert(SDNode *N,
    9170             :                                            TargetLowering::DAGCombinerInfo &DCI,
    9171             :                                            SelectionDAG &DAG) {
    9172             :   // Wait until after everything is legalized to try this. That way we have
    9173             :   // legal vector types and such.
    9174         178 :   if (DCI.isBeforeLegalizeOps())
    9175          46 :     return SDValue();
    9176             :   // Transform a scalar conversion of a value from a lane extract into a
    9177             :   // lane extract of a vector conversion. E.g., from foo1 to foo2:
    9178             :   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
    9179             :   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
    9180             :   //
    9181             :   // The second form interacts better with instruction selection and the
    9182             :   // register allocator to avoid cross-class register copies that aren't
    9183             :   // coalescable due to a lane reference.
    9184             : 
    9185             :   // Check the operand and see if it originates from a lane extract.
    9186          43 :   SDValue Op1 = N->getOperand(1);
    9187          43 :   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
    9188             :     // Yep, no additional predication needed. Perform the transform.
    9189           1 :     SDValue IID = N->getOperand(0);
    9190           1 :     SDValue Shift = N->getOperand(2);
    9191           1 :     SDValue Vec = Op1.getOperand(0);
    9192           1 :     SDValue Lane = Op1.getOperand(1);
    9193           2 :     EVT ResTy = N->getValueType(0);
    9194           1 :     EVT VecResTy;
    9195             :     SDLoc DL(N);
    9196             : 
    9197             :     // The vector width should be 128 bits by the time we get here, even
    9198             :     // if it started as 64 bits (the extract_vector handling will have
    9199             :     // done so).
    9200             :     assert(Vec.getValueSizeInBits() == 128 &&
    9201             :            "unexpected vector size on extract_vector_elt!");
    9202             :     if (Vec.getValueType() == MVT::v4i32)
    9203           0 :       VecResTy = MVT::v4f32;
    9204             :     else if (Vec.getValueType() == MVT::v2i64)
    9205           1 :       VecResTy = MVT::v2f64;
    9206             :     else
    9207           0 :       llvm_unreachable("unexpected vector type!");
    9208             : 
    9209             :     SDValue Convert =
    9210           1 :         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
    9211           1 :     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
    9212             :   }
    9213          42 :   return SDValue();
    9214             : }
    9215             : 
    9216             : // AArch64 high-vector "long" operations are formed by performing the non-high
    9217             : // version on an extract_subvector of each operand which gets the high half:
    9218             : //
    9219             : //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
    9220             : //
    9221             : // However, there are cases which don't have an extract_high explicitly, but
    9222             : // have another operation that can be made compatible with one for free. For
    9223             : // example:
    9224             : //
    9225             : //  (dupv64 scalar) --> (extract_high (dup128 scalar))
    9226             : //
    9227             : // This routine does the actual conversion of such DUPs, once outer routines
    9228             : // have determined that everything else is in order.
    9229             : // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
    9230             : // similarly here.
    9231         644 : static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
    9232             :   switch (N.getOpcode()) {
    9233             :   case AArch64ISD::DUP:
    9234             :   case AArch64ISD::DUPLANE8:
    9235             :   case AArch64ISD::DUPLANE16:
    9236             :   case AArch64ISD::DUPLANE32:
    9237             :   case AArch64ISD::DUPLANE64:
    9238             :   case AArch64ISD::MOVI:
    9239             :   case AArch64ISD::MOVIshift:
    9240             :   case AArch64ISD::MOVIedit:
    9241             :   case AArch64ISD::MOVImsl:
    9242             :   case AArch64ISD::MVNIshift:
    9243             :   case AArch64ISD::MVNImsl:
    9244             :     break;
    9245         396 :   default:
    9246             :     // FMOV could be supported, but isn't very useful, as it would only occur
    9247             :     // if you passed a bitcast' floating point immediate to an eligible long
    9248             :     // integer op (addl, smull, ...).
    9249         396 :     return SDValue();
    9250             :   }
    9251             : 
    9252         248 :   MVT NarrowTy = N.getSimpleValueType();
    9253         248 :   if (!NarrowTy.is64BitVector())
    9254           0 :     return SDValue();
    9255             : 
    9256         248 :   MVT ElementTy = NarrowTy.getVectorElementType();
    9257         248 :   unsigned NumElems = NarrowTy.getVectorNumElements();
    9258         248 :   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
    9259             : 
    9260             :   SDLoc dl(N);
    9261             :   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
    9262             :                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
    9263         992 :                      DAG.getConstant(NumElems, dl, MVT::i64));
    9264             : }
    9265             : 
    9266             : static bool isEssentiallyExtractSubvector(SDValue N) {
    9267        1364 :   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
    9268             :     return true;
    9269             : 
    9270         830 :   return N.getOpcode() == ISD::BITCAST &&
    9271          56 :          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
    9272             : }
    9273             : 
    9274             : /// Helper structure to keep track of ISD::SET_CC operands.
    9275             : struct GenericSetCCInfo {
    9276             :   const SDValue *Opnd0;
    9277             :   const SDValue *Opnd1;
    9278             :   ISD::CondCode CC;
    9279             : };
    9280             : 
    9281             : /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
    9282             : struct AArch64SetCCInfo {
    9283             :   const SDValue *Cmp;
    9284             :   AArch64CC::CondCode CC;
    9285             : };
    9286             : 
    9287             : /// Helper structure to keep track of SetCC information.
    9288             : union SetCCInfo {
    9289             :   GenericSetCCInfo Generic;
    9290             :   AArch64SetCCInfo AArch64;
    9291             : };
    9292             : 
    9293             : /// Helper structure to be able to read SetCC information.  If set to
    9294             : /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
    9295             : /// GenericSetCCInfo.
    9296             : struct SetCCInfoAndKind {
    9297             :   SetCCInfo Info;
    9298             :   bool IsAArch64;
    9299             : };
    9300             : 
    9301             : /// Check whether or not \p Op is a SET_CC operation, either a generic or
    9302             : /// an
    9303             : /// AArch64 lowered one.
    9304             : /// \p SetCCInfo is filled accordingly.
    9305             : /// \post SetCCInfo is meanginfull only when this function returns true.
    9306             : /// \return True when Op is a kind of SET_CC operation.
    9307       10019 : static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
    9308             :   // If this is a setcc, this is straight forward.
    9309       10019 :   if (Op.getOpcode() == ISD::SETCC) {
    9310           0 :     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
    9311           0 :     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
    9312           0 :     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    9313           0 :     SetCCInfo.IsAArch64 = false;
    9314             :     return true;
    9315             :   }
    9316             :   // Otherwise, check if this is a matching csel instruction.
    9317             :   // In other words:
    9318             :   // - csel 1, 0, cc
    9319             :   // - csel 0, 1, !cc
    9320       10019 :   if (Op.getOpcode() != AArch64ISD::CSEL)
    9321             :     return false;
    9322             :   // Set the information about the operands.
    9323             :   // TODO: we want the operands of the Cmp not the csel
    9324          10 :   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
    9325          10 :   SetCCInfo.IsAArch64 = true;
    9326          10 :   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
    9327          10 :       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
    9328             : 
    9329             :   // Check that the operands matches the constraints:
    9330             :   // (1) Both operands must be constants.
    9331             :   // (2) One must be 1 and the other must be 0.
    9332             :   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
    9333             :   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    9334             : 
    9335             :   // Check (1).
    9336          10 :   if (!TValue || !FValue)
    9337             :     return false;
    9338             : 
    9339             :   // Check (2).
    9340           8 :   if (!TValue->isOne()) {
    9341             :     // Update the comparison when we are interested in !cc.
    9342             :     std::swap(TValue, FValue);
    9343           4 :     SetCCInfo.Info.AArch64.CC =
    9344             :         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
    9345             :   }
    9346          12 :   return TValue->isOne() && FValue->isNullValue();
    9347             : }
    9348             : 
    9349             : // Returns true if Op is setcc or zext of setcc.
    9350        9982 : static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
    9351        9982 :   if (isSetCC(Op, Info))
    9352             :     return true;
    9353       19997 :   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
    9354          37 :     isSetCC(Op->getOperand(0), Info));
    9355             : }
    9356             : 
    9357             : // The folding we want to perform is:
    9358             : // (add x, [zext] (setcc cc ...) )
    9359             : //   -->
    9360             : // (csel x, (add x, 1), !cc ...)
    9361             : //
    9362             : // The latter will get matched to a CSINC instruction.
    9363        4992 : static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
    9364             :   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
    9365        4992 :   SDValue LHS = Op->getOperand(0);
    9366        4992 :   SDValue RHS = Op->getOperand(1);
    9367             :   SetCCInfoAndKind InfoAndKind;
    9368             : 
    9369             :   // If neither operand is a SET_CC, give up.
    9370        4992 :   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
    9371             :     std::swap(LHS, RHS);
    9372        4990 :     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
    9373        4988 :       return SDValue();
    9374             :   }
    9375             : 
    9376             :   // FIXME: This could be generatized to work for FP comparisons.
    9377           4 :   EVT CmpVT = InfoAndKind.IsAArch64
    9378           4 :                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
    9379           8 :                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
    9380             :   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
    9381           0 :     return SDValue();
    9382             : 
    9383           4 :   SDValue CCVal;
    9384           4 :   SDValue Cmp;
    9385             :   SDLoc dl(Op);
    9386           4 :   if (InfoAndKind.IsAArch64) {
    9387           4 :     CCVal = DAG.getConstant(
    9388           4 :         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
    9389           8 :         MVT::i32);
    9390           4 :     Cmp = *InfoAndKind.Info.AArch64.Cmp;
    9391             :   } else
    9392           0 :     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
    9393           0 :                       *InfoAndKind.Info.Generic.Opnd1,
    9394             :                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
    9395           0 :                       CCVal, DAG, dl);
    9396             : 
    9397           8 :   EVT VT = Op->getValueType(0);
    9398           4 :   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
    9399           4 :   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
    9400             : }
    9401             : 
    9402             : // The basic add/sub long vector instructions have variants with "2" on the end
    9403             : // which act on the high-half of their inputs. They are normally matched by
    9404             : // patterns like:
    9405             : //
    9406             : // (add (zeroext (extract_high LHS)),
    9407             : //      (zeroext (extract_high RHS)))
    9408             : // -> uaddl2 vD, vN, vM
    9409             : //
    9410             : // However, if one of the extracts is something like a duplicate, this
    9411             : // instruction can still be used profitably. This function puts the DAG into a
    9412             : // more appropriate form for those patterns to trigger.
    9413       14490 : static SDValue performAddSubLongCombine(SDNode *N,
    9414             :                                         TargetLowering::DAGCombinerInfo &DCI,
    9415             :                                         SelectionDAG &DAG) {
    9416       28980 :   if (DCI.isBeforeLegalizeOps())
    9417        7707 :     return SDValue();
    9418             : 
    9419        6783 :   MVT VT = N->getSimpleValueType(0);
    9420        6783 :   if (!VT.is128BitVector()) {
    9421        5572 :     if (N->getOpcode() == ISD::ADD)
    9422        4992 :       return performSetccAddFolding(N, DAG);
    9423         580 :     return SDValue();
    9424             :   }
    9425             : 
    9426             :   // Make sure both branches are extended in the same way.
    9427        1211 :   SDValue LHS = N->getOperand(0);
    9428        1211 :   SDValue RHS = N->getOperand(1);
    9429        1133 :   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
    9430        1342 :        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
    9431             :       LHS.getOpcode() != RHS.getOpcode())
    9432        1106 :     return SDValue();
    9433             : 
    9434             :   unsigned ExtType = LHS.getOpcode();
    9435             : 
    9436             :   // It's not worth doing if at least one of the inputs isn't already an
    9437             :   // extract, but we don't know which it'll be so we have to try both.
    9438         105 :   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
    9439          58 :     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
    9440          58 :     if (!RHS.getNode())
    9441          56 :       return SDValue();
    9442             : 
    9443           4 :     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
    9444          47 :   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
    9445           2 :     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
    9446           2 :     if (!LHS.getNode())
    9447           0 :       return SDValue();
    9448             : 
    9449           4 :     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
    9450             :   }
    9451             : 
    9452         147 :   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
    9453             : }
    9454             : 
    9455             : // Massage DAGs which we can use the high-half "long" operations on into
    9456             : // something isel will recognize better. E.g.
    9457             : //
    9458             : // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
    9459             : //   (aarch64_neon_umull (extract_high (v2i64 vec)))
    9460             : //                     (extract_high (v2i64 (dup128 scalar)))))
    9461             : //
    9462        1530 : static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
    9463             :                                        TargetLowering::DAGCombinerInfo &DCI,
    9464             :                                        SelectionDAG &DAG) {
    9465        3060 :   if (DCI.isBeforeLegalizeOps())
    9466         632 :     return SDValue();
    9467             : 
    9468         898 :   SDValue LHS = N->getOperand(1);
    9469         898 :   SDValue RHS = N->getOperand(2);
    9470             :   assert(LHS.getValueType().is64BitVector() &&
    9471             :          RHS.getValueType().is64BitVector() &&
    9472             :          "unexpected shape for long operation");
    9473             : 
    9474             :   // Either node could be a DUP, but it's not worth doing both of them (you'd
    9475             :   // just as well use the non-high version) so look for a corresponding extract
    9476             :   // operation on the other "wing".
    9477             :   if (isEssentiallyExtractSubvector(LHS)) {
    9478         584 :     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
    9479         584 :     if (!RHS.getNode())
    9480         340 :       return SDValue();
    9481             :   } else if (isEssentiallyExtractSubvector(RHS)) {
    9482           0 :     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
    9483           0 :     if (!LHS.getNode())
    9484           0 :       return SDValue();
    9485             :   }
    9486             : 
    9487         558 :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
    9488        2232 :                      N->getOperand(0), LHS, RHS);
    9489             : }
    9490             : 
    9491         110 : static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
    9492         220 :   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
    9493         110 :   unsigned ElemBits = ElemTy.getSizeInBits();
    9494             : 
    9495             :   int64_t ShiftAmount;
    9496         110 :   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
    9497             :     APInt SplatValue, SplatUndef;
    9498             :     unsigned SplatBitSize;
    9499             :     bool HasAnyUndefs;
    9500          51 :     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
    9501         102 :                               HasAnyUndefs, ElemBits) ||
    9502          51 :         SplatBitSize != ElemBits)
    9503           0 :       return SDValue();
    9504             : 
    9505             :     ShiftAmount = SplatValue.getSExtValue();
    9506             :   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
    9507           2 :     ShiftAmount = CVN->getSExtValue();
    9508             :   } else
    9509          57 :     return SDValue();
    9510             : 
    9511             :   unsigned Opcode;
    9512             :   bool IsRightShift;
    9513          53 :   switch (IID) {
    9514           0 :   default:
    9515           0 :     llvm_unreachable("Unknown shift intrinsic");
    9516             :   case Intrinsic::aarch64_neon_sqshl:
    9517             :     Opcode = AArch64ISD::SQSHL_I;
    9518             :     IsRightShift = false;
    9519             :     break;
    9520          10 :   case Intrinsic::aarch64_neon_uqshl:
    9521             :     Opcode = AArch64ISD::UQSHL_I;
    9522             :     IsRightShift = false;
    9523          10 :     break;
    9524          14 :   case Intrinsic::aarch64_neon_srshl:
    9525             :     Opcode = AArch64ISD::SRSHR_I;
    9526             :     IsRightShift = true;
    9527          14 :     break;
    9528          14 :   case Intrinsic::aarch64_neon_urshl:
    9529             :     Opcode = AArch64ISD::URSHR_I;
    9530             :     IsRightShift = true;
    9531          14 :     break;
    9532           7 :   case Intrinsic::aarch64_neon_sqshlu:
    9533             :     Opcode = AArch64ISD::SQSHLU_I;
    9534             :     IsRightShift = false;
    9535           7 :     break;
    9536             :   }
    9537             : 
    9538          53 :   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
    9539             :     SDLoc dl(N);
    9540          28 :     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
    9541          84 :                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
    9542          25 :   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
    9543             :     SDLoc dl(N);
    9544          23 :     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
    9545          69 :                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
    9546             :   }
    9547             : 
    9548           2 :   return SDValue();
    9549             : }
    9550             : 
    9551             : // The CRC32[BH] instructions ignore the high bits of their data operand. Since
    9552             : // the intrinsics must be legal and take an i32, this means there's almost
    9553             : // certainly going to be a zext in the DAG which we can eliminate.
    9554          32 : static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
    9555          32 :   SDValue AndN = N->getOperand(2);
    9556          32 :   if (AndN.getOpcode() != ISD::AND)
    9557          24 :     return SDValue();
    9558             : 
    9559             :   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
    9560          16 :   if (!CMask || CMask->getZExtValue() != Mask)
    9561           0 :     return SDValue();
    9562             : 
    9563           8 :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
    9564          16 :                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
    9565             : }
    9566             : 
    9567         115 : static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
    9568             :                                            SelectionDAG &DAG) {
    9569             :   SDLoc dl(N);
    9570             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
    9571             :                      DAG.getNode(Opc, dl,
    9572             :                                  N->getOperand(1).getSimpleValueType(),
    9573         115 :                                  N->getOperand(1)),
    9574         460 :                      DAG.getConstant(0, dl, MVT::i64));
    9575             : }
    9576             : 
    9577        6234 : static SDValue performIntrinsicCombine(SDNode *N,
    9578             :                                        TargetLowering::DAGCombinerInfo &DCI,
    9579             :                                        const AArch64Subtarget *Subtarget) {
    9580        6234 :   SelectionDAG &DAG = DCI.DAG;
    9581             :   unsigned IID = getIntrinsicID(N);
    9582        6234 :   switch (IID) {
    9583             :   default:
    9584             :     break;
    9585          89 :   case Intrinsic::aarch64_neon_vcvtfxs2fp:
    9586             :   case Intrinsic::aarch64_neon_vcvtfxu2fp:
    9587          89 :     return tryCombineFixedPointConvert(N, DCI, DAG);
    9588          25 :   case Intrinsic::aarch64_neon_saddv:
    9589          25 :     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
    9590          17 :   case Intrinsic::aarch64_neon_uaddv:
    9591          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
    9592          17 :   case Intrinsic::aarch64_neon_sminv:
    9593          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
    9594          20 :   case Intrinsic::aarch64_neon_uminv:
    9595          20 :     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
    9596          17 :   case Intrinsic::aarch64_neon_smaxv:
    9597          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
    9598          19 :   case Intrinsic::aarch64_neon_umaxv:
    9599          19 :     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
    9600             :   case Intrinsic::aarch64_neon_fmax:
    9601          11 :     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
    9602          33 :                        N->getOperand(1), N->getOperand(2));
    9603             :   case Intrinsic::aarch64_neon_fmin:
    9604          11 :     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
    9605          33 :                        N->getOperand(1), N->getOperand(2));
    9606             :   case Intrinsic::aarch64_neon_fmaxnm:
    9607           5 :     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
    9608          15 :                        N->getOperand(1), N->getOperand(2));
    9609             :   case Intrinsic::aarch64_neon_fminnm:
    9610           5 :     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
    9611          15 :                        N->getOperand(1), N->getOperand(2));
    9612        1478 :   case Intrinsic::aarch64_neon_smull:
    9613             :   case Intrinsic::aarch64_neon_umull:
    9614             :   case Intrinsic::aarch64_neon_pmull:
    9615             :   case Intrinsic::aarch64_neon_sqdmull:
    9616        1478 :     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
    9617         110 :   case Intrinsic::aarch64_neon_sqshl:
    9618             :   case Intrinsic::aarch64_neon_uqshl:
    9619             :   case Intrinsic::aarch64_neon_sqshlu:
    9620             :   case Intrinsic::aarch64_neon_srshl:
    9621             :   case Intrinsic::aarch64_neon_urshl:
    9622         110 :     return tryCombineShiftImm(IID, N, DAG);
    9623          16 :   case Intrinsic::aarch64_crc32b:
    9624             :   case Intrinsic::aarch64_crc32cb:
    9625          16 :     return tryCombineCRC32(0xff, N, DAG);
    9626          16 :   case Intrinsic::aarch64_crc32h:
    9627             :   case Intrinsic::aarch64_crc32ch:
    9628          16 :     return tryCombineCRC32(0xffff, N, DAG);
    9629             :   }
    9630        4378 :   return SDValue();
    9631             : }
    9632             : 
    9633        3533 : static SDValue performExtendCombine(SDNode *N,
    9634             :                                     TargetLowering::DAGCombinerInfo &DCI,
    9635             :                                     SelectionDAG &DAG) {
    9636             :   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
    9637             :   // we can convert that DUP into another extract_high (of a bigger DUP), which
    9638             :   // helps the backend to decide that an sabdl2 would be useful, saving a real
    9639             :   // extract_high operation.
    9640        7634 :   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
    9641         568 :       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
    9642             :     SDNode *ABDNode = N->getOperand(0).getNode();
    9643             :     unsigned IID = getIntrinsicID(ABDNode);
    9644         112 :     if (IID == Intrinsic::aarch64_neon_sabd ||
    9645          56 :         IID == Intrinsic::aarch64_neon_uabd) {
    9646          52 :       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
    9647          52 :       if (!NewABD.getNode())
    9648          14 :         return SDValue();
    9649             : 
    9650          38 :       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
    9651         114 :                          NewABD);
    9652             :     }
    9653             :   }
    9654             : 
    9655             :   // This is effectively a custom type legalization for AArch64.
    9656             :   //
    9657             :   // Type legalization will split an extend of a small, legal, type to a larger
    9658             :   // illegal type by first splitting the destination type, often creating
    9659             :   // illegal source types, which then get legalized in isel-confusing ways,
    9660             :   // leading to really terrible codegen. E.g.,
    9661             :   //   %result = v8i32 sext v8i8 %value
    9662             :   // becomes
    9663             :   //   %losrc = extract_subreg %value, ...
    9664             :   //   %hisrc = extract_subreg %value, ...
    9665             :   //   %lo = v4i32 sext v4i8 %losrc
    9666             :   //   %hi = v4i32 sext v4i8 %hisrc
    9667             :   // Things go rapidly downhill from there.
    9668             :   //
    9669             :   // For AArch64, the [sz]ext vector instructions can only go up one element
    9670             :   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
    9671             :   // take two instructions.
    9672             :   //
    9673             :   // This implies that the most efficient way to do the extend from v8i8
    9674             :   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
    9675             :   // the normal splitting to happen for the v8i16->v8i32.
    9676             : 
    9677             :   // This is pre-legalization to catch some cases where the default
    9678             :   // type legalization will create ill-tempered code.
    9679        3481 :   if (!DCI.isBeforeLegalizeOps())
    9680        1041 :     return SDValue();
    9681             : 
    9682             :   // We're only interested in cleaning things up for non-legal vector types
    9683             :   // here. If both the source and destination are legal, things will just
    9684             :   // work naturally without any fiddling.
    9685        2440 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9686        4880 :   EVT ResVT = N->getValueType(0);
    9687        2440 :   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
    9688        2382 :     return SDValue();
    9689             :   // If the vector type isn't a simple VT, it's beyond the scope of what
    9690             :   // we're  worried about here. Let legalization do its thing and hope for
    9691             :   // the best.
    9692          58 :   SDValue Src = N->getOperand(0);
    9693         116 :   EVT SrcVT = Src->getValueType(0);
    9694         115 :   if (!ResVT.isSimple() || !SrcVT.isSimple())
    9695           1 :     return SDValue();
    9696             : 
    9697             :   // If the source VT is a 64-bit vector, we can play games and get the
    9698             :   // better results we want.
    9699          57 :   if (SrcVT.getSizeInBits() != 64)
    9700          50 :     return SDValue();
    9701             : 
    9702             :   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
    9703           7 :   unsigned ElementCount = SrcVT.getVectorNumElements();
    9704           7 :   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
    9705             :   SDLoc DL(N);
    9706          14 :   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
    9707             : 
    9708             :   // Now split the rest of the operation into two halves, each with a 64
    9709             :   // bit source.
    9710           7 :   EVT LoVT, HiVT;
    9711             :   SDValue Lo, Hi;
    9712           7 :   unsigned NumElements = ResVT.getVectorNumElements();
    9713             :   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
    9714           7 :   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
    9715           7 :                                  ResVT.getVectorElementType(), NumElements / 2);
    9716             : 
    9717           7 :   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
    9718          14 :                                LoVT.getVectorNumElements());
    9719           7 :   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
    9720          14 :                    DAG.getConstant(0, DL, MVT::i64));
    9721           7 :   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
    9722          14 :                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
    9723          14 :   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
    9724          14 :   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
    9725             : 
    9726             :   // Now combine the parts back together so we still have a single result
    9727             :   // like the combiner expects.
    9728           7 :   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
    9729             : }
    9730             : 
    9731          40 : static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
    9732             :                                SDValue SplatVal, unsigned NumVecElts) {
    9733          40 :   unsigned OrigAlignment = St.getAlignment();
    9734          80 :   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
    9735             : 
    9736             :   // Create scalar stores. This is at least as good as the code sequence for a
    9737             :   // split unaligned store which is a dup.s, ext.b, and two stores.
    9738             :   // Most of the time the three stores should be replaced by store pair
    9739             :   // instructions (stp).
    9740             :   SDLoc DL(&St);
    9741          40 :   SDValue BasePtr = St.getBasePtr();
    9742             :   uint64_t BaseOffset = 0;
    9743             : 
    9744          40 :   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
    9745             :   SDValue NewST1 =
    9746             :       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
    9747          80 :                    OrigAlignment, St.getMemOperand()->getFlags());
    9748             : 
    9749             :   // As this in ISel, we will not merge this add which may degrade results.
    9750          40 :   if (BasePtr->getOpcode() == ISD::ADD &&
    9751           7 :       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
    9752          12 :     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
    9753           6 :     BasePtr = BasePtr->getOperand(0);
    9754             :   }
    9755             : 
    9756             :   unsigned Offset = EltOffset;
    9757         164 :   while (--NumVecElts) {
    9758         124 :     unsigned Alignment = MinAlign(OrigAlignment, Offset);
    9759             :     SDValue OffsetPtr =
    9760             :         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
    9761         124 :                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
    9762          62 :     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
    9763             :                           PtrInfo.getWithOffset(Offset), Alignment,
    9764         124 :                           St.getMemOperand()->getFlags());
    9765          62 :     Offset += EltOffset;
    9766             :   }
    9767          80 :   return NewST1;
    9768             : }
    9769             : 
    9770             : /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
    9771             : /// load store optimizer pass will merge them to store pair stores.  This should
    9772             : /// be better than a movi to create the vector zero followed by a vector store
    9773             : /// if the zero constant is not re-used, since one instructions and one register
    9774             : /// live range will be removed.
    9775             : ///
    9776             : /// For example, the final generated code should be:
    9777             : ///
    9778             : ///   stp xzr, xzr, [x0]
    9779             : ///
    9780             : /// instead of:
    9781             : ///
    9782             : ///   movi v0.2d, #0
    9783             : ///   str q0, [x0]
    9784             : ///
    9785        2769 : static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
    9786        2769 :   SDValue StVal = St.getValue();
    9787        2769 :   EVT VT = StVal.getValueType();
    9788             : 
    9789             :   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
    9790             :   // 2, 3 or 4 i32 elements.
    9791        2769 :   int NumVecElts = VT.getVectorNumElements();
    9792        4068 :   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
    9793        4068 :          VT.getVectorElementType().getSizeInBits() == 64) ||
    9794         785 :         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
    9795        3554 :          VT.getVectorElementType().getSizeInBits() == 32)))
    9796        1167 :     return SDValue();
    9797             : 
    9798        1602 :   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
    9799        1372 :     return SDValue();
    9800             : 
    9801             :   // If the zero constant has more than one use then the vector store could be
    9802             :   // better since the constant mov will be amortized and stp q instructions
    9803             :   // should be able to be formed.
    9804         230 :   if (!StVal.hasOneUse())
    9805         169 :     return SDValue();
    9806             : 
    9807             :   // If the immediate offset of the address operand is too large for the stp
    9808             :   // instruction, then bail out.
    9809          61 :   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
    9810           8 :     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
    9811           8 :     if (Offset < -512 || Offset > 504)
    9812           2 :       return SDValue();
    9813             :   }
    9814             : 
    9815         263 :   for (int I = 0; I < NumVecElts; ++I) {
    9816         242 :     SDValue EltVal = StVal.getOperand(I);
    9817         121 :     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
    9818          19 :       return SDValue();
    9819             :   }
    9820             : 
    9821             :   // Use a CopyFromReg WZR/XZR here to prevent
    9822             :   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
    9823             :   SDLoc DL(&St);
    9824             :   unsigned ZeroReg;
    9825          40 :   EVT ZeroVT;
    9826          40 :   if (VT.getVectorElementType().getSizeInBits() == 32) {
    9827             :     ZeroReg = AArch64::WZR;
    9828          14 :     ZeroVT = MVT::i32;
    9829             :   } else {
    9830             :     ZeroReg = AArch64::XZR;
    9831          26 :     ZeroVT = MVT::i64;
    9832             :   }
    9833             :   SDValue SplatVal =
    9834          40 :       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
    9835          40 :   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
    9836             : }
    9837             : 
    9838             : /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
    9839             : /// value. The load store optimizer pass will merge them to store pair stores.
    9840             : /// This has better performance than a splat of the scalar followed by a split
    9841             : /// vector store. Even if the stores are not merged it is four stores vs a dup,
    9842             : /// followed by an ext.b and two stores.
    9843           4 : static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
    9844           4 :   SDValue StVal = St.getValue();
    9845           4 :   EVT VT = StVal.getValueType();
    9846             : 
    9847             :   // Don't replace floating point stores, they possibly won't be transformed to
    9848             :   // stp because of the store pair suppress pass.
    9849           4 :   if (VT.isFloatingPoint())
    9850           3 :     return SDValue();
    9851             : 
    9852             :   // We can express a splat as store pair(s) for 2 or 4 elements.
    9853           1 :   unsigned NumVecElts = VT.getVectorNumElements();
    9854           1 :   if (NumVecElts != 4 && NumVecElts != 2)
    9855           0 :     return SDValue();
    9856             : 
    9857             :   // Check that this is a splat.
    9858             :   // Make sure that each of the relevant vector element locations are inserted
    9859             :   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
    9860           1 :   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
    9861             :   SDValue SplatVal;
    9862           1 :   for (unsigned I = 0; I < NumVecElts; ++I) {
    9863             :     // Check for insert vector elements.
    9864           1 :     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
    9865           1 :       return SDValue();
    9866             : 
    9867             :     // Check that same value is inserted at each vector element.
    9868           0 :     if (I == 0)
    9869           0 :       SplatVal = StVal.getOperand(1);
    9870             :     else if (StVal.getOperand(1) != SplatVal)
    9871           0 :       return SDValue();
    9872             : 
    9873             :     // Check insert element index.
    9874             :     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
    9875             :     if (!CIndex)
    9876           0 :       return SDValue();
    9877           0 :     uint64_t IndexVal = CIndex->getZExtValue();
    9878           0 :     if (IndexVal >= NumVecElts)
    9879           0 :       return SDValue();
    9880           0 :     IndexNotInserted.reset(IndexVal);
    9881             : 
    9882           0 :     StVal = StVal.getOperand(0);
    9883             :   }
    9884             :   // Check that all vector element locations were inserted to.
    9885           0 :   if (IndexNotInserted.any())
    9886           0 :       return SDValue();
    9887             : 
    9888           0 :   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
    9889             : }
    9890             : 
    9891       13815 : static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
    9892             :                            SelectionDAG &DAG,
    9893             :                            const AArch64Subtarget *Subtarget) {
    9894             : 
    9895             :   StoreSDNode *S = cast<StoreSDNode>(N);
    9896       24977 :   if (S->isVolatile() || S->isIndexed())
    9897        2697 :     return SDValue();
    9898             : 
    9899       11118 :   SDValue StVal = S->getValue();
    9900       11118 :   EVT VT = StVal.getValueType();
    9901       11118 :   if (!VT.isVector())
    9902        8349 :     return SDValue();
    9903             : 
    9904             :   // If we get a splat of zeros, convert this vector store to a store of
    9905             :   // scalars. They will be merged into store pairs of xzr thereby removing one
    9906             :   // instruction and one register.
    9907        2769 :   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
    9908          40 :     return ReplacedZeroSplat;
    9909             : 
    9910             :   // FIXME: The logic for deciding if an unaligned store should be split should
    9911             :   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
    9912             :   // a call to that function here.
    9913             : 
    9914        2729 :   if (!Subtarget->isMisaligned128StoreSlow())
    9915        2597 :     return SDValue();
    9916             : 
    9917             :   // Don't split at -Oz.
    9918         264 :   if (DAG.getMachineFunction().getFunction().optForMinSize())
    9919           0 :     return SDValue();
    9920             : 
    9921             :   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
    9922             :   // those up regresses performance on micro-benchmarks and olden/bh.
    9923         132 :   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
    9924          14 :     return SDValue();
    9925             : 
    9926             :   // Split unaligned 16B stores. They are terrible for performance.
    9927             :   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
    9928             :   // extensions can use this to mark that it does not want splitting to happen
    9929             :   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
    9930             :   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
    9931         326 :   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
    9932           8 :       S->getAlignment() <= 2)
    9933         114 :     return SDValue();
    9934             : 
    9935             :   // If we get a splat of a scalar convert this vector store to a store of
    9936             :   // scalars. They will be merged into store pairs thereby removing two
    9937             :   // instructions.
    9938           4 :   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
    9939           0 :     return ReplacedSplat;
    9940             : 
    9941             :   SDLoc DL(S);
    9942           4 :   unsigned NumElts = VT.getVectorNumElements() / 2;
    9943             :   // Split VT into two.
    9944             :   EVT HalfVT =
    9945           4 :       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
    9946             :   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
    9947           4 :                                    DAG.getConstant(0, DL, MVT::i64));
    9948             :   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
    9949           4 :                                    DAG.getConstant(NumElts, DL, MVT::i64));
    9950           4 :   SDValue BasePtr = S->getBasePtr();
    9951             :   SDValue NewST1 =
    9952           4 :       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
    9953           8 :                    S->getAlignment(), S->getMemOperand()->getFlags());
    9954             :   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
    9955           8 :                                   DAG.getConstant(8, DL, MVT::i64));
    9956             :   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
    9957           4 :                       S->getPointerInfo(), S->getAlignment(),
    9958           8 :                       S->getMemOperand()->getFlags());
    9959             : }
    9960             : 
    9961             : /// Target-specific DAG combine function for post-increment LD1 (lane) and
    9962             : /// post-increment LD1R.
    9963        1832 : static SDValue performPostLD1Combine(SDNode *N,
    9964             :                                      TargetLowering::DAGCombinerInfo &DCI,
    9965             :                                      bool IsLaneOp) {
    9966        3664 :   if (DCI.isBeforeLegalizeOps())
    9967         690 :     return SDValue();
    9968             : 
    9969        1142 :   SelectionDAG &DAG = DCI.DAG;
    9970        2284 :   EVT VT = N->getValueType(0);
    9971             : 
    9972        1142 :   unsigned LoadIdx = IsLaneOp ? 1 : 0;
    9973        2284 :   SDNode *LD = N->getOperand(LoadIdx).getNode();
    9974             :   // If it is not LOAD, can not do such combine.
    9975        1142 :   if (LD->getOpcode() != ISD::LOAD)
    9976        1027 :     return SDValue();
    9977             : 
    9978             :   // The vector lane must be a constant in the LD1LANE opcode.
    9979         115 :   SDValue Lane;
    9980         115 :   if (IsLaneOp) {
    9981          68 :     Lane = N->getOperand(2);
    9982             :     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
    9983         132 :     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
    9984           2 :       return SDValue();
    9985             :   }
    9986             : 
    9987             :   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
    9988         113 :   EVT MemVT = LoadSDN->getMemoryVT();
    9989             :   // Check if memory operand is the same type as the vector element.
    9990         113 :   if (MemVT != VT.getVectorElementType())
    9991           6 :     return SDValue();
    9992             : 
    9993             :   // Check if there are other uses. If so, do not combine as it will introduce
    9994             :   // an extra load.
    9995         107 :   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
    9996             :        ++UI) {
    9997         167 :     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
    9998          60 :       continue;
    9999         107 :     if (*UI != N)
   10000           0 :       return SDValue();
   10001             :   }
   10002             : 
   10003         107 :   SDValue Addr = LD->getOperand(1);
   10004         107 :   SDValue Vector = N->getOperand(0);
   10005             :   // Search for a use of the address operand that is an increment.
   10006         107 :   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
   10007         192 :        Addr.getNode()->use_end(); UI != UE; ++UI) {
   10008             :     SDNode *User = *UI;
   10009         210 :     if (User->getOpcode() != ISD::ADD
   10010         171 :         || UI.getUse().getResNo() != Addr.getResNo())
   10011         168 :       continue;
   10012             : 
   10013             :     // Check that the add is independent of the load.  Otherwise, folding it
   10014             :     // would create a cycle.
   10015          88 :     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
   10016           0 :       continue;
   10017             :     // Also check that add is not used in the vector operand.  This would also
   10018             :     // create a cycle.
   10019          88 :     if (User->isPredecessorOf(Vector.getNode()))
   10020           0 :       continue;
   10021             : 
   10022             :     // If the increment is a constant, it must match the memory ref size.
   10023          88 :     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
   10024          44 :     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
   10025          44 :       uint32_t IncVal = CInc->getZExtValue();
   10026          22 :       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
   10027          22 :       if (IncVal != NumBytes)
   10028           1 :         continue;
   10029          21 :       Inc = DAG.getRegister(AArch64::XZR,