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