[FastISel][AArch64] Custom lower sdiv by power-of-2.
[oota-llvm.git] / lib / Target / AArch64 / AArch64FastISel.cpp
1 //===-- AArch6464FastISel.cpp - AArch64 FastISel 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 defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "AArch64.h"
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
39 using namespace llvm;
40
41 namespace {
42
43 class AArch64FastISel final : public FastISel {
44   class Address {
45   public:
46     typedef enum {
47       RegBase,
48       FrameIndexBase
49     } BaseKind;
50
51   private:
52     BaseKind Kind;
53     AArch64_AM::ShiftExtendType ExtType;
54     union {
55       unsigned Reg;
56       int FI;
57     } Base;
58     unsigned OffsetReg;
59     unsigned Shift;
60     int64_t Offset;
61     const GlobalValue *GV;
62
63   public:
64     Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65       OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66     void setKind(BaseKind K) { Kind = K; }
67     BaseKind getKind() const { return Kind; }
68     void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69     AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70     bool isRegBase() const { return Kind == RegBase; }
71     bool isFIBase() const { return Kind == FrameIndexBase; }
72     void setReg(unsigned Reg) {
73       assert(isRegBase() && "Invalid base register access!");
74       Base.Reg = Reg;
75     }
76     unsigned getReg() const {
77       assert(isRegBase() && "Invalid base register access!");
78       return Base.Reg;
79     }
80     void setOffsetReg(unsigned Reg) {
81       assert(isRegBase() && "Invalid offset register access!");
82       OffsetReg = Reg;
83     }
84     unsigned getOffsetReg() const {
85       assert(isRegBase() && "Invalid offset register access!");
86       return OffsetReg;
87     }
88     void setFI(unsigned FI) {
89       assert(isFIBase() && "Invalid base frame index  access!");
90       Base.FI = FI;
91     }
92     unsigned getFI() const {
93       assert(isFIBase() && "Invalid base frame index access!");
94       return Base.FI;
95     }
96     void setOffset(int64_t O) { Offset = O; }
97     int64_t getOffset() { return Offset; }
98     void setShift(unsigned S) { Shift = S; }
99     unsigned getShift() { return Shift; }
100
101     void setGlobalValue(const GlobalValue *G) { GV = G; }
102     const GlobalValue *getGlobalValue() { return GV; }
103   };
104
105   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106   /// make the right decision when generating code for different targets.
107   const AArch64Subtarget *Subtarget;
108   LLVMContext *Context;
109
110   bool fastLowerArguments() override;
111   bool fastLowerCall(CallLoweringInfo &CLI) override;
112   bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
113
114 private:
115   // Selection routines.
116   bool selectAddSub(const Instruction *I);
117   bool selectLogicalOp(const Instruction *I);
118   bool selectLoad(const Instruction *I);
119   bool selectStore(const Instruction *I);
120   bool selectBranch(const Instruction *I);
121   bool selectIndirectBr(const Instruction *I);
122   bool selectCmp(const Instruction *I);
123   bool selectSelect(const Instruction *I);
124   bool selectFPExt(const Instruction *I);
125   bool selectFPTrunc(const Instruction *I);
126   bool selectFPToInt(const Instruction *I, bool Signed);
127   bool selectIntToFP(const Instruction *I, bool Signed);
128   bool selectRem(const Instruction *I, unsigned ISDOpcode);
129   bool selectRet(const Instruction *I);
130   bool selectTrunc(const Instruction *I);
131   bool selectIntExt(const Instruction *I);
132   bool selectMul(const Instruction *I);
133   bool selectShift(const Instruction *I);
134   bool selectBitCast(const Instruction *I);
135   bool selectFRem(const Instruction *I);
136   bool selectSDiv(const Instruction *I);
137
138   // Utility helper routines.
139   bool isTypeLegal(Type *Ty, MVT &VT);
140   bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141   bool isValueAvailable(const Value *V) const;
142   bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143   bool computeCallAddress(const Value *V, Address &Addr);
144   bool simplifyAddress(Address &Addr, MVT VT);
145   void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146                             unsigned Flags, unsigned ScaleFactor,
147                             MachineMemOperand *MMO);
148   bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149   bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150                           unsigned Alignment);
151   bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152                          const Value *Cond);
153
154   // Emit helper routines.
155   unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
156                       const Value *RHS, bool SetFlags = false,
157                       bool WantResult = true,  bool IsZExt = false);
158   unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
159                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
160                          bool SetFlags = false, bool WantResult = true);
161   unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
162                          bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
163                          bool WantResult = true);
164   unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
165                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
166                          AArch64_AM::ShiftExtendType ShiftType,
167                          uint64_t ShiftImm, bool SetFlags = false,
168                          bool WantResult = true);
169   unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
170                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
171                           AArch64_AM::ShiftExtendType ExtType,
172                           uint64_t ShiftImm, bool SetFlags = false,
173                          bool WantResult = true);
174
175   // Emit functions.
176   bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
177   bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
178   bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
179   bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
180   bool emitLoad(MVT VT, unsigned &ResultReg, Address Addr,
181                 MachineMemOperand *MMO = nullptr);
182   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
183                  MachineMemOperand *MMO = nullptr);
184   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
185   unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
186   unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
187                    bool SetFlags = false, bool WantResult = true,
188                    bool IsZExt = false);
189   unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
190                    bool SetFlags = false, bool WantResult = true,
191                    bool IsZExt = false);
192   unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
193                        unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
194   unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
195                        unsigned RHSReg, bool RHSIsKill,
196                        AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
197                        bool WantResult = true);
198   unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
199                          const Value *RHS);
200   unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
201                             bool LHSIsKill, uint64_t Imm);
202   unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
203                             bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
204                             uint64_t ShiftImm);
205   unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
206   unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
207                       unsigned Op1, bool Op1IsKill);
208   unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
209                         unsigned Op1, bool Op1IsKill);
210   unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211                         unsigned Op1, bool Op1IsKill);
212   unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
213                       unsigned Op1Reg, bool Op1IsKill);
214   unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
215                       uint64_t Imm, bool IsZExt = true);
216   unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
217                       unsigned Op1Reg, bool Op1IsKill);
218   unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
219                       uint64_t Imm, bool IsZExt = true);
220   unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
221                       unsigned Op1Reg, bool Op1IsKill);
222   unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
223                       uint64_t Imm, bool IsZExt = false);
224
225   unsigned materializeInt(const ConstantInt *CI, MVT VT);
226   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
227   unsigned materializeGV(const GlobalValue *GV);
228
229   // Call handling routines.
230 private:
231   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
232   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
233                        unsigned &NumBytes);
234   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
235
236 public:
237   // Backend specific FastISel code.
238   unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
239   unsigned fastMaterializeConstant(const Constant *C) override;
240   unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
241
242   explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
243                          const TargetLibraryInfo *LibInfo)
244       : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
245     Subtarget = &TM.getSubtarget<AArch64Subtarget>();
246     Context = &FuncInfo.Fn->getContext();
247   }
248
249   bool fastSelectInstruction(const Instruction *I) override;
250
251 #include "AArch64GenFastISel.inc"
252 };
253
254 } // end anonymous namespace
255
256 #include "AArch64GenCallingConv.inc"
257
258 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
259   if (CC == CallingConv::WebKit_JS)
260     return CC_AArch64_WebKit_JS;
261   return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
262 }
263
264 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
265   assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
266          "Alloca should always return a pointer.");
267
268   // Don't handle dynamic allocas.
269   if (!FuncInfo.StaticAllocaMap.count(AI))
270     return 0;
271
272   DenseMap<const AllocaInst *, int>::iterator SI =
273       FuncInfo.StaticAllocaMap.find(AI);
274
275   if (SI != FuncInfo.StaticAllocaMap.end()) {
276     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
277     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
278             ResultReg)
279         .addFrameIndex(SI->second)
280         .addImm(0)
281         .addImm(0);
282     return ResultReg;
283   }
284
285   return 0;
286 }
287
288 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
289   if (VT > MVT::i64)
290     return 0;
291
292   if (!CI->isZero())
293     return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
294
295   // Create a copy from the zero register to materialize a "0" value.
296   const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
297                                                    : &AArch64::GPR32RegClass;
298   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
299   unsigned ResultReg = createResultReg(RC);
300   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
301           ResultReg).addReg(ZeroReg, getKillRegState(true));
302   return ResultReg;
303 }
304
305 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
306   // Positive zero (+0.0) has to be materialized with a fmov from the zero
307   // register, because the immediate version of fmov cannot encode zero.
308   if (CFP->isNullValue())
309     return fastMaterializeFloatZero(CFP);
310
311   if (VT != MVT::f32 && VT != MVT::f64)
312     return 0;
313
314   const APFloat Val = CFP->getValueAPF();
315   bool Is64Bit = (VT == MVT::f64);
316   // This checks to see if we can use FMOV instructions to materialize
317   // a constant, otherwise we have to materialize via the constant pool.
318   if (TLI.isFPImmLegal(Val, VT)) {
319     int Imm =
320         Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
321     assert((Imm != -1) && "Cannot encode floating-point constant.");
322     unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
323     return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
324   }
325
326   // Materialize via constant pool.  MachineConstantPool wants an explicit
327   // alignment.
328   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
329   if (Align == 0)
330     Align = DL.getTypeAllocSize(CFP->getType());
331
332   unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
333   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
334   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
335           ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
336
337   unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
338   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
339   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
340       .addReg(ADRPReg)
341       .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
342   return ResultReg;
343 }
344
345 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
346   // We can't handle thread-local variables quickly yet.
347   if (GV->isThreadLocal())
348     return 0;
349
350   // MachO still uses GOT for large code-model accesses, but ELF requires
351   // movz/movk sequences, which FastISel doesn't handle yet.
352   if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
353     return 0;
354
355   unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
356
357   EVT DestEVT = TLI.getValueType(GV->getType(), true);
358   if (!DestEVT.isSimple())
359     return 0;
360
361   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
362   unsigned ResultReg;
363
364   if (OpFlags & AArch64II::MO_GOT) {
365     // ADRP + LDRX
366     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
367             ADRPReg)
368       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
369
370     ResultReg = createResultReg(&AArch64::GPR64RegClass);
371     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
372             ResultReg)
373       .addReg(ADRPReg)
374       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
375                         AArch64II::MO_NC);
376   } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
377     // We can't handle addresses loaded from a constant pool quickly yet.
378     return 0;
379   } else {
380     // ADRP + ADDX
381     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
382             ADRPReg)
383       .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
384
385     ResultReg = createResultReg(&AArch64::GPR64spRegClass);
386     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
387             ResultReg)
388       .addReg(ADRPReg)
389       .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
390       .addImm(0);
391   }
392   return ResultReg;
393 }
394
395 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
396   EVT CEVT = TLI.getValueType(C->getType(), true);
397
398   // Only handle simple types.
399   if (!CEVT.isSimple())
400     return 0;
401   MVT VT = CEVT.getSimpleVT();
402
403   if (const auto *CI = dyn_cast<ConstantInt>(C))
404     return materializeInt(CI, VT);
405   else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
406     return materializeFP(CFP, VT);
407   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
408     return materializeGV(GV);
409
410   return 0;
411 }
412
413 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
414   assert(CFP->isNullValue() &&
415          "Floating-point constant is not a positive zero.");
416   MVT VT;
417   if (!isTypeLegal(CFP->getType(), VT))
418     return 0;
419
420   if (VT != MVT::f32 && VT != MVT::f64)
421     return 0;
422
423   bool Is64Bit = (VT == MVT::f64);
424   unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
425   unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
426   return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
427 }
428
429 /// \brief Check if the multiply is by a power-of-2 constant.
430 static bool isMulPowOf2(const Value *I) {
431   if (const auto *MI = dyn_cast<MulOperator>(I)) {
432     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
433       if (C->getValue().isPowerOf2())
434         return true;
435     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
436       if (C->getValue().isPowerOf2())
437         return true;
438   }
439   return false;
440 }
441
442 // Computes the address to get to an object.
443 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
444 {
445   const User *U = nullptr;
446   unsigned Opcode = Instruction::UserOp1;
447   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
448     // Don't walk into other basic blocks unless the object is an alloca from
449     // another block, otherwise it may not have a virtual register assigned.
450     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
451         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
452       Opcode = I->getOpcode();
453       U = I;
454     }
455   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
456     Opcode = C->getOpcode();
457     U = C;
458   }
459
460   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
461     if (Ty->getAddressSpace() > 255)
462       // Fast instruction selection doesn't support the special
463       // address spaces.
464       return false;
465
466   switch (Opcode) {
467   default:
468     break;
469   case Instruction::BitCast: {
470     // Look through bitcasts.
471     return computeAddress(U->getOperand(0), Addr, Ty);
472   }
473   case Instruction::IntToPtr: {
474     // Look past no-op inttoptrs.
475     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
476       return computeAddress(U->getOperand(0), Addr, Ty);
477     break;
478   }
479   case Instruction::PtrToInt: {
480     // Look past no-op ptrtoints.
481     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
482       return computeAddress(U->getOperand(0), Addr, Ty);
483     break;
484   }
485   case Instruction::GetElementPtr: {
486     Address SavedAddr = Addr;
487     uint64_t TmpOffset = Addr.getOffset();
488
489     // Iterate through the GEP folding the constants into offsets where
490     // we can.
491     gep_type_iterator GTI = gep_type_begin(U);
492     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
493          ++i, ++GTI) {
494       const Value *Op = *i;
495       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
496         const StructLayout *SL = DL.getStructLayout(STy);
497         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
498         TmpOffset += SL->getElementOffset(Idx);
499       } else {
500         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
501         for (;;) {
502           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
503             // Constant-offset addressing.
504             TmpOffset += CI->getSExtValue() * S;
505             break;
506           }
507           if (canFoldAddIntoGEP(U, Op)) {
508             // A compatible add with a constant operand. Fold the constant.
509             ConstantInt *CI =
510                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
511             TmpOffset += CI->getSExtValue() * S;
512             // Iterate on the other operand.
513             Op = cast<AddOperator>(Op)->getOperand(0);
514             continue;
515           }
516           // Unsupported
517           goto unsupported_gep;
518         }
519       }
520     }
521
522     // Try to grab the base operand now.
523     Addr.setOffset(TmpOffset);
524     if (computeAddress(U->getOperand(0), Addr, Ty))
525       return true;
526
527     // We failed, restore everything and try the other options.
528     Addr = SavedAddr;
529
530   unsupported_gep:
531     break;
532   }
533   case Instruction::Alloca: {
534     const AllocaInst *AI = cast<AllocaInst>(Obj);
535     DenseMap<const AllocaInst *, int>::iterator SI =
536         FuncInfo.StaticAllocaMap.find(AI);
537     if (SI != FuncInfo.StaticAllocaMap.end()) {
538       Addr.setKind(Address::FrameIndexBase);
539       Addr.setFI(SI->second);
540       return true;
541     }
542     break;
543   }
544   case Instruction::Add: {
545     // Adds of constants are common and easy enough.
546     const Value *LHS = U->getOperand(0);
547     const Value *RHS = U->getOperand(1);
548
549     if (isa<ConstantInt>(LHS))
550       std::swap(LHS, RHS);
551
552     if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
553       Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
554       return computeAddress(LHS, Addr, Ty);
555     }
556
557     Address Backup = Addr;
558     if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
559       return true;
560     Addr = Backup;
561
562     break;
563   }
564   case Instruction::Shl:
565     if (Addr.getOffsetReg())
566       break;
567
568     if (const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
569       unsigned Val = CI->getZExtValue();
570       if (Val < 1 || Val > 3)
571         break;
572
573       uint64_t NumBytes = 0;
574       if (Ty && Ty->isSized()) {
575         uint64_t NumBits = DL.getTypeSizeInBits(Ty);
576         NumBytes = NumBits / 8;
577         if (!isPowerOf2_64(NumBits))
578           NumBytes = 0;
579       }
580
581       if (NumBytes != (1ULL << Val))
582         break;
583
584       Addr.setShift(Val);
585       Addr.setExtendType(AArch64_AM::LSL);
586
587       if (const auto *I = dyn_cast<Instruction>(U->getOperand(0)))
588         if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
589           U = I;
590
591       if (const auto *ZE = dyn_cast<ZExtInst>(U))
592         if (ZE->getOperand(0)->getType()->isIntegerTy(32))
593           Addr.setExtendType(AArch64_AM::UXTW);
594
595       if (const auto *SE = dyn_cast<SExtInst>(U))
596         if (SE->getOperand(0)->getType()->isIntegerTy(32))
597           Addr.setExtendType(AArch64_AM::SXTW);
598
599       unsigned Reg = getRegForValue(U->getOperand(0));
600       if (!Reg)
601         return false;
602       Addr.setOffsetReg(Reg);
603       return true;
604     }
605     break;
606   case Instruction::Mul: {
607     if (Addr.getOffsetReg())
608       break;
609
610     if (!isMulPowOf2(U))
611       break;
612
613     const Value *LHS = U->getOperand(0);
614     const Value *RHS = U->getOperand(1);
615
616     // Canonicalize power-of-2 value to the RHS.
617     if (const auto *C = dyn_cast<ConstantInt>(LHS))
618       if (C->getValue().isPowerOf2())
619         std::swap(LHS, RHS);
620
621     assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
622     const auto *C = cast<ConstantInt>(RHS);
623     unsigned Val = C->getValue().logBase2();
624     if (Val < 1 || Val > 3)
625       break;
626
627     uint64_t NumBytes = 0;
628     if (Ty && Ty->isSized()) {
629       uint64_t NumBits = DL.getTypeSizeInBits(Ty);
630       NumBytes = NumBits / 8;
631       if (!isPowerOf2_64(NumBits))
632         NumBytes = 0;
633     }
634
635     if (NumBytes != (1ULL << Val))
636       break;
637
638     Addr.setShift(Val);
639     Addr.setExtendType(AArch64_AM::LSL);
640
641     if (const auto *I = dyn_cast<Instruction>(LHS))
642       if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
643         U = I;
644
645     if (const auto *ZE = dyn_cast<ZExtInst>(U))
646       if (ZE->getOperand(0)->getType()->isIntegerTy(32)) {
647         Addr.setExtendType(AArch64_AM::UXTW);
648         LHS = U->getOperand(0);
649       }
650
651     if (const auto *SE = dyn_cast<SExtInst>(U))
652       if (SE->getOperand(0)->getType()->isIntegerTy(32)) {
653         Addr.setExtendType(AArch64_AM::SXTW);
654         LHS = U->getOperand(0);
655       }
656
657     unsigned Reg = getRegForValue(LHS);
658     if (!Reg)
659       return false;
660     Addr.setOffsetReg(Reg);
661     return true;
662   }
663   } // end switch
664
665   if (Addr.getReg()) {
666     if (!Addr.getOffsetReg()) {
667       unsigned Reg = getRegForValue(Obj);
668       if (!Reg)
669         return false;
670       Addr.setOffsetReg(Reg);
671       return true;
672     }
673     return false;
674   }
675
676   unsigned Reg = getRegForValue(Obj);
677   if (!Reg)
678     return false;
679   Addr.setReg(Reg);
680   return true;
681 }
682
683 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
684   const User *U = nullptr;
685   unsigned Opcode = Instruction::UserOp1;
686   bool InMBB = true;
687
688   if (const auto *I = dyn_cast<Instruction>(V)) {
689     Opcode = I->getOpcode();
690     U = I;
691     InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
692   } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
693     Opcode = C->getOpcode();
694     U = C;
695   }
696
697   switch (Opcode) {
698   default: break;
699   case Instruction::BitCast:
700     // Look past bitcasts if its operand is in the same BB.
701     if (InMBB)
702       return computeCallAddress(U->getOperand(0), Addr);
703     break;
704   case Instruction::IntToPtr:
705     // Look past no-op inttoptrs if its operand is in the same BB.
706     if (InMBB &&
707         TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
708       return computeCallAddress(U->getOperand(0), Addr);
709     break;
710   case Instruction::PtrToInt:
711     // Look past no-op ptrtoints if its operand is in the same BB.
712     if (InMBB &&
713         TLI.getValueType(U->getType()) == TLI.getPointerTy())
714       return computeCallAddress(U->getOperand(0), Addr);
715     break;
716   }
717
718   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
719     Addr.setGlobalValue(GV);
720     return true;
721   }
722
723   // If all else fails, try to materialize the value in a register.
724   if (!Addr.getGlobalValue()) {
725     Addr.setReg(getRegForValue(V));
726     return Addr.getReg() != 0;
727   }
728
729   return false;
730 }
731
732
733 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
734   EVT evt = TLI.getValueType(Ty, true);
735
736   // Only handle simple types.
737   if (evt == MVT::Other || !evt.isSimple())
738     return false;
739   VT = evt.getSimpleVT();
740
741   // This is a legal type, but it's not something we handle in fast-isel.
742   if (VT == MVT::f128)
743     return false;
744
745   // Handle all other legal types, i.e. a register that will directly hold this
746   // value.
747   return TLI.isTypeLegal(VT);
748 }
749
750 /// \brief Determine if the value type is supported by FastISel.
751 ///
752 /// FastISel for AArch64 can handle more value types than are legal. This adds
753 /// simple value type such as i1, i8, and i16.
754 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
755   if (Ty->isVectorTy() && !IsVectorAllowed)
756     return false;
757
758   if (isTypeLegal(Ty, VT))
759     return true;
760
761   // If this is a type than can be sign or zero-extended to a basic operation
762   // go ahead and accept it now.
763   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
764     return true;
765
766   return false;
767 }
768
769 bool AArch64FastISel::isValueAvailable(const Value *V) const {
770   if (!isa<Instruction>(V))
771     return true;
772
773   const auto *I = cast<Instruction>(V);
774   if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
775     return true;
776
777   return false;
778 }
779
780 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
781   unsigned ScaleFactor;
782   switch (VT.SimpleTy) {
783   default: return false;
784   case MVT::i1:  // fall-through
785   case MVT::i8:  ScaleFactor = 1; break;
786   case MVT::i16: ScaleFactor = 2; break;
787   case MVT::i32: // fall-through
788   case MVT::f32: ScaleFactor = 4; break;
789   case MVT::i64: // fall-through
790   case MVT::f64: ScaleFactor = 8; break;
791   }
792
793   bool ImmediateOffsetNeedsLowering = false;
794   bool RegisterOffsetNeedsLowering = false;
795   int64_t Offset = Addr.getOffset();
796   if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
797     ImmediateOffsetNeedsLowering = true;
798   else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
799            !isUInt<12>(Offset / ScaleFactor))
800     ImmediateOffsetNeedsLowering = true;
801
802   // Cannot encode an offset register and an immediate offset in the same
803   // instruction. Fold the immediate offset into the load/store instruction and
804   // emit an additonal add to take care of the offset register.
805   if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
806       Addr.getOffsetReg())
807     RegisterOffsetNeedsLowering = true;
808
809   // Cannot encode zero register as base.
810   if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
811     RegisterOffsetNeedsLowering = true;
812
813   // If this is a stack pointer and the offset needs to be simplified then put
814   // the alloca address into a register, set the base type back to register and
815   // continue. This should almost never happen.
816   if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
817     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
818     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
819             ResultReg)
820       .addFrameIndex(Addr.getFI())
821       .addImm(0)
822       .addImm(0);
823     Addr.setKind(Address::RegBase);
824     Addr.setReg(ResultReg);
825   }
826
827   if (RegisterOffsetNeedsLowering) {
828     unsigned ResultReg = 0;
829     if (Addr.getReg()) {
830       if (Addr.getExtendType() == AArch64_AM::SXTW ||
831           Addr.getExtendType() == AArch64_AM::UXTW   )
832         ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
833                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
834                                   /*TODO:IsKill=*/false, Addr.getExtendType(),
835                                   Addr.getShift());
836       else
837         ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
838                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
839                                   /*TODO:IsKill=*/false, AArch64_AM::LSL,
840                                   Addr.getShift());
841     } else {
842       if (Addr.getExtendType() == AArch64_AM::UXTW)
843         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
844                                /*Op0IsKill=*/false, Addr.getShift(),
845                                /*IsZExt=*/true);
846       else if (Addr.getExtendType() == AArch64_AM::SXTW)
847         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
848                                /*Op0IsKill=*/false, Addr.getShift(),
849                                /*IsZExt=*/false);
850       else
851         ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
852                                /*Op0IsKill=*/false, Addr.getShift());
853     }
854     if (!ResultReg)
855       return false;
856
857     Addr.setReg(ResultReg);
858     Addr.setOffsetReg(0);
859     Addr.setShift(0);
860     Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
861   }
862
863   // Since the offset is too large for the load/store instruction get the
864   // reg+offset into a register.
865   if (ImmediateOffsetNeedsLowering) {
866     unsigned ResultReg = 0;
867     if (Addr.getReg())
868       ResultReg = fastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(),
869                                /*IsKill=*/false, Offset, MVT::i64);
870     else
871       ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
872
873     if (!ResultReg)
874       return false;
875     Addr.setReg(ResultReg);
876     Addr.setOffset(0);
877   }
878   return true;
879 }
880
881 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
882                                            const MachineInstrBuilder &MIB,
883                                            unsigned Flags,
884                                            unsigned ScaleFactor,
885                                            MachineMemOperand *MMO) {
886   int64_t Offset = Addr.getOffset() / ScaleFactor;
887   // Frame base works a bit differently. Handle it separately.
888   if (Addr.isFIBase()) {
889     int FI = Addr.getFI();
890     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
891     // and alignment should be based on the VT.
892     MMO = FuncInfo.MF->getMachineMemOperand(
893       MachinePointerInfo::getFixedStack(FI, Offset), Flags,
894       MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
895     // Now add the rest of the operands.
896     MIB.addFrameIndex(FI).addImm(Offset);
897   } else {
898     assert(Addr.isRegBase() && "Unexpected address kind.");
899     const MCInstrDesc &II = MIB->getDesc();
900     unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
901     Addr.setReg(
902       constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
903     Addr.setOffsetReg(
904       constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
905     if (Addr.getOffsetReg()) {
906       assert(Addr.getOffset() == 0 && "Unexpected offset");
907       bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
908                       Addr.getExtendType() == AArch64_AM::SXTX;
909       MIB.addReg(Addr.getReg());
910       MIB.addReg(Addr.getOffsetReg());
911       MIB.addImm(IsSigned);
912       MIB.addImm(Addr.getShift() != 0);
913     } else {
914       MIB.addReg(Addr.getReg());
915       MIB.addImm(Offset);
916     }
917   }
918
919   if (MMO)
920     MIB.addMemOperand(MMO);
921 }
922
923 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
924                                      const Value *RHS, bool SetFlags,
925                                      bool WantResult,  bool IsZExt) {
926   AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
927   bool NeedExtend = false;
928   switch (RetVT.SimpleTy) {
929   default:
930     return 0;
931   case MVT::i1:
932     NeedExtend = true;
933     break;
934   case MVT::i8:
935     NeedExtend = true;
936     ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
937     break;
938   case MVT::i16:
939     NeedExtend = true;
940     ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
941     break;
942   case MVT::i32:  // fall-through
943   case MVT::i64:
944     break;
945   }
946   MVT SrcVT = RetVT;
947   RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
948
949   // Canonicalize immediates to the RHS first.
950   if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
951     std::swap(LHS, RHS);
952
953   // Canonicalize mul by power of 2 to the RHS.
954   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
955     if (isMulPowOf2(LHS))
956       std::swap(LHS, RHS);
957
958   // Canonicalize shift immediate to the RHS.
959   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
960     if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
961       if (isa<ConstantInt>(SI->getOperand(1)))
962         if (SI->getOpcode() == Instruction::Shl  ||
963             SI->getOpcode() == Instruction::LShr ||
964             SI->getOpcode() == Instruction::AShr   )
965           std::swap(LHS, RHS);
966
967   unsigned LHSReg = getRegForValue(LHS);
968   if (!LHSReg)
969     return 0;
970   bool LHSIsKill = hasTrivialKill(LHS);
971
972   if (NeedExtend)
973     LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
974
975   unsigned ResultReg = 0;
976   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
977     uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
978     if (C->isNegative())
979       ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
980                                 SetFlags, WantResult);
981     else
982       ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
983                                 WantResult);
984   }
985   if (ResultReg)
986     return ResultReg;
987
988   // Only extend the RHS within the instruction if there is a valid extend type.
989   if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
990       isValueAvailable(RHS)) {
991     if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
992       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
993         if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
994           unsigned RHSReg = getRegForValue(SI->getOperand(0));
995           if (!RHSReg)
996             return 0;
997           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
998           return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
999                                RHSIsKill, ExtendType, C->getZExtValue(),
1000                                SetFlags, WantResult);
1001         }
1002     unsigned RHSReg = getRegForValue(RHS);
1003     if (!RHSReg)
1004       return 0;
1005     bool RHSIsKill = hasTrivialKill(RHS);
1006     return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1007                          ExtendType, 0, SetFlags, WantResult);
1008   }
1009
1010   // Check if the mul can be folded into the instruction.
1011   if (RHS->hasOneUse() && isValueAvailable(RHS))
1012     if (isMulPowOf2(RHS)) {
1013       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1014       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1015
1016       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1017         if (C->getValue().isPowerOf2())
1018           std::swap(MulLHS, MulRHS);
1019
1020       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1021       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1022       unsigned RHSReg = getRegForValue(MulLHS);
1023       if (!RHSReg)
1024         return 0;
1025       bool RHSIsKill = hasTrivialKill(MulLHS);
1026       return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1027                            AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1028     }
1029
1030   // Check if the shift can be folded into the instruction.
1031   if (RHS->hasOneUse() && isValueAvailable(RHS))
1032     if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1033       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1034         AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1035         switch (SI->getOpcode()) {
1036         default: break;
1037         case Instruction::Shl:  ShiftType = AArch64_AM::LSL; break;
1038         case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1039         case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1040         }
1041         uint64_t ShiftVal = C->getZExtValue();
1042         if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1043           unsigned RHSReg = getRegForValue(SI->getOperand(0));
1044           if (!RHSReg)
1045             return 0;
1046           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1047           return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1048                                RHSIsKill, ShiftType, ShiftVal, SetFlags,
1049                                WantResult);
1050         }
1051       }
1052     }
1053
1054   unsigned RHSReg = getRegForValue(RHS);
1055   if (!RHSReg)
1056     return 0;
1057   bool RHSIsKill = hasTrivialKill(RHS);
1058
1059   if (NeedExtend)
1060     RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1061
1062   return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1063                        SetFlags, WantResult);
1064 }
1065
1066 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1067                                         bool LHSIsKill, unsigned RHSReg,
1068                                         bool RHSIsKill, bool SetFlags,
1069                                         bool WantResult) {
1070   assert(LHSReg && RHSReg && "Invalid register number.");
1071
1072   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1073     return 0;
1074
1075   static const unsigned OpcTable[2][2][2] = {
1076     { { AArch64::SUBWrr,  AArch64::SUBXrr  },
1077       { AArch64::ADDWrr,  AArch64::ADDXrr  }  },
1078     { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1079       { AArch64::ADDSWrr, AArch64::ADDSXrr }  }
1080   };
1081   bool Is64Bit = RetVT == MVT::i64;
1082   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1083   const TargetRegisterClass *RC =
1084       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1085   unsigned ResultReg;
1086   if (WantResult)
1087     ResultReg = createResultReg(RC);
1088   else
1089     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1090
1091   const MCInstrDesc &II = TII.get(Opc);
1092   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1093   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1094   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1095       .addReg(LHSReg, getKillRegState(LHSIsKill))
1096       .addReg(RHSReg, getKillRegState(RHSIsKill));
1097   return ResultReg;
1098 }
1099
1100 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1101                                         bool LHSIsKill, uint64_t Imm,
1102                                         bool SetFlags, bool WantResult) {
1103   assert(LHSReg && "Invalid register number.");
1104
1105   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1106     return 0;
1107
1108   unsigned ShiftImm;
1109   if (isUInt<12>(Imm))
1110     ShiftImm = 0;
1111   else if ((Imm & 0xfff000) == Imm) {
1112     ShiftImm = 12;
1113     Imm >>= 12;
1114   } else
1115     return 0;
1116
1117   static const unsigned OpcTable[2][2][2] = {
1118     { { AArch64::SUBWri,  AArch64::SUBXri  },
1119       { AArch64::ADDWri,  AArch64::ADDXri  }  },
1120     { { AArch64::SUBSWri, AArch64::SUBSXri },
1121       { AArch64::ADDSWri, AArch64::ADDSXri }  }
1122   };
1123   bool Is64Bit = RetVT == MVT::i64;
1124   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1125   const TargetRegisterClass *RC;
1126   if (SetFlags)
1127     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1128   else
1129     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1130   unsigned ResultReg;
1131   if (WantResult)
1132     ResultReg = createResultReg(RC);
1133   else
1134     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1135
1136   const MCInstrDesc &II = TII.get(Opc);
1137   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1138   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1139       .addReg(LHSReg, getKillRegState(LHSIsKill))
1140       .addImm(Imm)
1141       .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1142   return ResultReg;
1143 }
1144
1145 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1146                                         bool LHSIsKill, unsigned RHSReg,
1147                                         bool RHSIsKill,
1148                                         AArch64_AM::ShiftExtendType ShiftType,
1149                                         uint64_t ShiftImm, bool SetFlags,
1150                                         bool WantResult) {
1151   assert(LHSReg && RHSReg && "Invalid register number.");
1152
1153   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1154     return 0;
1155
1156   static const unsigned OpcTable[2][2][2] = {
1157     { { AArch64::SUBWrs,  AArch64::SUBXrs  },
1158       { AArch64::ADDWrs,  AArch64::ADDXrs  }  },
1159     { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1160       { AArch64::ADDSWrs, AArch64::ADDSXrs }  }
1161   };
1162   bool Is64Bit = RetVT == MVT::i64;
1163   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1164   const TargetRegisterClass *RC =
1165       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1166   unsigned ResultReg;
1167   if (WantResult)
1168     ResultReg = createResultReg(RC);
1169   else
1170     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1171
1172   const MCInstrDesc &II = TII.get(Opc);
1173   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1174   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1175   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1176       .addReg(LHSReg, getKillRegState(LHSIsKill))
1177       .addReg(RHSReg, getKillRegState(RHSIsKill))
1178       .addImm(getShifterImm(ShiftType, ShiftImm));
1179   return ResultReg;
1180 }
1181
1182 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1183                                         bool LHSIsKill, unsigned RHSReg,
1184                                         bool RHSIsKill,
1185                                         AArch64_AM::ShiftExtendType ExtType,
1186                                         uint64_t ShiftImm, bool SetFlags,
1187                                         bool WantResult) {
1188   assert(LHSReg && RHSReg && "Invalid register number.");
1189
1190   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1191     return 0;
1192
1193   static const unsigned OpcTable[2][2][2] = {
1194     { { AArch64::SUBWrx,  AArch64::SUBXrx  },
1195       { AArch64::ADDWrx,  AArch64::ADDXrx  }  },
1196     { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1197       { AArch64::ADDSWrx, AArch64::ADDSXrx }  }
1198   };
1199   bool Is64Bit = RetVT == MVT::i64;
1200   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1201   const TargetRegisterClass *RC = nullptr;
1202   if (SetFlags)
1203     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1204   else
1205     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1206   unsigned ResultReg;
1207   if (WantResult)
1208     ResultReg = createResultReg(RC);
1209   else
1210     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1211
1212   const MCInstrDesc &II = TII.get(Opc);
1213   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1214   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1215   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1216       .addReg(LHSReg, getKillRegState(LHSIsKill))
1217       .addReg(RHSReg, getKillRegState(RHSIsKill))
1218       .addImm(getArithExtendImm(ExtType, ShiftImm));
1219   return ResultReg;
1220 }
1221
1222 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1223   Type *Ty = LHS->getType();
1224   EVT EVT = TLI.getValueType(Ty, true);
1225   if (!EVT.isSimple())
1226     return false;
1227   MVT VT = EVT.getSimpleVT();
1228
1229   switch (VT.SimpleTy) {
1230   default:
1231     return false;
1232   case MVT::i1:
1233   case MVT::i8:
1234   case MVT::i16:
1235   case MVT::i32:
1236   case MVT::i64:
1237     return emitICmp(VT, LHS, RHS, IsZExt);
1238   case MVT::f32:
1239   case MVT::f64:
1240     return emitFCmp(VT, LHS, RHS);
1241   }
1242 }
1243
1244 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1245                                bool IsZExt) {
1246   return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1247                  IsZExt) != 0;
1248 }
1249
1250 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1251                                   uint64_t Imm) {
1252   return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1253                        /*SetFlags=*/true, /*WantResult=*/false) != 0;
1254 }
1255
1256 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1257   if (RetVT != MVT::f32 && RetVT != MVT::f64)
1258     return false;
1259
1260   // Check to see if the 2nd operand is a constant that we can encode directly
1261   // in the compare.
1262   bool UseImm = false;
1263   if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1264     if (CFP->isZero() && !CFP->isNegative())
1265       UseImm = true;
1266
1267   unsigned LHSReg = getRegForValue(LHS);
1268   if (!LHSReg)
1269     return false;
1270   bool LHSIsKill = hasTrivialKill(LHS);
1271
1272   if (UseImm) {
1273     unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1274     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1275         .addReg(LHSReg, getKillRegState(LHSIsKill));
1276     return true;
1277   }
1278
1279   unsigned RHSReg = getRegForValue(RHS);
1280   if (!RHSReg)
1281     return false;
1282   bool RHSIsKill = hasTrivialKill(RHS);
1283
1284   unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1285   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1286       .addReg(LHSReg, getKillRegState(LHSIsKill))
1287       .addReg(RHSReg, getKillRegState(RHSIsKill));
1288   return true;
1289 }
1290
1291 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1292                                   bool SetFlags, bool WantResult, bool IsZExt) {
1293   return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1294                     IsZExt);
1295 }
1296
1297 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1298                                   bool SetFlags, bool WantResult, bool IsZExt) {
1299   return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1300                     IsZExt);
1301 }
1302
1303 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1304                                       bool LHSIsKill, unsigned RHSReg,
1305                                       bool RHSIsKill, bool WantResult) {
1306   return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1307                        RHSIsKill, /*SetFlags=*/true, WantResult);
1308 }
1309
1310 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1311                                       bool LHSIsKill, unsigned RHSReg,
1312                                       bool RHSIsKill,
1313                                       AArch64_AM::ShiftExtendType ShiftType,
1314                                       uint64_t ShiftImm, bool WantResult) {
1315   return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1316                        RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1317                        WantResult);
1318 }
1319
1320 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1321                                         const Value *LHS, const Value *RHS) {
1322   // Canonicalize immediates to the RHS first.
1323   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1324     std::swap(LHS, RHS);
1325
1326   // Canonicalize mul by power-of-2 to the RHS.
1327   if (LHS->hasOneUse() && isValueAvailable(LHS))
1328     if (isMulPowOf2(LHS))
1329       std::swap(LHS, RHS);
1330
1331   // Canonicalize shift immediate to the RHS.
1332   if (LHS->hasOneUse() && isValueAvailable(LHS))
1333     if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1334       if (isa<ConstantInt>(SI->getOperand(1)))
1335         std::swap(LHS, RHS);
1336
1337   unsigned LHSReg = getRegForValue(LHS);
1338   if (!LHSReg)
1339     return 0;
1340   bool LHSIsKill = hasTrivialKill(LHS);
1341
1342   unsigned ResultReg = 0;
1343   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1344     uint64_t Imm = C->getZExtValue();
1345     ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1346   }
1347   if (ResultReg)
1348     return ResultReg;
1349
1350   // Check if the mul can be folded into the instruction.
1351   if (RHS->hasOneUse() && isValueAvailable(RHS))
1352     if (isMulPowOf2(RHS)) {
1353       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1354       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1355
1356       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1357         if (C->getValue().isPowerOf2())
1358           std::swap(MulLHS, MulRHS);
1359
1360       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1361       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1362
1363       unsigned RHSReg = getRegForValue(MulLHS);
1364       if (!RHSReg)
1365         return 0;
1366       bool RHSIsKill = hasTrivialKill(MulLHS);
1367       return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1368                               RHSIsKill, ShiftVal);
1369     }
1370
1371   // Check if the shift can be folded into the instruction.
1372   if (RHS->hasOneUse() && isValueAvailable(RHS))
1373     if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1374       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1375         uint64_t ShiftVal = C->getZExtValue();
1376         unsigned RHSReg = getRegForValue(SI->getOperand(0));
1377         if (!RHSReg)
1378           return 0;
1379         bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1380         return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1381                                 RHSIsKill, ShiftVal);
1382       }
1383
1384   unsigned RHSReg = getRegForValue(RHS);
1385   if (!RHSReg)
1386     return 0;
1387   bool RHSIsKill = hasTrivialKill(RHS);
1388
1389   MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1390   ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1391   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1392     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1393     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1394   }
1395   return ResultReg;
1396 }
1397
1398 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1399                                            unsigned LHSReg, bool LHSIsKill,
1400                                            uint64_t Imm) {
1401   assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1402          "ISD nodes are not consecutive!");
1403   static const unsigned OpcTable[3][2] = {
1404     { AArch64::ANDWri, AArch64::ANDXri },
1405     { AArch64::ORRWri, AArch64::ORRXri },
1406     { AArch64::EORWri, AArch64::EORXri }
1407   };
1408   const TargetRegisterClass *RC;
1409   unsigned Opc;
1410   unsigned RegSize;
1411   switch (RetVT.SimpleTy) {
1412   default:
1413     return 0;
1414   case MVT::i1:
1415   case MVT::i8:
1416   case MVT::i16:
1417   case MVT::i32: {
1418     unsigned Idx = ISDOpc - ISD::AND;
1419     Opc = OpcTable[Idx][0];
1420     RC = &AArch64::GPR32spRegClass;
1421     RegSize = 32;
1422     break;
1423   }
1424   case MVT::i64:
1425     Opc = OpcTable[ISDOpc - ISD::AND][1];
1426     RC = &AArch64::GPR64spRegClass;
1427     RegSize = 64;
1428     break;
1429   }
1430
1431   if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1432     return 0;
1433
1434   unsigned ResultReg =
1435       fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1436                       AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1437   if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1438     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1439     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1440   }
1441   return ResultReg;
1442 }
1443
1444 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1445                                            unsigned LHSReg, bool LHSIsKill,
1446                                            unsigned RHSReg, bool RHSIsKill,
1447                                            uint64_t ShiftImm) {
1448   assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1449          "ISD nodes are not consecutive!");
1450   static const unsigned OpcTable[3][2] = {
1451     { AArch64::ANDWrs, AArch64::ANDXrs },
1452     { AArch64::ORRWrs, AArch64::ORRXrs },
1453     { AArch64::EORWrs, AArch64::EORXrs }
1454   };
1455   const TargetRegisterClass *RC;
1456   unsigned Opc;
1457   switch (RetVT.SimpleTy) {
1458   default:
1459     return 0;
1460   case MVT::i1:
1461   case MVT::i8:
1462   case MVT::i16:
1463   case MVT::i32:
1464     Opc = OpcTable[ISDOpc - ISD::AND][0];
1465     RC = &AArch64::GPR32RegClass;
1466     break;
1467   case MVT::i64:
1468     Opc = OpcTable[ISDOpc - ISD::AND][1];
1469     RC = &AArch64::GPR64RegClass;
1470     break;
1471   }
1472   unsigned ResultReg =
1473       fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1474                        AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1475   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1476     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1477     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1478   }
1479   return ResultReg;
1480 }
1481
1482 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1483                                      uint64_t Imm) {
1484   return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1485 }
1486
1487 bool AArch64FastISel::emitLoad(MVT VT, unsigned &ResultReg, Address Addr,
1488                                MachineMemOperand *MMO) {
1489   // Simplify this down to something we can handle.
1490   if (!simplifyAddress(Addr, VT))
1491     return false;
1492
1493   unsigned ScaleFactor;
1494   switch (VT.SimpleTy) {
1495   default: llvm_unreachable("Unexpected value type.");
1496   case MVT::i1:  // fall-through
1497   case MVT::i8:  ScaleFactor = 1; break;
1498   case MVT::i16: ScaleFactor = 2; break;
1499   case MVT::i32: // fall-through
1500   case MVT::f32: ScaleFactor = 4; break;
1501   case MVT::i64: // fall-through
1502   case MVT::f64: ScaleFactor = 8; break;
1503   }
1504
1505   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1506   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1507   bool UseScaled = true;
1508   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1509     UseScaled = false;
1510     ScaleFactor = 1;
1511   }
1512
1513   static const unsigned OpcTable[4][6] = {
1514     { AArch64::LDURBBi,  AArch64::LDURHHi,  AArch64::LDURWi,  AArch64::LDURXi,
1515       AArch64::LDURSi,   AArch64::LDURDi },
1516     { AArch64::LDRBBui,  AArch64::LDRHHui,  AArch64::LDRWui,  AArch64::LDRXui,
1517       AArch64::LDRSui,   AArch64::LDRDui },
1518     { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX, AArch64::LDRXroX,
1519       AArch64::LDRSroX,  AArch64::LDRDroX },
1520     { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW, AArch64::LDRXroW,
1521       AArch64::LDRSroW,  AArch64::LDRDroW }
1522   };
1523
1524   unsigned Opc;
1525   const TargetRegisterClass *RC;
1526   bool VTIsi1 = false;
1527   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1528                       Addr.getOffsetReg();
1529   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1530   if (Addr.getExtendType() == AArch64_AM::UXTW ||
1531       Addr.getExtendType() == AArch64_AM::SXTW)
1532     Idx++;
1533
1534   switch (VT.SimpleTy) {
1535   default: llvm_unreachable("Unexpected value type.");
1536   case MVT::i1:  VTIsi1 = true; // Intentional fall-through.
1537   case MVT::i8:  Opc = OpcTable[Idx][0]; RC = &AArch64::GPR32RegClass; break;
1538   case MVT::i16: Opc = OpcTable[Idx][1]; RC = &AArch64::GPR32RegClass; break;
1539   case MVT::i32: Opc = OpcTable[Idx][2]; RC = &AArch64::GPR32RegClass; break;
1540   case MVT::i64: Opc = OpcTable[Idx][3]; RC = &AArch64::GPR64RegClass; break;
1541   case MVT::f32: Opc = OpcTable[Idx][4]; RC = &AArch64::FPR32RegClass; break;
1542   case MVT::f64: Opc = OpcTable[Idx][5]; RC = &AArch64::FPR64RegClass; break;
1543   }
1544
1545   // Create the base instruction, then add the operands.
1546   ResultReg = createResultReg(RC);
1547   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1548                                     TII.get(Opc), ResultReg);
1549   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1550
1551   // Loading an i1 requires special handling.
1552   if (VTIsi1) {
1553     unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1554     assert(ANDReg && "Unexpected AND instruction emission failure.");
1555     ResultReg = ANDReg;
1556   }
1557   return true;
1558 }
1559
1560 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1561   MVT VT;
1562   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1563     return false;
1564
1565   if (VT.isVector())
1566     return selectOperator(I, I->getOpcode());
1567
1568   unsigned ResultReg;
1569   switch (I->getOpcode()) {
1570   default:
1571     llvm_unreachable("Unexpected instruction.");
1572   case Instruction::Add:
1573     ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1574     break;
1575   case Instruction::Sub:
1576     ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1577     break;
1578   }
1579   if (!ResultReg)
1580     return false;
1581
1582   updateValueMap(I, ResultReg);
1583   return true;
1584 }
1585
1586 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1587   MVT VT;
1588   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1589     return false;
1590
1591   if (VT.isVector())
1592     return selectOperator(I, I->getOpcode());
1593
1594   unsigned ResultReg;
1595   switch (I->getOpcode()) {
1596   default:
1597     llvm_unreachable("Unexpected instruction.");
1598   case Instruction::And:
1599     ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1600     break;
1601   case Instruction::Or:
1602     ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1603     break;
1604   case Instruction::Xor:
1605     ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1606     break;
1607   }
1608   if (!ResultReg)
1609     return false;
1610
1611   updateValueMap(I, ResultReg);
1612   return true;
1613 }
1614
1615 bool AArch64FastISel::selectLoad(const Instruction *I) {
1616   MVT VT;
1617   // Verify we have a legal type before going any further.  Currently, we handle
1618   // simple types that will directly fit in a register (i32/f32/i64/f64) or
1619   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1620   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1621       cast<LoadInst>(I)->isAtomic())
1622     return false;
1623
1624   // See if we can handle this address.
1625   Address Addr;
1626   if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1627     return false;
1628
1629   unsigned ResultReg;
1630   if (!emitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
1631     return false;
1632
1633   updateValueMap(I, ResultReg);
1634   return true;
1635 }
1636
1637 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1638                                 MachineMemOperand *MMO) {
1639   // Simplify this down to something we can handle.
1640   if (!simplifyAddress(Addr, VT))
1641     return false;
1642
1643   unsigned ScaleFactor;
1644   switch (VT.SimpleTy) {
1645   default: llvm_unreachable("Unexpected value type.");
1646   case MVT::i1:  // fall-through
1647   case MVT::i8:  ScaleFactor = 1; break;
1648   case MVT::i16: ScaleFactor = 2; break;
1649   case MVT::i32: // fall-through
1650   case MVT::f32: ScaleFactor = 4; break;
1651   case MVT::i64: // fall-through
1652   case MVT::f64: ScaleFactor = 8; break;
1653   }
1654
1655   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1656   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1657   bool UseScaled = true;
1658   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1659     UseScaled = false;
1660     ScaleFactor = 1;
1661   }
1662
1663
1664   static const unsigned OpcTable[4][6] = {
1665     { AArch64::STURBBi,  AArch64::STURHHi,  AArch64::STURWi,  AArch64::STURXi,
1666       AArch64::STURSi,   AArch64::STURDi },
1667     { AArch64::STRBBui,  AArch64::STRHHui,  AArch64::STRWui,  AArch64::STRXui,
1668       AArch64::STRSui,   AArch64::STRDui },
1669     { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1670       AArch64::STRSroX,  AArch64::STRDroX },
1671     { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1672       AArch64::STRSroW,  AArch64::STRDroW }
1673
1674   };
1675
1676   unsigned Opc;
1677   bool VTIsi1 = false;
1678   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1679                       Addr.getOffsetReg();
1680   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1681   if (Addr.getExtendType() == AArch64_AM::UXTW ||
1682       Addr.getExtendType() == AArch64_AM::SXTW)
1683     Idx++;
1684
1685   switch (VT.SimpleTy) {
1686   default: llvm_unreachable("Unexpected value type.");
1687   case MVT::i1:  VTIsi1 = true;
1688   case MVT::i8:  Opc = OpcTable[Idx][0]; break;
1689   case MVT::i16: Opc = OpcTable[Idx][1]; break;
1690   case MVT::i32: Opc = OpcTable[Idx][2]; break;
1691   case MVT::i64: Opc = OpcTable[Idx][3]; break;
1692   case MVT::f32: Opc = OpcTable[Idx][4]; break;
1693   case MVT::f64: Opc = OpcTable[Idx][5]; break;
1694   }
1695
1696   // Storing an i1 requires special handling.
1697   if (VTIsi1 && SrcReg != AArch64::WZR) {
1698     unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1699     assert(ANDReg && "Unexpected AND instruction emission failure.");
1700     SrcReg = ANDReg;
1701   }
1702   // Create the base instruction, then add the operands.
1703   const MCInstrDesc &II = TII.get(Opc);
1704   SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1705   MachineInstrBuilder MIB =
1706       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1707   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1708
1709   return true;
1710 }
1711
1712 bool AArch64FastISel::selectStore(const Instruction *I) {
1713   MVT VT;
1714   const Value *Op0 = I->getOperand(0);
1715   // Verify we have a legal type before going any further.  Currently, we handle
1716   // simple types that will directly fit in a register (i32/f32/i64/f64) or
1717   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1718   if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
1719       cast<StoreInst>(I)->isAtomic())
1720     return false;
1721
1722   // Get the value to be stored into a register. Use the zero register directly
1723   // when possible to avoid an unnecessary copy and a wasted register.
1724   unsigned SrcReg = 0;
1725   if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
1726     if (CI->isZero())
1727       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1728   } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
1729     if (CF->isZero() && !CF->isNegative()) {
1730       VT = MVT::getIntegerVT(VT.getSizeInBits());
1731       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1732     }
1733   }
1734
1735   if (!SrcReg)
1736     SrcReg = getRegForValue(Op0);
1737
1738   if (!SrcReg)
1739     return false;
1740
1741   // See if we can handle this address.
1742   Address Addr;
1743   if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
1744     return false;
1745
1746   if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
1747     return false;
1748   return true;
1749 }
1750
1751 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
1752   switch (Pred) {
1753   case CmpInst::FCMP_ONE:
1754   case CmpInst::FCMP_UEQ:
1755   default:
1756     // AL is our "false" for now. The other two need more compares.
1757     return AArch64CC::AL;
1758   case CmpInst::ICMP_EQ:
1759   case CmpInst::FCMP_OEQ:
1760     return AArch64CC::EQ;
1761   case CmpInst::ICMP_SGT:
1762   case CmpInst::FCMP_OGT:
1763     return AArch64CC::GT;
1764   case CmpInst::ICMP_SGE:
1765   case CmpInst::FCMP_OGE:
1766     return AArch64CC::GE;
1767   case CmpInst::ICMP_UGT:
1768   case CmpInst::FCMP_UGT:
1769     return AArch64CC::HI;
1770   case CmpInst::FCMP_OLT:
1771     return AArch64CC::MI;
1772   case CmpInst::ICMP_ULE:
1773   case CmpInst::FCMP_OLE:
1774     return AArch64CC::LS;
1775   case CmpInst::FCMP_ORD:
1776     return AArch64CC::VC;
1777   case CmpInst::FCMP_UNO:
1778     return AArch64CC::VS;
1779   case CmpInst::FCMP_UGE:
1780     return AArch64CC::PL;
1781   case CmpInst::ICMP_SLT:
1782   case CmpInst::FCMP_ULT:
1783     return AArch64CC::LT;
1784   case CmpInst::ICMP_SLE:
1785   case CmpInst::FCMP_ULE:
1786     return AArch64CC::LE;
1787   case CmpInst::FCMP_UNE:
1788   case CmpInst::ICMP_NE:
1789     return AArch64CC::NE;
1790   case CmpInst::ICMP_UGE:
1791     return AArch64CC::HS;
1792   case CmpInst::ICMP_ULT:
1793     return AArch64CC::LO;
1794   }
1795 }
1796
1797 /// \brief Check if the comparison against zero and the following branch can be
1798 /// folded into a single instruction (CBZ or CBNZ).
1799 static bool canFoldZeroIntoBranch(const CmpInst *CI) {
1800   CmpInst::Predicate Predicate = CI->getPredicate();
1801   if ((Predicate != CmpInst::ICMP_EQ) && (Predicate != CmpInst::ICMP_NE))
1802     return false;
1803
1804   Type *Ty = CI->getOperand(0)->getType();
1805   if (!Ty->isIntegerTy())
1806     return false;
1807
1808   unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
1809   if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
1810     return false;
1811
1812   if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(0)))
1813     if (C->isNullValue())
1814       return true;
1815
1816   if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(1)))
1817     if (C->isNullValue())
1818       return true;
1819
1820   return false;
1821 }
1822
1823 bool AArch64FastISel::selectBranch(const Instruction *I) {
1824   const BranchInst *BI = cast<BranchInst>(I);
1825   if (BI->isUnconditional()) {
1826     MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
1827     fastEmitBranch(MSucc, BI->getDebugLoc());
1828     return true;
1829   }
1830
1831   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1832   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1833
1834   AArch64CC::CondCode CC = AArch64CC::NE;
1835   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1836     if (CI->hasOneUse() && isValueAvailable(CI)) {
1837       // Try to optimize or fold the cmp.
1838       CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1839       switch (Predicate) {
1840       default:
1841         break;
1842       case CmpInst::FCMP_FALSE:
1843         fastEmitBranch(FBB, DbgLoc);
1844         return true;
1845       case CmpInst::FCMP_TRUE:
1846         fastEmitBranch(TBB, DbgLoc);
1847         return true;
1848       }
1849
1850       // Try to take advantage of fallthrough opportunities.
1851       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1852         std::swap(TBB, FBB);
1853         Predicate = CmpInst::getInversePredicate(Predicate);
1854       }
1855
1856       // Try to optimize comparisons against zero.
1857       if (canFoldZeroIntoBranch(CI)) {
1858         const Value *LHS = CI->getOperand(0);
1859         const Value *RHS = CI->getOperand(1);
1860
1861         // Canonicalize zero values to the RHS.
1862         if (const auto *C = dyn_cast<ConstantInt>(LHS))
1863           if (C->isNullValue())
1864             std::swap(LHS, RHS);
1865
1866         static const unsigned OpcTable[2][2] = {
1867           {AArch64::CBZW,  AArch64::CBZX }, {AArch64::CBNZW, AArch64::CBNZX}
1868         };
1869         bool IsCmpNE = Predicate == CmpInst::ICMP_NE;
1870         bool Is64Bit = LHS->getType()->isIntegerTy(64);
1871         unsigned Opc = OpcTable[IsCmpNE][Is64Bit];
1872
1873         unsigned SrcReg = getRegForValue(LHS);
1874         if (!SrcReg)
1875           return false;
1876         bool SrcIsKill = hasTrivialKill(LHS);
1877
1878         // Emit the combined compare and branch instruction.
1879         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1880             .addReg(SrcReg, getKillRegState(SrcIsKill))
1881             .addMBB(TBB);
1882
1883         // Obtain the branch weight and add the TrueBB to the successor list.
1884         uint32_t BranchWeight = 0;
1885         if (FuncInfo.BPI)
1886           BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1887                                                      TBB->getBasicBlock());
1888         FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1889
1890         fastEmitBranch(FBB, DbgLoc);
1891         return true;
1892       }
1893
1894       // Emit the cmp.
1895       if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1896         return false;
1897
1898       // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
1899       // instruction.
1900       CC = getCompareCC(Predicate);
1901       AArch64CC::CondCode ExtraCC = AArch64CC::AL;
1902       switch (Predicate) {
1903       default:
1904         break;
1905       case CmpInst::FCMP_UEQ:
1906         ExtraCC = AArch64CC::EQ;
1907         CC = AArch64CC::VS;
1908         break;
1909       case CmpInst::FCMP_ONE:
1910         ExtraCC = AArch64CC::MI;
1911         CC = AArch64CC::GT;
1912         break;
1913       }
1914       assert((CC != AArch64CC::AL) && "Unexpected condition code.");
1915
1916       // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
1917       if (ExtraCC != AArch64CC::AL) {
1918         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1919             .addImm(ExtraCC)
1920             .addMBB(TBB);
1921       }
1922
1923       // Emit the branch.
1924       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1925           .addImm(CC)
1926           .addMBB(TBB);
1927
1928       // Obtain the branch weight and add the TrueBB to the successor list.
1929       uint32_t BranchWeight = 0;
1930       if (FuncInfo.BPI)
1931         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1932                                                   TBB->getBasicBlock());
1933       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1934
1935       fastEmitBranch(FBB, DbgLoc);
1936       return true;
1937     }
1938   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1939     MVT SrcVT;
1940     if (TI->hasOneUse() && isValueAvailable(TI) &&
1941         isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
1942       unsigned CondReg = getRegForValue(TI->getOperand(0));
1943       if (!CondReg)
1944         return false;
1945       bool CondIsKill = hasTrivialKill(TI->getOperand(0));
1946
1947       // Issue an extract_subreg to get the lower 32-bits.
1948       if (SrcVT == MVT::i64) {
1949         CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
1950                                              AArch64::sub_32);
1951         CondIsKill = true;
1952       }
1953
1954       unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
1955       assert(ANDReg && "Unexpected AND instruction emission failure.");
1956       emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1957
1958       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1959         std::swap(TBB, FBB);
1960         CC = AArch64CC::EQ;
1961       }
1962       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1963           .addImm(CC)
1964           .addMBB(TBB);
1965
1966       // Obtain the branch weight and add the TrueBB to the successor list.
1967       uint32_t BranchWeight = 0;
1968       if (FuncInfo.BPI)
1969         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1970                                                   TBB->getBasicBlock());
1971       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1972
1973       fastEmitBranch(FBB, DbgLoc);
1974       return true;
1975     }
1976   } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
1977     uint64_t Imm = CI->getZExtValue();
1978     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1979     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
1980         .addMBB(Target);
1981
1982     // Obtain the branch weight and add the target to the successor list.
1983     uint32_t BranchWeight = 0;
1984     if (FuncInfo.BPI)
1985       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1986                                                  Target->getBasicBlock());
1987     FuncInfo.MBB->addSuccessor(Target, BranchWeight);
1988     return true;
1989   } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
1990     // Fake request the condition, otherwise the intrinsic might be completely
1991     // optimized away.
1992     unsigned CondReg = getRegForValue(BI->getCondition());
1993     if (!CondReg)
1994       return false;
1995
1996     // Emit the branch.
1997     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1998       .addImm(CC)
1999       .addMBB(TBB);
2000
2001     // Obtain the branch weight and add the TrueBB to the successor list.
2002     uint32_t BranchWeight = 0;
2003     if (FuncInfo.BPI)
2004       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2005                                                  TBB->getBasicBlock());
2006     FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2007
2008     fastEmitBranch(FBB, DbgLoc);
2009     return true;
2010   }
2011
2012   unsigned CondReg = getRegForValue(BI->getCondition());
2013   if (CondReg == 0)
2014     return false;
2015   bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2016
2017   // We've been divorced from our compare!  Our block was split, and
2018   // now our compare lives in a predecessor block.  We musn't
2019   // re-compare here, as the children of the compare aren't guaranteed
2020   // live across the block boundary (we *could* check for this).
2021   // Regardless, the compare has been done in the predecessor block,
2022   // and it left a value for us in a virtual register.  Ergo, we test
2023   // the one-bit value left in the virtual register.
2024   emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2025
2026   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2027     std::swap(TBB, FBB);
2028     CC = AArch64CC::EQ;
2029   }
2030
2031   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2032       .addImm(CC)
2033       .addMBB(TBB);
2034
2035   // Obtain the branch weight and add the TrueBB to the successor list.
2036   uint32_t BranchWeight = 0;
2037   if (FuncInfo.BPI)
2038     BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2039                                                TBB->getBasicBlock());
2040   FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2041
2042   fastEmitBranch(FBB, DbgLoc);
2043   return true;
2044 }
2045
2046 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2047   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2048   unsigned AddrReg = getRegForValue(BI->getOperand(0));
2049   if (AddrReg == 0)
2050     return false;
2051
2052   // Emit the indirect branch.
2053   const MCInstrDesc &II = TII.get(AArch64::BR);
2054   AddrReg = constrainOperandRegClass(II, AddrReg,  II.getNumDefs());
2055   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2056
2057   // Make sure the CFG is up-to-date.
2058   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2059     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2060
2061   return true;
2062 }
2063
2064 bool AArch64FastISel::selectCmp(const Instruction *I) {
2065   const CmpInst *CI = cast<CmpInst>(I);
2066
2067   // Try to optimize or fold the cmp.
2068   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2069   unsigned ResultReg = 0;
2070   switch (Predicate) {
2071   default:
2072     break;
2073   case CmpInst::FCMP_FALSE:
2074     ResultReg = createResultReg(&AArch64::GPR32RegClass);
2075     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2076             TII.get(TargetOpcode::COPY), ResultReg)
2077         .addReg(AArch64::WZR, getKillRegState(true));
2078     break;
2079   case CmpInst::FCMP_TRUE:
2080     ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2081     break;
2082   }
2083
2084   if (ResultReg) {
2085     updateValueMap(I, ResultReg);
2086     return true;
2087   }
2088
2089   // Emit the cmp.
2090   if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2091     return false;
2092
2093   ResultReg = createResultReg(&AArch64::GPR32RegClass);
2094
2095   // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2096   // condition codes are inverted, because they are used by CSINC.
2097   static unsigned CondCodeTable[2][2] = {
2098     { AArch64CC::NE, AArch64CC::VC },
2099     { AArch64CC::PL, AArch64CC::LE }
2100   };
2101   unsigned *CondCodes = nullptr;
2102   switch (Predicate) {
2103   default:
2104     break;
2105   case CmpInst::FCMP_UEQ:
2106     CondCodes = &CondCodeTable[0][0];
2107     break;
2108   case CmpInst::FCMP_ONE:
2109     CondCodes = &CondCodeTable[1][0];
2110     break;
2111   }
2112
2113   if (CondCodes) {
2114     unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2115     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2116             TmpReg1)
2117         .addReg(AArch64::WZR, getKillRegState(true))
2118         .addReg(AArch64::WZR, getKillRegState(true))
2119         .addImm(CondCodes[0]);
2120     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2121             ResultReg)
2122         .addReg(TmpReg1, getKillRegState(true))
2123         .addReg(AArch64::WZR, getKillRegState(true))
2124         .addImm(CondCodes[1]);
2125
2126     updateValueMap(I, ResultReg);
2127     return true;
2128   }
2129
2130   // Now set a register based on the comparison.
2131   AArch64CC::CondCode CC = getCompareCC(Predicate);
2132   assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2133   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2134   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2135           ResultReg)
2136       .addReg(AArch64::WZR, getKillRegState(true))
2137       .addReg(AArch64::WZR, getKillRegState(true))
2138       .addImm(invertedCC);
2139
2140   updateValueMap(I, ResultReg);
2141   return true;
2142 }
2143
2144 bool AArch64FastISel::selectSelect(const Instruction *I) {
2145   const SelectInst *SI = cast<SelectInst>(I);
2146
2147   EVT DestEVT = TLI.getValueType(SI->getType(), true);
2148   if (!DestEVT.isSimple())
2149     return false;
2150
2151   MVT DestVT = DestEVT.getSimpleVT();
2152   if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2153       DestVT != MVT::f64)
2154     return false;
2155
2156   unsigned SelectOpc;
2157   const TargetRegisterClass *RC = nullptr;
2158   switch (DestVT.SimpleTy) {
2159   default: return false;
2160   case MVT::i32:
2161     SelectOpc = AArch64::CSELWr;    RC = &AArch64::GPR32RegClass; break;
2162   case MVT::i64:
2163     SelectOpc = AArch64::CSELXr;    RC = &AArch64::GPR64RegClass; break;
2164   case MVT::f32:
2165     SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2166   case MVT::f64:
2167     SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2168   }
2169
2170   const Value *Cond = SI->getCondition();
2171   bool NeedTest = true;
2172   AArch64CC::CondCode CC = AArch64CC::NE;
2173   if (foldXALUIntrinsic(CC, I, Cond))
2174     NeedTest = false;
2175
2176   unsigned CondReg = getRegForValue(Cond);
2177   if (!CondReg)
2178     return false;
2179   bool CondIsKill = hasTrivialKill(Cond);
2180
2181   if (NeedTest) {
2182     unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2183     assert(ANDReg && "Unexpected AND instruction emission failure.");
2184     emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2185   }
2186
2187   unsigned TrueReg = getRegForValue(SI->getTrueValue());
2188   bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2189
2190   unsigned FalseReg = getRegForValue(SI->getFalseValue());
2191   bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2192
2193   if (!TrueReg || !FalseReg)
2194     return false;
2195
2196   unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2197                                         FalseReg, FalseIsKill, CC);
2198   updateValueMap(I, ResultReg);
2199   return true;
2200 }
2201
2202 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2203   Value *V = I->getOperand(0);
2204   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2205     return false;
2206
2207   unsigned Op = getRegForValue(V);
2208   if (Op == 0)
2209     return false;
2210
2211   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2212   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2213           ResultReg).addReg(Op);
2214   updateValueMap(I, ResultReg);
2215   return true;
2216 }
2217
2218 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2219   Value *V = I->getOperand(0);
2220   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2221     return false;
2222
2223   unsigned Op = getRegForValue(V);
2224   if (Op == 0)
2225     return false;
2226
2227   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2228   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2229           ResultReg).addReg(Op);
2230   updateValueMap(I, ResultReg);
2231   return true;
2232 }
2233
2234 // FPToUI and FPToSI
2235 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2236   MVT DestVT;
2237   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2238     return false;
2239
2240   unsigned SrcReg = getRegForValue(I->getOperand(0));
2241   if (SrcReg == 0)
2242     return false;
2243
2244   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2245   if (SrcVT == MVT::f128)
2246     return false;
2247
2248   unsigned Opc;
2249   if (SrcVT == MVT::f64) {
2250     if (Signed)
2251       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2252     else
2253       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2254   } else {
2255     if (Signed)
2256       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2257     else
2258       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2259   }
2260   unsigned ResultReg = createResultReg(
2261       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2262   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2263       .addReg(SrcReg);
2264   updateValueMap(I, ResultReg);
2265   return true;
2266 }
2267
2268 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2269   MVT DestVT;
2270   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2271     return false;
2272   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2273           "Unexpected value type.");
2274
2275   unsigned SrcReg = getRegForValue(I->getOperand(0));
2276   if (!SrcReg)
2277     return false;
2278   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2279
2280   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2281
2282   // Handle sign-extension.
2283   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2284     SrcReg =
2285         emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2286     if (!SrcReg)
2287       return false;
2288     SrcIsKill = true;
2289   }
2290
2291   unsigned Opc;
2292   if (SrcVT == MVT::i64) {
2293     if (Signed)
2294       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2295     else
2296       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2297   } else {
2298     if (Signed)
2299       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2300     else
2301       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2302   }
2303
2304   unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2305                                       SrcIsKill);
2306   updateValueMap(I, ResultReg);
2307   return true;
2308 }
2309
2310 bool AArch64FastISel::fastLowerArguments() {
2311   if (!FuncInfo.CanLowerReturn)
2312     return false;
2313
2314   const Function *F = FuncInfo.Fn;
2315   if (F->isVarArg())
2316     return false;
2317
2318   CallingConv::ID CC = F->getCallingConv();
2319   if (CC != CallingConv::C)
2320     return false;
2321
2322   // Only handle simple cases of up to 8 GPR and FPR each.
2323   unsigned GPRCnt = 0;
2324   unsigned FPRCnt = 0;
2325   unsigned Idx = 0;
2326   for (auto const &Arg : F->args()) {
2327     // The first argument is at index 1.
2328     ++Idx;
2329     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2330         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2331         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2332         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2333       return false;
2334
2335     Type *ArgTy = Arg.getType();
2336     if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2337       return false;
2338
2339     EVT ArgVT = TLI.getValueType(ArgTy);
2340     if (!ArgVT.isSimple())
2341       return false;
2342
2343     MVT VT = ArgVT.getSimpleVT().SimpleTy;
2344     if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2345       return false;
2346
2347     if (VT.isVector() &&
2348         (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2349       return false;
2350
2351     if (VT >= MVT::i1 && VT <= MVT::i64)
2352       ++GPRCnt;
2353     else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2354              VT.is128BitVector())
2355       ++FPRCnt;
2356     else
2357       return false;
2358
2359     if (GPRCnt > 8 || FPRCnt > 8)
2360       return false;
2361   }
2362
2363   static const MCPhysReg Registers[6][8] = {
2364     { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2365       AArch64::W5, AArch64::W6, AArch64::W7 },
2366     { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2367       AArch64::X5, AArch64::X6, AArch64::X7 },
2368     { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2369       AArch64::H5, AArch64::H6, AArch64::H7 },
2370     { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2371       AArch64::S5, AArch64::S6, AArch64::S7 },
2372     { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2373       AArch64::D5, AArch64::D6, AArch64::D7 },
2374     { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2375       AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2376   };
2377
2378   unsigned GPRIdx = 0;
2379   unsigned FPRIdx = 0;
2380   for (auto const &Arg : F->args()) {
2381     MVT VT = TLI.getSimpleValueType(Arg.getType());
2382     unsigned SrcReg;
2383     const TargetRegisterClass *RC;
2384     if (VT >= MVT::i1 && VT <= MVT::i32) {
2385       SrcReg = Registers[0][GPRIdx++];
2386       RC = &AArch64::GPR32RegClass;
2387       VT = MVT::i32;
2388     } else if (VT == MVT::i64) {
2389       SrcReg = Registers[1][GPRIdx++];
2390       RC = &AArch64::GPR64RegClass;
2391     } else if (VT == MVT::f16) {
2392       SrcReg = Registers[2][FPRIdx++];
2393       RC = &AArch64::FPR16RegClass;
2394     } else if (VT ==  MVT::f32) {
2395       SrcReg = Registers[3][FPRIdx++];
2396       RC = &AArch64::FPR32RegClass;
2397     } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2398       SrcReg = Registers[4][FPRIdx++];
2399       RC = &AArch64::FPR64RegClass;
2400     } else if (VT.is128BitVector()) {
2401       SrcReg = Registers[5][FPRIdx++];
2402       RC = &AArch64::FPR128RegClass;
2403     } else
2404       llvm_unreachable("Unexpected value type.");
2405
2406     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2407     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2408     // Without this, EmitLiveInCopies may eliminate the livein if its only
2409     // use is a bitcast (which isn't turned into an instruction).
2410     unsigned ResultReg = createResultReg(RC);
2411     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2412             TII.get(TargetOpcode::COPY), ResultReg)
2413         .addReg(DstReg, getKillRegState(true));
2414     updateValueMap(&Arg, ResultReg);
2415   }
2416   return true;
2417 }
2418
2419 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2420                                       SmallVectorImpl<MVT> &OutVTs,
2421                                       unsigned &NumBytes) {
2422   CallingConv::ID CC = CLI.CallConv;
2423   SmallVector<CCValAssign, 16> ArgLocs;
2424   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2425   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2426
2427   // Get a count of how many bytes are to be pushed on the stack.
2428   NumBytes = CCInfo.getNextStackOffset();
2429
2430   // Issue CALLSEQ_START
2431   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2432   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2433     .addImm(NumBytes);
2434
2435   // Process the args.
2436   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2437     CCValAssign &VA = ArgLocs[i];
2438     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2439     MVT ArgVT = OutVTs[VA.getValNo()];
2440
2441     unsigned ArgReg = getRegForValue(ArgVal);
2442     if (!ArgReg)
2443       return false;
2444
2445     // Handle arg promotion: SExt, ZExt, AExt.
2446     switch (VA.getLocInfo()) {
2447     case CCValAssign::Full:
2448       break;
2449     case CCValAssign::SExt: {
2450       MVT DestVT = VA.getLocVT();
2451       MVT SrcVT = ArgVT;
2452       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2453       if (!ArgReg)
2454         return false;
2455       break;
2456     }
2457     case CCValAssign::AExt:
2458     // Intentional fall-through.
2459     case CCValAssign::ZExt: {
2460       MVT DestVT = VA.getLocVT();
2461       MVT SrcVT = ArgVT;
2462       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2463       if (!ArgReg)
2464         return false;
2465       break;
2466     }
2467     default:
2468       llvm_unreachable("Unknown arg promotion!");
2469     }
2470
2471     // Now copy/store arg to correct locations.
2472     if (VA.isRegLoc() && !VA.needsCustom()) {
2473       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2474               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2475       CLI.OutRegs.push_back(VA.getLocReg());
2476     } else if (VA.needsCustom()) {
2477       // FIXME: Handle custom args.
2478       return false;
2479     } else {
2480       assert(VA.isMemLoc() && "Assuming store on stack.");
2481
2482       // Don't emit stores for undef values.
2483       if (isa<UndefValue>(ArgVal))
2484         continue;
2485
2486       // Need to store on the stack.
2487       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2488
2489       unsigned BEAlign = 0;
2490       if (ArgSize < 8 && !Subtarget->isLittleEndian())
2491         BEAlign = 8 - ArgSize;
2492
2493       Address Addr;
2494       Addr.setKind(Address::RegBase);
2495       Addr.setReg(AArch64::SP);
2496       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2497
2498       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2499       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2500         MachinePointerInfo::getStack(Addr.getOffset()),
2501         MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2502
2503       if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2504         return false;
2505     }
2506   }
2507   return true;
2508 }
2509
2510 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2511                                  unsigned NumBytes) {
2512   CallingConv::ID CC = CLI.CallConv;
2513
2514   // Issue CALLSEQ_END
2515   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2516   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2517     .addImm(NumBytes).addImm(0);
2518
2519   // Now the return value.
2520   if (RetVT != MVT::isVoid) {
2521     SmallVector<CCValAssign, 16> RVLocs;
2522     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2523     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2524
2525     // Only handle a single return value.
2526     if (RVLocs.size() != 1)
2527       return false;
2528
2529     // Copy all of the result registers out of their specified physreg.
2530     MVT CopyVT = RVLocs[0].getValVT();
2531     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2532     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2533             TII.get(TargetOpcode::COPY), ResultReg)
2534         .addReg(RVLocs[0].getLocReg());
2535     CLI.InRegs.push_back(RVLocs[0].getLocReg());
2536
2537     CLI.ResultReg = ResultReg;
2538     CLI.NumResultRegs = 1;
2539   }
2540
2541   return true;
2542 }
2543
2544 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2545   CallingConv::ID CC  = CLI.CallConv;
2546   bool IsTailCall     = CLI.IsTailCall;
2547   bool IsVarArg       = CLI.IsVarArg;
2548   const Value *Callee = CLI.Callee;
2549   const char *SymName = CLI.SymName;
2550
2551   if (!Callee && !SymName)
2552     return false;
2553
2554   // Allow SelectionDAG isel to handle tail calls.
2555   if (IsTailCall)
2556     return false;
2557
2558   CodeModel::Model CM = TM.getCodeModel();
2559   // Only support the small and large code model.
2560   if (CM != CodeModel::Small && CM != CodeModel::Large)
2561     return false;
2562
2563   // FIXME: Add large code model support for ELF.
2564   if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2565     return false;
2566
2567   // Let SDISel handle vararg functions.
2568   if (IsVarArg)
2569     return false;
2570
2571   // FIXME: Only handle *simple* calls for now.
2572   MVT RetVT;
2573   if (CLI.RetTy->isVoidTy())
2574     RetVT = MVT::isVoid;
2575   else if (!isTypeLegal(CLI.RetTy, RetVT))
2576     return false;
2577
2578   for (auto Flag : CLI.OutFlags)
2579     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2580       return false;
2581
2582   // Set up the argument vectors.
2583   SmallVector<MVT, 16> OutVTs;
2584   OutVTs.reserve(CLI.OutVals.size());
2585
2586   for (auto *Val : CLI.OutVals) {
2587     MVT VT;
2588     if (!isTypeLegal(Val->getType(), VT) &&
2589         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2590       return false;
2591
2592     // We don't handle vector parameters yet.
2593     if (VT.isVector() || VT.getSizeInBits() > 64)
2594       return false;
2595
2596     OutVTs.push_back(VT);
2597   }
2598
2599   Address Addr;
2600   if (Callee && !computeCallAddress(Callee, Addr))
2601     return false;
2602
2603   // Handle the arguments now that we've gotten them.
2604   unsigned NumBytes;
2605   if (!processCallArgs(CLI, OutVTs, NumBytes))
2606     return false;
2607
2608   // Issue the call.
2609   MachineInstrBuilder MIB;
2610   if (CM == CodeModel::Small) {
2611     const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2612     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2613     if (SymName)
2614       MIB.addExternalSymbol(SymName, 0);
2615     else if (Addr.getGlobalValue())
2616       MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2617     else if (Addr.getReg()) {
2618       unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2619       MIB.addReg(Reg);
2620     } else
2621       return false;
2622   } else {
2623     unsigned CallReg = 0;
2624     if (SymName) {
2625       unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2626       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2627               ADRPReg)
2628         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2629
2630       CallReg = createResultReg(&AArch64::GPR64RegClass);
2631       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2632               CallReg)
2633         .addReg(ADRPReg)
2634         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2635                            AArch64II::MO_NC);
2636     } else if (Addr.getGlobalValue())
2637       CallReg = materializeGV(Addr.getGlobalValue());
2638     else if (Addr.getReg())
2639       CallReg = Addr.getReg();
2640
2641     if (!CallReg)
2642       return false;
2643
2644     const MCInstrDesc &II = TII.get(AArch64::BLR);
2645     CallReg = constrainOperandRegClass(II, CallReg, 0);
2646     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2647   }
2648
2649   // Add implicit physical register uses to the call.
2650   for (auto Reg : CLI.OutRegs)
2651     MIB.addReg(Reg, RegState::Implicit);
2652
2653   // Add a register mask with the call-preserved registers.
2654   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2655   MIB.addRegMask(TRI.getCallPreservedMask(CC));
2656
2657   CLI.Call = MIB;
2658
2659   // Finish off the call including any return values.
2660   return finishCall(CLI, RetVT, NumBytes);
2661 }
2662
2663 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2664   if (Alignment)
2665     return Len / Alignment <= 4;
2666   else
2667     return Len < 32;
2668 }
2669
2670 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
2671                                          uint64_t Len, unsigned Alignment) {
2672   // Make sure we don't bloat code by inlining very large memcpy's.
2673   if (!isMemCpySmall(Len, Alignment))
2674     return false;
2675
2676   int64_t UnscaledOffset = 0;
2677   Address OrigDest = Dest;
2678   Address OrigSrc = Src;
2679
2680   while (Len) {
2681     MVT VT;
2682     if (!Alignment || Alignment >= 8) {
2683       if (Len >= 8)
2684         VT = MVT::i64;
2685       else if (Len >= 4)
2686         VT = MVT::i32;
2687       else if (Len >= 2)
2688         VT = MVT::i16;
2689       else {
2690         VT = MVT::i8;
2691       }
2692     } else {
2693       // Bound based on alignment.
2694       if (Len >= 4 && Alignment == 4)
2695         VT = MVT::i32;
2696       else if (Len >= 2 && Alignment == 2)
2697         VT = MVT::i16;
2698       else {
2699         VT = MVT::i8;
2700       }
2701     }
2702
2703     bool RV;
2704     unsigned ResultReg;
2705     RV = emitLoad(VT, ResultReg, Src);
2706     if (!RV)
2707       return false;
2708
2709     RV = emitStore(VT, ResultReg, Dest);
2710     if (!RV)
2711       return false;
2712
2713     int64_t Size = VT.getSizeInBits() / 8;
2714     Len -= Size;
2715     UnscaledOffset += Size;
2716
2717     // We need to recompute the unscaled offset for each iteration.
2718     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2719     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2720   }
2721
2722   return true;
2723 }
2724
2725 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2726 /// into the user. The condition code will only be updated on success.
2727 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2728                                         const Instruction *I,
2729                                         const Value *Cond) {
2730   if (!isa<ExtractValueInst>(Cond))
2731     return false;
2732
2733   const auto *EV = cast<ExtractValueInst>(Cond);
2734   if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2735     return false;
2736
2737   const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2738   MVT RetVT;
2739   const Function *Callee = II->getCalledFunction();
2740   Type *RetTy =
2741   cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2742   if (!isTypeLegal(RetTy, RetVT))
2743     return false;
2744
2745   if (RetVT != MVT::i32 && RetVT != MVT::i64)
2746     return false;
2747
2748   AArch64CC::CondCode TmpCC;
2749   switch (II->getIntrinsicID()) {
2750     default: return false;
2751     case Intrinsic::sadd_with_overflow:
2752     case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
2753     case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
2754     case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
2755     case Intrinsic::smul_with_overflow:
2756     case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
2757   }
2758
2759   // Check if both instructions are in the same basic block.
2760   if (!isValueAvailable(II))
2761     return false;
2762
2763   // Make sure nothing is in the way
2764   BasicBlock::const_iterator Start = I;
2765   BasicBlock::const_iterator End = II;
2766   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2767     // We only expect extractvalue instructions between the intrinsic and the
2768     // instruction to be selected.
2769     if (!isa<ExtractValueInst>(Itr))
2770       return false;
2771
2772     // Check that the extractvalue operand comes from the intrinsic.
2773     const auto *EVI = cast<ExtractValueInst>(Itr);
2774     if (EVI->getAggregateOperand() != II)
2775       return false;
2776   }
2777
2778   CC = TmpCC;
2779   return true;
2780 }
2781
2782 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2783   // FIXME: Handle more intrinsics.
2784   switch (II->getIntrinsicID()) {
2785   default: return false;
2786   case Intrinsic::frameaddress: {
2787     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2788     MFI->setFrameAddressIsTaken(true);
2789
2790     const AArch64RegisterInfo *RegInfo =
2791         static_cast<const AArch64RegisterInfo *>(
2792             TM.getSubtargetImpl()->getRegisterInfo());
2793     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2794     unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2795     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2796             TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
2797     // Recursively load frame address
2798     // ldr x0, [fp]
2799     // ldr x0, [x0]
2800     // ldr x0, [x0]
2801     // ...
2802     unsigned DestReg;
2803     unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2804     while (Depth--) {
2805       DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
2806                                 SrcReg, /*IsKill=*/true, 0);
2807       assert(DestReg && "Unexpected LDR instruction emission failure.");
2808       SrcReg = DestReg;
2809     }
2810
2811     updateValueMap(II, SrcReg);
2812     return true;
2813   }
2814   case Intrinsic::memcpy:
2815   case Intrinsic::memmove: {
2816     const auto *MTI = cast<MemTransferInst>(II);
2817     // Don't handle volatile.
2818     if (MTI->isVolatile())
2819       return false;
2820
2821     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2822     // we would emit dead code because we don't currently handle memmoves.
2823     bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
2824     if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
2825       // Small memcpy's are common enough that we want to do them without a call
2826       // if possible.
2827       uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
2828       unsigned Alignment = MTI->getAlignment();
2829       if (isMemCpySmall(Len, Alignment)) {
2830         Address Dest, Src;
2831         if (!computeAddress(MTI->getRawDest(), Dest) ||
2832             !computeAddress(MTI->getRawSource(), Src))
2833           return false;
2834         if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2835           return true;
2836       }
2837     }
2838
2839     if (!MTI->getLength()->getType()->isIntegerTy(64))
2840       return false;
2841
2842     if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
2843       // Fast instruction selection doesn't support the special
2844       // address spaces.
2845       return false;
2846
2847     const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
2848     return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
2849   }
2850   case Intrinsic::memset: {
2851     const MemSetInst *MSI = cast<MemSetInst>(II);
2852     // Don't handle volatile.
2853     if (MSI->isVolatile())
2854       return false;
2855
2856     if (!MSI->getLength()->getType()->isIntegerTy(64))
2857       return false;
2858
2859     if (MSI->getDestAddressSpace() > 255)
2860       // Fast instruction selection doesn't support the special
2861       // address spaces.
2862       return false;
2863
2864     return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2865   }
2866   case Intrinsic::sin:
2867   case Intrinsic::cos:
2868   case Intrinsic::pow: {
2869     MVT RetVT;
2870     if (!isTypeLegal(II->getType(), RetVT))
2871       return false;
2872
2873     if (RetVT != MVT::f32 && RetVT != MVT::f64)
2874       return false;
2875
2876     static const RTLIB::Libcall LibCallTable[3][2] = {
2877       { RTLIB::SIN_F32, RTLIB::SIN_F64 },
2878       { RTLIB::COS_F32, RTLIB::COS_F64 },
2879       { RTLIB::POW_F32, RTLIB::POW_F64 }
2880     };
2881     RTLIB::Libcall LC;
2882     bool Is64Bit = RetVT == MVT::f64;
2883     switch (II->getIntrinsicID()) {
2884     default:
2885       llvm_unreachable("Unexpected intrinsic.");
2886     case Intrinsic::sin:
2887       LC = LibCallTable[0][Is64Bit];
2888       break;
2889     case Intrinsic::cos:
2890       LC = LibCallTable[1][Is64Bit];
2891       break;
2892     case Intrinsic::pow:
2893       LC = LibCallTable[2][Is64Bit];
2894       break;
2895     }
2896
2897     ArgListTy Args;
2898     Args.reserve(II->getNumArgOperands());
2899
2900     // Populate the argument list.
2901     for (auto &Arg : II->arg_operands()) {
2902       ArgListEntry Entry;
2903       Entry.Val = Arg;
2904       Entry.Ty = Arg->getType();
2905       Args.push_back(Entry);
2906     }
2907
2908     CallLoweringInfo CLI;
2909     CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
2910                   TLI.getLibcallName(LC), std::move(Args));
2911     if (!lowerCallTo(CLI))
2912       return false;
2913     updateValueMap(II, CLI.ResultReg);
2914     return true;
2915   }
2916   case Intrinsic::trap: {
2917     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
2918         .addImm(1);
2919     return true;
2920   }
2921   case Intrinsic::sqrt: {
2922     Type *RetTy = II->getCalledFunction()->getReturnType();
2923
2924     MVT VT;
2925     if (!isTypeLegal(RetTy, VT))
2926       return false;
2927
2928     unsigned Op0Reg = getRegForValue(II->getOperand(0));
2929     if (!Op0Reg)
2930       return false;
2931     bool Op0IsKill = hasTrivialKill(II->getOperand(0));
2932
2933     unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
2934     if (!ResultReg)
2935       return false;
2936
2937     updateValueMap(II, ResultReg);
2938     return true;
2939   }
2940   case Intrinsic::sadd_with_overflow:
2941   case Intrinsic::uadd_with_overflow:
2942   case Intrinsic::ssub_with_overflow:
2943   case Intrinsic::usub_with_overflow:
2944   case Intrinsic::smul_with_overflow:
2945   case Intrinsic::umul_with_overflow: {
2946     // This implements the basic lowering of the xalu with overflow intrinsics.
2947     const Function *Callee = II->getCalledFunction();
2948     auto *Ty = cast<StructType>(Callee->getReturnType());
2949     Type *RetTy = Ty->getTypeAtIndex(0U);
2950
2951     MVT VT;
2952     if (!isTypeLegal(RetTy, VT))
2953       return false;
2954
2955     if (VT != MVT::i32 && VT != MVT::i64)
2956       return false;
2957
2958     const Value *LHS = II->getArgOperand(0);
2959     const Value *RHS = II->getArgOperand(1);
2960     // Canonicalize immediate to the RHS.
2961     if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2962         isCommutativeIntrinsic(II))
2963       std::swap(LHS, RHS);
2964
2965     unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
2966     AArch64CC::CondCode CC = AArch64CC::Invalid;
2967     switch (II->getIntrinsicID()) {
2968     default: llvm_unreachable("Unexpected intrinsic!");
2969     case Intrinsic::sadd_with_overflow:
2970       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2971       CC = AArch64CC::VS;
2972       break;
2973     case Intrinsic::uadd_with_overflow:
2974       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2975       CC = AArch64CC::HS;
2976       break;
2977     case Intrinsic::ssub_with_overflow:
2978       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2979       CC = AArch64CC::VS;
2980       break;
2981     case Intrinsic::usub_with_overflow:
2982       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2983       CC = AArch64CC::LO;
2984       break;
2985     case Intrinsic::smul_with_overflow: {
2986       CC = AArch64CC::NE;
2987       unsigned LHSReg = getRegForValue(LHS);
2988       if (!LHSReg)
2989         return false;
2990       bool LHSIsKill = hasTrivialKill(LHS);
2991
2992       unsigned RHSReg = getRegForValue(RHS);
2993       if (!RHSReg)
2994         return false;
2995       bool RHSIsKill = hasTrivialKill(RHS);
2996
2997       if (VT == MVT::i32) {
2998         MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2999         unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3000                                        /*IsKill=*/false, 32);
3001         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3002                                             AArch64::sub_32);
3003         ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3004                                               AArch64::sub_32);
3005         emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3006                     AArch64_AM::ASR, 31, /*WantResult=*/false);
3007       } else {
3008         assert(VT == MVT::i64 && "Unexpected value type.");
3009         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3010         unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3011                                         RHSReg, RHSIsKill);
3012         emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3013                     AArch64_AM::ASR, 63, /*WantResult=*/false);
3014       }
3015       break;
3016     }
3017     case Intrinsic::umul_with_overflow: {
3018       CC = AArch64CC::NE;
3019       unsigned LHSReg = getRegForValue(LHS);
3020       if (!LHSReg)
3021         return false;
3022       bool LHSIsKill = hasTrivialKill(LHS);
3023
3024       unsigned RHSReg = getRegForValue(RHS);
3025       if (!RHSReg)
3026         return false;
3027       bool RHSIsKill = hasTrivialKill(RHS);
3028
3029       if (VT == MVT::i32) {
3030         MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3031         emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3032                     /*IsKill=*/false, AArch64_AM::LSR, 32,
3033                     /*WantResult=*/false);
3034         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3035                                             AArch64::sub_32);
3036       } else {
3037         assert(VT == MVT::i64 && "Unexpected value type.");
3038         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3039         unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3040                                         RHSReg, RHSIsKill);
3041         emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3042                     /*IsKill=*/false, /*WantResult=*/false);
3043       }
3044       break;
3045     }
3046     }
3047
3048     if (MulReg) {
3049       ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3050       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3051               TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3052     }
3053
3054     ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3055                                   AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3056                                   /*IsKill=*/true, getInvertedCondCode(CC));
3057     assert((ResultReg1 + 1) == ResultReg2 &&
3058            "Nonconsecutive result registers.");
3059     updateValueMap(II, ResultReg1, 2);
3060     return true;
3061   }
3062   }
3063   return false;
3064 }
3065
3066 bool AArch64FastISel::selectRet(const Instruction *I) {
3067   const ReturnInst *Ret = cast<ReturnInst>(I);
3068   const Function &F = *I->getParent()->getParent();
3069
3070   if (!FuncInfo.CanLowerReturn)
3071     return false;
3072
3073   if (F.isVarArg())
3074     return false;
3075
3076   // Build a list of return value registers.
3077   SmallVector<unsigned, 4> RetRegs;
3078
3079   if (Ret->getNumOperands() > 0) {
3080     CallingConv::ID CC = F.getCallingConv();
3081     SmallVector<ISD::OutputArg, 4> Outs;
3082     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3083
3084     // Analyze operands of the call, assigning locations to each operand.
3085     SmallVector<CCValAssign, 16> ValLocs;
3086     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3087     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3088                                                      : RetCC_AArch64_AAPCS;
3089     CCInfo.AnalyzeReturn(Outs, RetCC);
3090
3091     // Only handle a single return value for now.
3092     if (ValLocs.size() != 1)
3093       return false;
3094
3095     CCValAssign &VA = ValLocs[0];
3096     const Value *RV = Ret->getOperand(0);
3097
3098     // Don't bother handling odd stuff for now.
3099     if ((VA.getLocInfo() != CCValAssign::Full) &&
3100         (VA.getLocInfo() != CCValAssign::BCvt))
3101       return false;
3102
3103     // Only handle register returns for now.
3104     if (!VA.isRegLoc())
3105       return false;
3106
3107     unsigned Reg = getRegForValue(RV);
3108     if (Reg == 0)
3109       return false;
3110
3111     unsigned SrcReg = Reg + VA.getValNo();
3112     unsigned DestReg = VA.getLocReg();
3113     // Avoid a cross-class copy. This is very unlikely.
3114     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3115       return false;
3116
3117     EVT RVEVT = TLI.getValueType(RV->getType());
3118     if (!RVEVT.isSimple())
3119       return false;
3120
3121     // Vectors (of > 1 lane) in big endian need tricky handling.
3122     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3123         !Subtarget->isLittleEndian())
3124       return false;
3125
3126     MVT RVVT = RVEVT.getSimpleVT();
3127     if (RVVT == MVT::f128)
3128       return false;
3129
3130     MVT DestVT = VA.getValVT();
3131     // Special handling for extended integers.
3132     if (RVVT != DestVT) {
3133       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3134         return false;
3135
3136       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3137         return false;
3138
3139       bool IsZExt = Outs[0].Flags.isZExt();
3140       SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3141       if (SrcReg == 0)
3142         return false;
3143     }
3144
3145     // Make the copy.
3146     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3147             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3148
3149     // Add register to return instruction.
3150     RetRegs.push_back(VA.getLocReg());
3151   }
3152
3153   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3154                                     TII.get(AArch64::RET_ReallyLR));
3155   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3156     MIB.addReg(RetRegs[i], RegState::Implicit);
3157   return true;
3158 }
3159
3160 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3161   Type *DestTy = I->getType();
3162   Value *Op = I->getOperand(0);
3163   Type *SrcTy = Op->getType();
3164
3165   EVT SrcEVT = TLI.getValueType(SrcTy, true);
3166   EVT DestEVT = TLI.getValueType(DestTy, true);
3167   if (!SrcEVT.isSimple())
3168     return false;
3169   if (!DestEVT.isSimple())
3170     return false;
3171
3172   MVT SrcVT = SrcEVT.getSimpleVT();
3173   MVT DestVT = DestEVT.getSimpleVT();
3174
3175   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3176       SrcVT != MVT::i8)
3177     return false;
3178   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3179       DestVT != MVT::i1)
3180     return false;
3181
3182   unsigned SrcReg = getRegForValue(Op);
3183   if (!SrcReg)
3184     return false;
3185   bool SrcIsKill = hasTrivialKill(Op);
3186
3187   // If we're truncating from i64 to a smaller non-legal type then generate an
3188   // AND. Otherwise, we know the high bits are undefined and a truncate only
3189   // generate a COPY. We cannot mark the source register also as result
3190   // register, because this can incorrectly transfer the kill flag onto the
3191   // source register.
3192   unsigned ResultReg;
3193   if (SrcVT == MVT::i64) {
3194     uint64_t Mask = 0;
3195     switch (DestVT.SimpleTy) {
3196     default:
3197       // Trunc i64 to i32 is handled by the target-independent fast-isel.
3198       return false;
3199     case MVT::i1:
3200       Mask = 0x1;
3201       break;
3202     case MVT::i8:
3203       Mask = 0xff;
3204       break;
3205     case MVT::i16:
3206       Mask = 0xffff;
3207       break;
3208     }
3209     // Issue an extract_subreg to get the lower 32-bits.
3210     unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3211                                                 AArch64::sub_32);
3212     // Create the AND instruction which performs the actual truncation.
3213     ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3214     assert(ResultReg && "Unexpected AND instruction emission failure.");
3215   } else {
3216     ResultReg = createResultReg(&AArch64::GPR32RegClass);
3217     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3218             TII.get(TargetOpcode::COPY), ResultReg)
3219         .addReg(SrcReg, getKillRegState(SrcIsKill));
3220   }
3221
3222   updateValueMap(I, ResultReg);
3223   return true;
3224 }
3225
3226 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3227   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3228           DestVT == MVT::i64) &&
3229          "Unexpected value type.");
3230   // Handle i8 and i16 as i32.
3231   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3232     DestVT = MVT::i32;
3233
3234   if (IsZExt) {
3235     unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3236     assert(ResultReg && "Unexpected AND instruction emission failure.");
3237     if (DestVT == MVT::i64) {
3238       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
3239       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
3240       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3241       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3242               TII.get(AArch64::SUBREG_TO_REG), Reg64)
3243           .addImm(0)
3244           .addReg(ResultReg)
3245           .addImm(AArch64::sub_32);
3246       ResultReg = Reg64;
3247     }
3248     return ResultReg;
3249   } else {
3250     if (DestVT == MVT::i64) {
3251       // FIXME: We're SExt i1 to i64.
3252       return 0;
3253     }
3254     return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3255                             /*TODO:IsKill=*/false, 0, 0);
3256   }
3257 }
3258
3259 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3260                                       unsigned Op1, bool Op1IsKill) {
3261   unsigned Opc, ZReg;
3262   switch (RetVT.SimpleTy) {
3263   default: return 0;
3264   case MVT::i8:
3265   case MVT::i16:
3266   case MVT::i32:
3267     RetVT = MVT::i32;
3268     Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3269   case MVT::i64:
3270     Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3271   }
3272
3273   const TargetRegisterClass *RC =
3274       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3275   return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3276                           /*IsKill=*/ZReg, true);
3277 }
3278
3279 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3280                                         unsigned Op1, bool Op1IsKill) {
3281   if (RetVT != MVT::i64)
3282     return 0;
3283
3284   return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3285                           Op0, Op0IsKill, Op1, Op1IsKill,
3286                           AArch64::XZR, /*IsKill=*/true);
3287 }
3288
3289 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3290                                         unsigned Op1, bool Op1IsKill) {
3291   if (RetVT != MVT::i64)
3292     return 0;
3293
3294   return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3295                           Op0, Op0IsKill, Op1, Op1IsKill,
3296                           AArch64::XZR, /*IsKill=*/true);
3297 }
3298
3299 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3300                                      unsigned Op1Reg, bool Op1IsKill) {
3301   unsigned Opc = 0;
3302   bool NeedTrunc = false;
3303   uint64_t Mask = 0;
3304   switch (RetVT.SimpleTy) {
3305   default: return 0;
3306   case MVT::i8:  Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff;   break;
3307   case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3308   case MVT::i32: Opc = AArch64::LSLVWr;                                  break;
3309   case MVT::i64: Opc = AArch64::LSLVXr;                                  break;
3310   }
3311
3312   const TargetRegisterClass *RC =
3313       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3314   if (NeedTrunc) {
3315     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3316     Op1IsKill = true;
3317   }
3318   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3319                                        Op1IsKill);
3320   if (NeedTrunc)
3321     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3322   return ResultReg;
3323 }
3324
3325 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3326                                      bool Op0IsKill, uint64_t Shift,
3327                                      bool IsZext) {
3328   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3329          "Unexpected source/return type pair.");
3330   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3331           SrcVT == MVT::i64) && "Unexpected source value type.");
3332   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3333           RetVT == MVT::i64) && "Unexpected return value type.");
3334
3335   bool Is64Bit = (RetVT == MVT::i64);
3336   unsigned RegSize = Is64Bit ? 64 : 32;
3337   unsigned DstBits = RetVT.getSizeInBits();
3338   unsigned SrcBits = SrcVT.getSizeInBits();
3339
3340   // Don't deal with undefined shifts.
3341   if (Shift >= DstBits)
3342     return 0;
3343
3344   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3345   // {S|U}BFM Wd, Wn, #r, #s
3346   // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3347
3348   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3349   // %2 = shl i16 %1, 4
3350   // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3351   // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3352   // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3353   // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3354
3355   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3356   // %2 = shl i16 %1, 8
3357   // Wd<32+7-24,32-24> = Wn<7:0>
3358   // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3359   // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3360   // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3361
3362   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3363   // %2 = shl i16 %1, 12
3364   // Wd<32+3-20,32-20> = Wn<3:0>
3365   // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3366   // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3367   // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3368
3369   unsigned ImmR = RegSize - Shift;
3370   // Limit the width to the length of the source type.
3371   unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3372   static const unsigned OpcTable[2][2] = {
3373     {AArch64::SBFMWri, AArch64::SBFMXri},
3374     {AArch64::UBFMWri, AArch64::UBFMXri}
3375   };
3376   unsigned Opc = OpcTable[IsZext][Is64Bit];
3377   const TargetRegisterClass *RC =
3378       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3379   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3380     unsigned TmpReg = MRI.createVirtualRegister(RC);
3381     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3382             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3383         .addImm(0)
3384         .addReg(Op0, getKillRegState(Op0IsKill))
3385         .addImm(AArch64::sub_32);
3386     Op0 = TmpReg;
3387     Op0IsKill = true;
3388   }
3389   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3390 }
3391
3392 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3393                                      unsigned Op1Reg, bool Op1IsKill) {
3394   unsigned Opc = 0;
3395   bool NeedTrunc = false;
3396   uint64_t Mask = 0;
3397   switch (RetVT.SimpleTy) {
3398   default: return 0;
3399   case MVT::i8:  Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff;   break;
3400   case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3401   case MVT::i32: Opc = AArch64::LSRVWr; break;
3402   case MVT::i64: Opc = AArch64::LSRVXr; break;
3403   }
3404
3405   const TargetRegisterClass *RC =
3406       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3407   if (NeedTrunc) {
3408     Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3409     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3410     Op0IsKill = Op1IsKill = true;
3411   }
3412   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3413                                        Op1IsKill);
3414   if (NeedTrunc)
3415     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3416   return ResultReg;
3417 }
3418
3419 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3420                                      bool Op0IsKill, uint64_t Shift,
3421                                      bool IsZExt) {
3422   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3423          "Unexpected source/return type pair.");
3424   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3425           SrcVT == MVT::i64) && "Unexpected source value type.");
3426   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3427           RetVT == MVT::i64) && "Unexpected return value type.");
3428
3429   bool Is64Bit = (RetVT == MVT::i64);
3430   unsigned RegSize = Is64Bit ? 64 : 32;
3431   unsigned DstBits = RetVT.getSizeInBits();
3432   unsigned SrcBits = SrcVT.getSizeInBits();
3433
3434   // Don't deal with undefined shifts.
3435   if (Shift >= DstBits)
3436     return 0;
3437
3438   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3439   // {S|U}BFM Wd, Wn, #r, #s
3440   // Wd<s-r:0> = Wn<s:r> when r <= s
3441
3442   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3443   // %2 = lshr i16 %1, 4
3444   // Wd<7-4:0> = Wn<7:4>
3445   // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3446   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3447   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3448
3449   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3450   // %2 = lshr i16 %1, 8
3451   // Wd<7-7,0> = Wn<7:7>
3452   // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3453   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3454   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3455
3456   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3457   // %2 = lshr i16 %1, 12
3458   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3459   // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3460   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3461   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3462
3463   if (Shift >= SrcBits && IsZExt)
3464     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3465
3466   // It is not possible to fold a sign-extend into the LShr instruction. In this
3467   // case emit a sign-extend.
3468   if (!IsZExt) {
3469     Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3470     if (!Op0)
3471       return 0;
3472     Op0IsKill = true;
3473     SrcVT = RetVT;
3474     SrcBits = SrcVT.getSizeInBits();
3475     IsZExt = true;
3476   }
3477
3478   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3479   unsigned ImmS = SrcBits - 1;
3480   static const unsigned OpcTable[2][2] = {
3481     {AArch64::SBFMWri, AArch64::SBFMXri},
3482     {AArch64::UBFMWri, AArch64::UBFMXri}
3483   };
3484   unsigned Opc = OpcTable[IsZExt][Is64Bit];
3485   const TargetRegisterClass *RC =
3486       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3487   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3488     unsigned TmpReg = MRI.createVirtualRegister(RC);
3489     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3490             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3491         .addImm(0)
3492         .addReg(Op0, getKillRegState(Op0IsKill))
3493         .addImm(AArch64::sub_32);
3494     Op0 = TmpReg;
3495     Op0IsKill = true;
3496   }
3497   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3498 }
3499
3500 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3501                                      unsigned Op1Reg, bool Op1IsKill) {
3502   unsigned Opc = 0;
3503   bool NeedTrunc = false;
3504   uint64_t Mask = 0;
3505   switch (RetVT.SimpleTy) {
3506   default: return 0;
3507   case MVT::i8:  Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff;   break;
3508   case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3509   case MVT::i32: Opc = AArch64::ASRVWr;                                  break;
3510   case MVT::i64: Opc = AArch64::ASRVXr;                                  break;
3511   }
3512
3513   const TargetRegisterClass *RC =
3514       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3515   if (NeedTrunc) {
3516     Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3517     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3518     Op0IsKill = Op1IsKill = true;
3519   }
3520   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3521                                        Op1IsKill);
3522   if (NeedTrunc)
3523     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3524   return ResultReg;
3525 }
3526
3527 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3528                                      bool Op0IsKill, uint64_t Shift,
3529                                      bool IsZExt) {
3530   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3531          "Unexpected source/return type pair.");
3532   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3533           SrcVT == MVT::i64) && "Unexpected source value type.");
3534   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3535           RetVT == MVT::i64) && "Unexpected return value type.");
3536
3537   bool Is64Bit = (RetVT == MVT::i64);
3538   unsigned RegSize = Is64Bit ? 64 : 32;
3539   unsigned DstBits = RetVT.getSizeInBits();
3540   unsigned SrcBits = SrcVT.getSizeInBits();
3541
3542   // Don't deal with undefined shifts.
3543   if (Shift >= DstBits)
3544     return 0;
3545
3546   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3547   // {S|U}BFM Wd, Wn, #r, #s
3548   // Wd<s-r:0> = Wn<s:r> when r <= s
3549
3550   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3551   // %2 = ashr i16 %1, 4
3552   // Wd<7-4:0> = Wn<7:4>
3553   // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3554   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3555   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3556
3557   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3558   // %2 = ashr i16 %1, 8
3559   // Wd<7-7,0> = Wn<7:7>
3560   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3561   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3562   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3563
3564   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3565   // %2 = ashr i16 %1, 12
3566   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3567   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3568   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3569   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3570
3571   if (Shift >= SrcBits && IsZExt)
3572     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3573
3574   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3575   unsigned ImmS = SrcBits - 1;
3576   static const unsigned OpcTable[2][2] = {
3577     {AArch64::SBFMWri, AArch64::SBFMXri},
3578     {AArch64::UBFMWri, AArch64::UBFMXri}
3579   };
3580   unsigned Opc = OpcTable[IsZExt][Is64Bit];
3581   const TargetRegisterClass *RC =
3582       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3583   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3584     unsigned TmpReg = MRI.createVirtualRegister(RC);
3585     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3586             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3587         .addImm(0)
3588         .addReg(Op0, getKillRegState(Op0IsKill))
3589         .addImm(AArch64::sub_32);
3590     Op0 = TmpReg;
3591     Op0IsKill = true;
3592   }
3593   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3594 }
3595
3596 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3597                                      bool IsZExt) {
3598   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3599
3600   // FastISel does not have plumbing to deal with extensions where the SrcVT or
3601   // DestVT are odd things, so test to make sure that they are both types we can
3602   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3603   // bail out to SelectionDAG.
3604   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3605        (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3606       ((SrcVT !=  MVT::i1) && (SrcVT !=  MVT::i8) &&
3607        (SrcVT !=  MVT::i16) && (SrcVT !=  MVT::i32)))
3608     return 0;
3609
3610   unsigned Opc;
3611   unsigned Imm = 0;
3612
3613   switch (SrcVT.SimpleTy) {
3614   default:
3615     return 0;
3616   case MVT::i1:
3617     return emiti1Ext(SrcReg, DestVT, IsZExt);
3618   case MVT::i8:
3619     if (DestVT == MVT::i64)
3620       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3621     else
3622       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3623     Imm = 7;
3624     break;
3625   case MVT::i16:
3626     if (DestVT == MVT::i64)
3627       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3628     else
3629       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3630     Imm = 15;
3631     break;
3632   case MVT::i32:
3633     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
3634     Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3635     Imm = 31;
3636     break;
3637   }
3638
3639   // Handle i8 and i16 as i32.
3640   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3641     DestVT = MVT::i32;
3642   else if (DestVT == MVT::i64) {
3643     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3644     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3645             TII.get(AArch64::SUBREG_TO_REG), Src64)
3646         .addImm(0)
3647         .addReg(SrcReg)
3648         .addImm(AArch64::sub_32);
3649     SrcReg = Src64;
3650   }
3651
3652   const TargetRegisterClass *RC =
3653       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3654   return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
3655 }
3656
3657 bool AArch64FastISel::selectIntExt(const Instruction *I) {
3658   // On ARM, in general, integer casts don't involve legal types; this code
3659   // handles promotable integers.  The high bits for a type smaller than
3660   // the register size are assumed to be undefined.
3661   Type *DestTy = I->getType();
3662   Value *Src = I->getOperand(0);
3663   Type *SrcTy = Src->getType();
3664
3665   unsigned SrcReg = getRegForValue(Src);
3666   if (!SrcReg)
3667     return false;
3668
3669   EVT SrcEVT = TLI.getValueType(SrcTy, true);
3670   EVT DestEVT = TLI.getValueType(DestTy, true);
3671   if (!SrcEVT.isSimple())
3672     return false;
3673   if (!DestEVT.isSimple())
3674     return false;
3675
3676   MVT SrcVT = SrcEVT.getSimpleVT();
3677   MVT DestVT = DestEVT.getSimpleVT();
3678   unsigned ResultReg = 0;
3679
3680   bool IsZExt = isa<ZExtInst>(I);
3681   // Check if it is an argument and if it is already zero/sign-extended.
3682   if (const auto *Arg = dyn_cast<Argument>(Src)) {
3683     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
3684       if (DestVT == MVT::i64) {
3685         ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
3686         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3687                 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3688           .addImm(0)
3689           .addReg(SrcReg)
3690           .addImm(AArch64::sub_32);
3691       } else
3692         ResultReg = SrcReg;
3693     }
3694   }
3695
3696   if (!ResultReg)
3697     ResultReg = emitIntExt(SrcVT, SrcReg, DestVT, IsZExt);
3698
3699   if (!ResultReg)
3700     return false;
3701
3702   updateValueMap(I, ResultReg);
3703   return true;
3704 }
3705
3706 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
3707   EVT DestEVT = TLI.getValueType(I->getType(), true);
3708   if (!DestEVT.isSimple())
3709     return false;
3710
3711   MVT DestVT = DestEVT.getSimpleVT();
3712   if (DestVT != MVT::i64 && DestVT != MVT::i32)
3713     return false;
3714
3715   unsigned DivOpc;
3716   bool Is64bit = (DestVT == MVT::i64);
3717   switch (ISDOpcode) {
3718   default:
3719     return false;
3720   case ISD::SREM:
3721     DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
3722     break;
3723   case ISD::UREM:
3724     DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
3725     break;
3726   }
3727   unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
3728   unsigned Src0Reg = getRegForValue(I->getOperand(0));
3729   if (!Src0Reg)
3730     return false;
3731   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3732
3733   unsigned Src1Reg = getRegForValue(I->getOperand(1));
3734   if (!Src1Reg)
3735     return false;
3736   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3737
3738   const TargetRegisterClass *RC =
3739       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3740   unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
3741                                      Src1Reg, /*IsKill=*/false);
3742   assert(QuotReg && "Unexpected DIV instruction emission failure.");
3743   // The remainder is computed as numerator - (quotient * denominator) using the
3744   // MSUB instruction.
3745   unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
3746                                         Src1Reg, Src1IsKill, Src0Reg,
3747                                         Src0IsKill);
3748   updateValueMap(I, ResultReg);
3749   return true;
3750 }
3751
3752 bool AArch64FastISel::selectMul(const Instruction *I) {
3753   MVT VT;
3754   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
3755     return false;
3756
3757   if (VT.isVector())
3758     return selectBinaryOp(I, ISD::MUL);
3759
3760   const Value *Src0 = I->getOperand(0);
3761   const Value *Src1 = I->getOperand(1);
3762   if (const auto *C = dyn_cast<ConstantInt>(Src0))
3763     if (C->getValue().isPowerOf2())
3764       std::swap(Src0, Src1);
3765
3766   // Try to simplify to a shift instruction.
3767   if (const auto *C = dyn_cast<ConstantInt>(Src1))
3768     if (C->getValue().isPowerOf2()) {
3769       uint64_t ShiftVal = C->getValue().logBase2();
3770       MVT SrcVT = VT;
3771       bool IsZExt = true;
3772       if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
3773         MVT VT;
3774         if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
3775           SrcVT = VT;
3776           IsZExt = true;
3777           Src0 = ZExt->getOperand(0);
3778         }
3779       } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
3780         MVT VT;
3781         if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
3782           SrcVT = VT;
3783           IsZExt = false;
3784           Src0 = SExt->getOperand(0);
3785         }
3786       }
3787
3788       unsigned Src0Reg = getRegForValue(Src0);
3789       if (!Src0Reg)
3790         return false;
3791       bool Src0IsKill = hasTrivialKill(Src0);
3792
3793       unsigned ResultReg =
3794           emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
3795
3796       if (ResultReg) {
3797         updateValueMap(I, ResultReg);
3798         return true;
3799       }
3800     }
3801
3802   unsigned Src0Reg = getRegForValue(I->getOperand(0));
3803   if (!Src0Reg)
3804     return false;
3805   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3806
3807   unsigned Src1Reg = getRegForValue(I->getOperand(1));
3808   if (!Src1Reg)
3809     return false;
3810   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3811
3812   unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
3813
3814   if (!ResultReg)
3815     return false;
3816
3817   updateValueMap(I, ResultReg);
3818   return true;
3819 }
3820
3821 bool AArch64FastISel::selectShift(const Instruction *I) {
3822   MVT RetVT;
3823   if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
3824     return false;
3825
3826   if (RetVT.isVector())
3827     return selectOperator(I, I->getOpcode());
3828
3829   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
3830     unsigned ResultReg = 0;
3831     uint64_t ShiftVal = C->getZExtValue();
3832     MVT SrcVT = RetVT;
3833     bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
3834     const Value *Op0 = I->getOperand(0);
3835     if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
3836       MVT TmpVT;
3837       if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
3838         SrcVT = TmpVT;
3839         IsZExt = true;
3840         Op0 = ZExt->getOperand(0);
3841       }
3842     } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
3843       MVT TmpVT;
3844       if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
3845         SrcVT = TmpVT;
3846         IsZExt = false;
3847         Op0 = SExt->getOperand(0);
3848       }
3849     }
3850
3851     unsigned Op0Reg = getRegForValue(Op0);
3852     if (!Op0Reg)
3853       return false;
3854     bool Op0IsKill = hasTrivialKill(Op0);
3855
3856     switch (I->getOpcode()) {
3857     default: llvm_unreachable("Unexpected instruction.");
3858     case Instruction::Shl:
3859       ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3860       break;
3861     case Instruction::AShr:
3862       ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3863       break;
3864     case Instruction::LShr:
3865       ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3866       break;
3867     }
3868     if (!ResultReg)
3869       return false;
3870
3871     updateValueMap(I, ResultReg);
3872     return true;
3873   }
3874
3875   unsigned Op0Reg = getRegForValue(I->getOperand(0));
3876   if (!Op0Reg)
3877     return false;
3878   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3879
3880   unsigned Op1Reg = getRegForValue(I->getOperand(1));
3881   if (!Op1Reg)
3882     return false;
3883   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
3884
3885   unsigned ResultReg = 0;
3886   switch (I->getOpcode()) {
3887   default: llvm_unreachable("Unexpected instruction.");
3888   case Instruction::Shl:
3889     ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3890     break;
3891   case Instruction::AShr:
3892     ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3893     break;
3894   case Instruction::LShr:
3895     ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3896     break;
3897   }
3898
3899   if (!ResultReg)
3900     return false;
3901
3902   updateValueMap(I, ResultReg);
3903   return true;
3904 }
3905
3906 bool AArch64FastISel::selectBitCast(const Instruction *I) {
3907   MVT RetVT, SrcVT;
3908
3909   if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
3910     return false;
3911   if (!isTypeLegal(I->getType(), RetVT))
3912     return false;
3913
3914   unsigned Opc;
3915   if (RetVT == MVT::f32 && SrcVT == MVT::i32)
3916     Opc = AArch64::FMOVWSr;
3917   else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
3918     Opc = AArch64::FMOVXDr;
3919   else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
3920     Opc = AArch64::FMOVSWr;
3921   else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
3922     Opc = AArch64::FMOVDXr;
3923   else
3924     return false;
3925
3926   const TargetRegisterClass *RC = nullptr;
3927   switch (RetVT.SimpleTy) {
3928   default: llvm_unreachable("Unexpected value type.");
3929   case MVT::i32: RC = &AArch64::GPR32RegClass; break;
3930   case MVT::i64: RC = &AArch64::GPR64RegClass; break;
3931   case MVT::f32: RC = &AArch64::FPR32RegClass; break;
3932   case MVT::f64: RC = &AArch64::FPR64RegClass; break;
3933   }
3934   unsigned Op0Reg = getRegForValue(I->getOperand(0));
3935   if (!Op0Reg)
3936     return false;
3937   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3938   unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
3939
3940   if (!ResultReg)
3941     return false;
3942
3943   updateValueMap(I, ResultReg);
3944   return true;
3945 }
3946
3947 bool AArch64FastISel::selectFRem(const Instruction *I) {
3948   MVT RetVT;
3949   if (!isTypeLegal(I->getType(), RetVT))
3950     return false;
3951
3952   RTLIB::Libcall LC;
3953   switch (RetVT.SimpleTy) {
3954   default:
3955     return false;
3956   case MVT::f32:
3957     LC = RTLIB::REM_F32;
3958     break;
3959   case MVT::f64:
3960     LC = RTLIB::REM_F64;
3961     break;
3962   }
3963
3964   ArgListTy Args;
3965   Args.reserve(I->getNumOperands());
3966
3967   // Populate the argument list.
3968   for (auto &Arg : I->operands()) {
3969     ArgListEntry Entry;
3970     Entry.Val = Arg;
3971     Entry.Ty = Arg->getType();
3972     Args.push_back(Entry);
3973   }
3974
3975   CallLoweringInfo CLI;
3976   CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
3977                 TLI.getLibcallName(LC), std::move(Args));
3978   if (!lowerCallTo(CLI))
3979     return false;
3980   updateValueMap(I, CLI.ResultReg);
3981   return true;
3982 }
3983
3984 bool AArch64FastISel::selectSDiv(const Instruction *I) {
3985   MVT VT;
3986   if (!isTypeLegal(I->getType(), VT))
3987     return false;
3988
3989   if (!isa<ConstantInt>(I->getOperand(1)))
3990     return selectBinaryOp(I, ISD::SDIV);
3991
3992   const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
3993   if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
3994       !(C.isPowerOf2() || (-C).isPowerOf2()))
3995     return selectBinaryOp(I, ISD::SDIV);
3996
3997   unsigned Lg2 = C.countTrailingZeros();
3998   unsigned Src0Reg = getRegForValue(I->getOperand(0));
3999   if (!Src0Reg)
4000     return false;
4001   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4002
4003   if (cast<BinaryOperator>(I)->isExact()) {
4004     unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4005     if (!ResultReg)
4006       return false;
4007     updateValueMap(I, ResultReg);
4008     return true;
4009   }
4010
4011   unsigned Pow2MinusOne = (1 << Lg2) - 1;
4012   unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4013                                   /*IsKill=*/false, Pow2MinusOne);
4014   if (!AddReg)
4015     return false;
4016
4017   // (Src0 < 0) ? Pow2 - 1 : 0;
4018   if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4019     return false;
4020
4021   unsigned SelectOpc;
4022   const TargetRegisterClass *RC;
4023   if (VT == MVT::i64) {
4024     SelectOpc = AArch64::CSELXr;
4025     RC = &AArch64::GPR64RegClass;
4026   } else {
4027     SelectOpc = AArch64::CSELWr;
4028     RC = &AArch64::GPR32RegClass;
4029   }
4030   unsigned SelectReg =
4031       fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4032                        Src0IsKill, AArch64CC::LT);
4033   if (!SelectReg)
4034     return false;
4035
4036   // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4037   // negate the result.
4038   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4039   unsigned ResultReg;
4040   if (C.isNegative())
4041     ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4042                               SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4043   else
4044     ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4045
4046   if (!ResultReg)
4047     return false;
4048
4049   updateValueMap(I, ResultReg);
4050   return true;
4051 }
4052
4053 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4054   switch (I->getOpcode()) {
4055   default:
4056     break;
4057   case Instruction::Add:
4058   case Instruction::Sub:
4059     return selectAddSub(I);
4060   case Instruction::Mul:
4061     return selectMul(I);
4062   case Instruction::SDiv:
4063     return selectSDiv(I);
4064   case Instruction::SRem:
4065     if (!selectBinaryOp(I, ISD::SREM))
4066       return selectRem(I, ISD::SREM);
4067     return true;
4068   case Instruction::URem:
4069     if (!selectBinaryOp(I, ISD::UREM))
4070       return selectRem(I, ISD::UREM);
4071     return true;
4072   case Instruction::Shl:
4073   case Instruction::LShr:
4074   case Instruction::AShr:
4075     return selectShift(I);
4076   case Instruction::And:
4077   case Instruction::Or:
4078   case Instruction::Xor:
4079     return selectLogicalOp(I);
4080   case Instruction::Br:
4081     return selectBranch(I);
4082   case Instruction::IndirectBr:
4083     return selectIndirectBr(I);
4084   case Instruction::BitCast:
4085     if (!FastISel::selectBitCast(I))
4086       return selectBitCast(I);
4087     return true;
4088   case Instruction::FPToSI:
4089     if (!selectCast(I, ISD::FP_TO_SINT))
4090       return selectFPToInt(I, /*Signed=*/true);
4091     return true;
4092   case Instruction::FPToUI:
4093     return selectFPToInt(I, /*Signed=*/false);
4094   case Instruction::ZExt:
4095     if (!selectCast(I, ISD::ZERO_EXTEND))
4096       return selectIntExt(I);
4097     return true;
4098   case Instruction::SExt:
4099     if (!selectCast(I, ISD::SIGN_EXTEND))
4100       return selectIntExt(I);
4101     return true;
4102   case Instruction::Trunc:
4103     if (!selectCast(I, ISD::TRUNCATE))
4104       return selectTrunc(I);
4105     return true;
4106   case Instruction::FPExt:
4107     return selectFPExt(I);
4108   case Instruction::FPTrunc:
4109     return selectFPTrunc(I);
4110   case Instruction::SIToFP:
4111     if (!selectCast(I, ISD::SINT_TO_FP))
4112       return selectIntToFP(I, /*Signed=*/true);
4113     return true;
4114   case Instruction::UIToFP:
4115     return selectIntToFP(I, /*Signed=*/false);
4116   case Instruction::Load:
4117     return selectLoad(I);
4118   case Instruction::Store:
4119     return selectStore(I);
4120   case Instruction::FCmp:
4121   case Instruction::ICmp:
4122     return selectCmp(I);
4123   case Instruction::Select:
4124     return selectSelect(I);
4125   case Instruction::Ret:
4126     return selectRet(I);
4127   case Instruction::FRem:
4128     return selectFRem(I);
4129   }
4130
4131   // fall-back to target-independent instruction selection.
4132   return selectOperator(I, I->getOpcode());
4133   // Silence warnings.
4134   (void)&CC_AArch64_DarwinPCS_VarArg;
4135 }
4136
4137 namespace llvm {
4138 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4139                                         const TargetLibraryInfo *LibInfo) {
4140   return new AArch64FastISel(FuncInfo, LibInfo);
4141 }
4142 }