da69735c8f1028a05f68a1f2c92ad04608151ed5
[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 /// \brief Check if the comparison against zero and the following branch can be
1677 /// folded into a single instruction (CBZ or CBNZ).
1678 static bool canFoldZeroIntoBranch(const CmpInst *CI) {
1679   CmpInst::Predicate Predicate = CI->getPredicate();
1680   if ((Predicate != CmpInst::ICMP_EQ) && (Predicate != CmpInst::ICMP_NE))
1681     return false;
1682
1683   Type *Ty = CI->getOperand(0)->getType();
1684   if (!Ty->isIntegerTy())
1685     return false;
1686
1687   unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
1688   if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
1689     return false;
1690
1691   if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(0)))
1692     if (C->isNullValue())
1693       return true;
1694
1695   if (const auto *C = dyn_cast<ConstantInt>(CI->getOperand(1)))
1696     if (C->isNullValue())
1697       return true;
1698
1699   return false;
1700 }
1701
1702 bool AArch64FastISel::selectBranch(const Instruction *I) {
1703   const BranchInst *BI = cast<BranchInst>(I);
1704   if (BI->isUnconditional()) {
1705     MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
1706     fastEmitBranch(MSucc, BI->getDebugLoc());
1707     return true;
1708   }
1709
1710   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1711   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1712
1713   AArch64CC::CondCode CC = AArch64CC::NE;
1714   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1715     if (CI->hasOneUse() && isValueAvailable(CI)) {
1716       // Try to optimize or fold the cmp.
1717       CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1718       switch (Predicate) {
1719       default:
1720         break;
1721       case CmpInst::FCMP_FALSE:
1722         fastEmitBranch(FBB, DbgLoc);
1723         return true;
1724       case CmpInst::FCMP_TRUE:
1725         fastEmitBranch(TBB, DbgLoc);
1726         return true;
1727       }
1728
1729       // Try to take advantage of fallthrough opportunities.
1730       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1731         std::swap(TBB, FBB);
1732         Predicate = CmpInst::getInversePredicate(Predicate);
1733       }
1734
1735       // Try to optimize comparisons against zero.
1736       if (canFoldZeroIntoBranch(CI)) {
1737         const Value *LHS = CI->getOperand(0);
1738         const Value *RHS = CI->getOperand(1);
1739
1740         // Canonicalize zero values to the RHS.
1741         if (const auto *C = dyn_cast<ConstantInt>(LHS))
1742           if (C->isNullValue())
1743             std::swap(LHS, RHS);
1744
1745         static const unsigned OpcTable[2][2] = {
1746           {AArch64::CBZW,  AArch64::CBZX }, {AArch64::CBNZW, AArch64::CBNZX}
1747         };
1748         bool IsCmpNE = Predicate == CmpInst::ICMP_NE;
1749         bool Is64Bit = LHS->getType()->isIntegerTy(64);
1750         unsigned Opc = OpcTable[IsCmpNE][Is64Bit];
1751
1752         unsigned SrcReg = getRegForValue(LHS);
1753         if (!SrcReg)
1754           return false;
1755         bool SrcIsKill = hasTrivialKill(LHS);
1756
1757         // Emit the combined compare and branch instruction.
1758         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1759             .addReg(SrcReg, getKillRegState(SrcIsKill))
1760             .addMBB(TBB);
1761
1762         // Obtain the branch weight and add the TrueBB to the successor list.
1763         uint32_t BranchWeight = 0;
1764         if (FuncInfo.BPI)
1765           BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1766                                                      TBB->getBasicBlock());
1767         FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1768
1769         fastEmitBranch(FBB, DbgLoc);
1770         return true;
1771       }
1772
1773       // Emit the cmp.
1774       if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1775         return false;
1776
1777       // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
1778       // instruction.
1779       CC = getCompareCC(Predicate);
1780       AArch64CC::CondCode ExtraCC = AArch64CC::AL;
1781       switch (Predicate) {
1782       default:
1783         break;
1784       case CmpInst::FCMP_UEQ:
1785         ExtraCC = AArch64CC::EQ;
1786         CC = AArch64CC::VS;
1787         break;
1788       case CmpInst::FCMP_ONE:
1789         ExtraCC = AArch64CC::MI;
1790         CC = AArch64CC::GT;
1791         break;
1792       }
1793       assert((CC != AArch64CC::AL) && "Unexpected condition code.");
1794
1795       // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
1796       if (ExtraCC != AArch64CC::AL) {
1797         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1798             .addImm(ExtraCC)
1799             .addMBB(TBB);
1800       }
1801
1802       // Emit the branch.
1803       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1804           .addImm(CC)
1805           .addMBB(TBB);
1806
1807       // Obtain the branch weight and add the TrueBB to the successor list.
1808       uint32_t BranchWeight = 0;
1809       if (FuncInfo.BPI)
1810         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1811                                                   TBB->getBasicBlock());
1812       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1813
1814       fastEmitBranch(FBB, DbgLoc);
1815       return true;
1816     }
1817   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1818     MVT SrcVT;
1819     if (TI->hasOneUse() && isValueAvailable(TI) &&
1820         isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
1821       unsigned CondReg = getRegForValue(TI->getOperand(0));
1822       if (!CondReg)
1823         return false;
1824       bool CondIsKill = hasTrivialKill(TI->getOperand(0));
1825
1826       // Issue an extract_subreg to get the lower 32-bits.
1827       if (SrcVT == MVT::i64) {
1828         CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
1829                                              AArch64::sub_32);
1830         CondIsKill = true;
1831       }
1832
1833       unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
1834       assert(ANDReg && "Unexpected AND instruction emission failure.");
1835       emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
1836
1837       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1838         std::swap(TBB, FBB);
1839         CC = AArch64CC::EQ;
1840       }
1841       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1842           .addImm(CC)
1843           .addMBB(TBB);
1844
1845       // Obtain the branch weight and add the TrueBB to the successor list.
1846       uint32_t BranchWeight = 0;
1847       if (FuncInfo.BPI)
1848         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1849                                                   TBB->getBasicBlock());
1850       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1851
1852       fastEmitBranch(FBB, DbgLoc);
1853       return true;
1854     }
1855   } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
1856     uint64_t Imm = CI->getZExtValue();
1857     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1858     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
1859         .addMBB(Target);
1860
1861     // Obtain the branch weight and add the target to the successor list.
1862     uint32_t BranchWeight = 0;
1863     if (FuncInfo.BPI)
1864       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1865                                                  Target->getBasicBlock());
1866     FuncInfo.MBB->addSuccessor(Target, BranchWeight);
1867     return true;
1868   } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
1869     // Fake request the condition, otherwise the intrinsic might be completely
1870     // optimized away.
1871     unsigned CondReg = getRegForValue(BI->getCondition());
1872     if (!CondReg)
1873       return false;
1874
1875     // Emit the branch.
1876     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1877       .addImm(CC)
1878       .addMBB(TBB);
1879
1880     // Obtain the branch weight and add the TrueBB to the successor list.
1881     uint32_t BranchWeight = 0;
1882     if (FuncInfo.BPI)
1883       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1884                                                  TBB->getBasicBlock());
1885     FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1886
1887     fastEmitBranch(FBB, DbgLoc);
1888     return true;
1889   }
1890
1891   unsigned CondReg = getRegForValue(BI->getCondition());
1892   if (CondReg == 0)
1893     return false;
1894   bool CondRegIsKill = hasTrivialKill(BI->getCondition());
1895
1896   // We've been divorced from our compare!  Our block was split, and
1897   // now our compare lives in a predecessor block.  We musn't
1898   // re-compare here, as the children of the compare aren't guaranteed
1899   // live across the block boundary (we *could* check for this).
1900   // Regardless, the compare has been done in the predecessor block,
1901   // and it left a value for us in a virtual register.  Ergo, we test
1902   // the one-bit value left in the virtual register.
1903   emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
1904
1905   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1906     std::swap(TBB, FBB);
1907     CC = AArch64CC::EQ;
1908   }
1909
1910   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
1911       .addImm(CC)
1912       .addMBB(TBB);
1913
1914   // Obtain the branch weight and add the TrueBB to the successor list.
1915   uint32_t BranchWeight = 0;
1916   if (FuncInfo.BPI)
1917     BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1918                                                TBB->getBasicBlock());
1919   FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
1920
1921   fastEmitBranch(FBB, DbgLoc);
1922   return true;
1923 }
1924
1925 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
1926   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
1927   unsigned AddrReg = getRegForValue(BI->getOperand(0));
1928   if (AddrReg == 0)
1929     return false;
1930
1931   // Emit the indirect branch.
1932   const MCInstrDesc &II = TII.get(AArch64::BR);
1933   AddrReg = constrainOperandRegClass(II, AddrReg,  II.getNumDefs());
1934   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
1935
1936   // Make sure the CFG is up-to-date.
1937   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
1938     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
1939
1940   return true;
1941 }
1942
1943 bool AArch64FastISel::selectCmp(const Instruction *I) {
1944   const CmpInst *CI = cast<CmpInst>(I);
1945
1946   // Try to optimize or fold the cmp.
1947   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1948   unsigned ResultReg = 0;
1949   switch (Predicate) {
1950   default:
1951     break;
1952   case CmpInst::FCMP_FALSE:
1953     ResultReg = createResultReg(&AArch64::GPR32RegClass);
1954     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1955             TII.get(TargetOpcode::COPY), ResultReg)
1956         .addReg(AArch64::WZR, getKillRegState(true));
1957     break;
1958   case CmpInst::FCMP_TRUE:
1959     ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
1960     break;
1961   }
1962
1963   if (ResultReg) {
1964     updateValueMap(I, ResultReg);
1965     return true;
1966   }
1967
1968   // Emit the cmp.
1969   if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1970     return false;
1971
1972   ResultReg = createResultReg(&AArch64::GPR32RegClass);
1973
1974   // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
1975   // condition codes are inverted, because they are used by CSINC.
1976   static unsigned CondCodeTable[2][2] = {
1977     { AArch64CC::NE, AArch64CC::VC },
1978     { AArch64CC::PL, AArch64CC::LE }
1979   };
1980   unsigned *CondCodes = nullptr;
1981   switch (Predicate) {
1982   default:
1983     break;
1984   case CmpInst::FCMP_UEQ:
1985     CondCodes = &CondCodeTable[0][0];
1986     break;
1987   case CmpInst::FCMP_ONE:
1988     CondCodes = &CondCodeTable[1][0];
1989     break;
1990   }
1991
1992   if (CondCodes) {
1993     unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
1994     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1995             TmpReg1)
1996         .addReg(AArch64::WZR, getKillRegState(true))
1997         .addReg(AArch64::WZR, getKillRegState(true))
1998         .addImm(CondCodes[0]);
1999     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2000             ResultReg)
2001         .addReg(TmpReg1, getKillRegState(true))
2002         .addReg(AArch64::WZR, getKillRegState(true))
2003         .addImm(CondCodes[1]);
2004
2005     updateValueMap(I, ResultReg);
2006     return true;
2007   }
2008
2009   // Now set a register based on the comparison.
2010   AArch64CC::CondCode CC = getCompareCC(Predicate);
2011   assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2012   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2013   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2014           ResultReg)
2015       .addReg(AArch64::WZR, getKillRegState(true))
2016       .addReg(AArch64::WZR, getKillRegState(true))
2017       .addImm(invertedCC);
2018
2019   updateValueMap(I, ResultReg);
2020   return true;
2021 }
2022
2023 bool AArch64FastISel::selectSelect(const Instruction *I) {
2024   const SelectInst *SI = cast<SelectInst>(I);
2025
2026   EVT DestEVT = TLI.getValueType(SI->getType(), true);
2027   if (!DestEVT.isSimple())
2028     return false;
2029
2030   MVT DestVT = DestEVT.getSimpleVT();
2031   if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2032       DestVT != MVT::f64)
2033     return false;
2034
2035   unsigned SelectOpc;
2036   const TargetRegisterClass *RC = nullptr;
2037   switch (DestVT.SimpleTy) {
2038   default: return false;
2039   case MVT::i32:
2040     SelectOpc = AArch64::CSELWr;    RC = &AArch64::GPR32RegClass; break;
2041   case MVT::i64:
2042     SelectOpc = AArch64::CSELXr;    RC = &AArch64::GPR64RegClass; break;
2043   case MVT::f32:
2044     SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2045   case MVT::f64:
2046     SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2047   }
2048
2049   const Value *Cond = SI->getCondition();
2050   bool NeedTest = true;
2051   AArch64CC::CondCode CC = AArch64CC::NE;
2052   if (foldXALUIntrinsic(CC, I, Cond))
2053     NeedTest = false;
2054
2055   unsigned CondReg = getRegForValue(Cond);
2056   if (!CondReg)
2057     return false;
2058   bool CondIsKill = hasTrivialKill(Cond);
2059
2060   if (NeedTest) {
2061     unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2062     assert(ANDReg && "Unexpected AND instruction emission failure.");
2063     emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2064   }
2065
2066   unsigned TrueReg = getRegForValue(SI->getTrueValue());
2067   bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2068
2069   unsigned FalseReg = getRegForValue(SI->getFalseValue());
2070   bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2071
2072   if (!TrueReg || !FalseReg)
2073     return false;
2074
2075   unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2076                                         FalseReg, FalseIsKill, CC);
2077   updateValueMap(I, ResultReg);
2078   return true;
2079 }
2080
2081 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2082   Value *V = I->getOperand(0);
2083   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2084     return false;
2085
2086   unsigned Op = getRegForValue(V);
2087   if (Op == 0)
2088     return false;
2089
2090   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2091   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2092           ResultReg).addReg(Op);
2093   updateValueMap(I, ResultReg);
2094   return true;
2095 }
2096
2097 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2098   Value *V = I->getOperand(0);
2099   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2100     return false;
2101
2102   unsigned Op = getRegForValue(V);
2103   if (Op == 0)
2104     return false;
2105
2106   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2107   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2108           ResultReg).addReg(Op);
2109   updateValueMap(I, ResultReg);
2110   return true;
2111 }
2112
2113 // FPToUI and FPToSI
2114 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2115   MVT DestVT;
2116   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2117     return false;
2118
2119   unsigned SrcReg = getRegForValue(I->getOperand(0));
2120   if (SrcReg == 0)
2121     return false;
2122
2123   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2124   if (SrcVT == MVT::f128)
2125     return false;
2126
2127   unsigned Opc;
2128   if (SrcVT == MVT::f64) {
2129     if (Signed)
2130       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2131     else
2132       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2133   } else {
2134     if (Signed)
2135       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2136     else
2137       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2138   }
2139   unsigned ResultReg = createResultReg(
2140       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2141   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2142       .addReg(SrcReg);
2143   updateValueMap(I, ResultReg);
2144   return true;
2145 }
2146
2147 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2148   MVT DestVT;
2149   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2150     return false;
2151   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2152           "Unexpected value type.");
2153
2154   unsigned SrcReg = getRegForValue(I->getOperand(0));
2155   if (!SrcReg)
2156     return false;
2157   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2158
2159   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2160
2161   // Handle sign-extension.
2162   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2163     SrcReg =
2164         emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2165     if (!SrcReg)
2166       return false;
2167     SrcIsKill = true;
2168   }
2169
2170   unsigned Opc;
2171   if (SrcVT == MVT::i64) {
2172     if (Signed)
2173       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2174     else
2175       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2176   } else {
2177     if (Signed)
2178       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2179     else
2180       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2181   }
2182
2183   unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2184                                       SrcIsKill);
2185   updateValueMap(I, ResultReg);
2186   return true;
2187 }
2188
2189 bool AArch64FastISel::fastLowerArguments() {
2190   if (!FuncInfo.CanLowerReturn)
2191     return false;
2192
2193   const Function *F = FuncInfo.Fn;
2194   if (F->isVarArg())
2195     return false;
2196
2197   CallingConv::ID CC = F->getCallingConv();
2198   if (CC != CallingConv::C)
2199     return false;
2200
2201   // Only handle simple cases of up to 8 GPR and FPR each.
2202   unsigned GPRCnt = 0;
2203   unsigned FPRCnt = 0;
2204   unsigned Idx = 0;
2205   for (auto const &Arg : F->args()) {
2206     // The first argument is at index 1.
2207     ++Idx;
2208     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2209         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2210         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2211         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2212       return false;
2213
2214     Type *ArgTy = Arg.getType();
2215     if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2216       return false;
2217
2218     EVT ArgVT = TLI.getValueType(ArgTy);
2219     if (!ArgVT.isSimple())
2220       return false;
2221
2222     MVT VT = ArgVT.getSimpleVT().SimpleTy;
2223     if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2224       return false;
2225
2226     if (VT.isVector() &&
2227         (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2228       return false;
2229
2230     if (VT >= MVT::i1 && VT <= MVT::i64)
2231       ++GPRCnt;
2232     else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2233              VT.is128BitVector())
2234       ++FPRCnt;
2235     else
2236       return false;
2237
2238     if (GPRCnt > 8 || FPRCnt > 8)
2239       return false;
2240   }
2241
2242   static const MCPhysReg Registers[6][8] = {
2243     { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2244       AArch64::W5, AArch64::W6, AArch64::W7 },
2245     { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2246       AArch64::X5, AArch64::X6, AArch64::X7 },
2247     { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2248       AArch64::H5, AArch64::H6, AArch64::H7 },
2249     { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2250       AArch64::S5, AArch64::S6, AArch64::S7 },
2251     { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2252       AArch64::D5, AArch64::D6, AArch64::D7 },
2253     { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2254       AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2255   };
2256
2257   unsigned GPRIdx = 0;
2258   unsigned FPRIdx = 0;
2259   for (auto const &Arg : F->args()) {
2260     MVT VT = TLI.getSimpleValueType(Arg.getType());
2261     unsigned SrcReg;
2262     const TargetRegisterClass *RC;
2263     if (VT >= MVT::i1 && VT <= MVT::i32) {
2264       SrcReg = Registers[0][GPRIdx++];
2265       RC = &AArch64::GPR32RegClass;
2266       VT = MVT::i32;
2267     } else if (VT == MVT::i64) {
2268       SrcReg = Registers[1][GPRIdx++];
2269       RC = &AArch64::GPR64RegClass;
2270     } else if (VT == MVT::f16) {
2271       SrcReg = Registers[2][FPRIdx++];
2272       RC = &AArch64::FPR16RegClass;
2273     } else if (VT ==  MVT::f32) {
2274       SrcReg = Registers[3][FPRIdx++];
2275       RC = &AArch64::FPR32RegClass;
2276     } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2277       SrcReg = Registers[4][FPRIdx++];
2278       RC = &AArch64::FPR64RegClass;
2279     } else if (VT.is128BitVector()) {
2280       SrcReg = Registers[5][FPRIdx++];
2281       RC = &AArch64::FPR128RegClass;
2282     } else
2283       llvm_unreachable("Unexpected value type.");
2284
2285     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2286     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2287     // Without this, EmitLiveInCopies may eliminate the livein if its only
2288     // use is a bitcast (which isn't turned into an instruction).
2289     unsigned ResultReg = createResultReg(RC);
2290     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2291             TII.get(TargetOpcode::COPY), ResultReg)
2292         .addReg(DstReg, getKillRegState(true));
2293     updateValueMap(&Arg, ResultReg);
2294   }
2295   return true;
2296 }
2297
2298 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2299                                       SmallVectorImpl<MVT> &OutVTs,
2300                                       unsigned &NumBytes) {
2301   CallingConv::ID CC = CLI.CallConv;
2302   SmallVector<CCValAssign, 16> ArgLocs;
2303   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2304   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2305
2306   // Get a count of how many bytes are to be pushed on the stack.
2307   NumBytes = CCInfo.getNextStackOffset();
2308
2309   // Issue CALLSEQ_START
2310   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2311   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2312     .addImm(NumBytes);
2313
2314   // Process the args.
2315   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2316     CCValAssign &VA = ArgLocs[i];
2317     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2318     MVT ArgVT = OutVTs[VA.getValNo()];
2319
2320     unsigned ArgReg = getRegForValue(ArgVal);
2321     if (!ArgReg)
2322       return false;
2323
2324     // Handle arg promotion: SExt, ZExt, AExt.
2325     switch (VA.getLocInfo()) {
2326     case CCValAssign::Full:
2327       break;
2328     case CCValAssign::SExt: {
2329       MVT DestVT = VA.getLocVT();
2330       MVT SrcVT = ArgVT;
2331       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2332       if (!ArgReg)
2333         return false;
2334       break;
2335     }
2336     case CCValAssign::AExt:
2337     // Intentional fall-through.
2338     case CCValAssign::ZExt: {
2339       MVT DestVT = VA.getLocVT();
2340       MVT SrcVT = ArgVT;
2341       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2342       if (!ArgReg)
2343         return false;
2344       break;
2345     }
2346     default:
2347       llvm_unreachable("Unknown arg promotion!");
2348     }
2349
2350     // Now copy/store arg to correct locations.
2351     if (VA.isRegLoc() && !VA.needsCustom()) {
2352       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2353               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2354       CLI.OutRegs.push_back(VA.getLocReg());
2355     } else if (VA.needsCustom()) {
2356       // FIXME: Handle custom args.
2357       return false;
2358     } else {
2359       assert(VA.isMemLoc() && "Assuming store on stack.");
2360
2361       // Don't emit stores for undef values.
2362       if (isa<UndefValue>(ArgVal))
2363         continue;
2364
2365       // Need to store on the stack.
2366       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2367
2368       unsigned BEAlign = 0;
2369       if (ArgSize < 8 && !Subtarget->isLittleEndian())
2370         BEAlign = 8 - ArgSize;
2371
2372       Address Addr;
2373       Addr.setKind(Address::RegBase);
2374       Addr.setReg(AArch64::SP);
2375       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2376
2377       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2378       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2379         MachinePointerInfo::getStack(Addr.getOffset()),
2380         MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2381
2382       if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2383         return false;
2384     }
2385   }
2386   return true;
2387 }
2388
2389 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2390                                  unsigned NumBytes) {
2391   CallingConv::ID CC = CLI.CallConv;
2392
2393   // Issue CALLSEQ_END
2394   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2395   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2396     .addImm(NumBytes).addImm(0);
2397
2398   // Now the return value.
2399   if (RetVT != MVT::isVoid) {
2400     SmallVector<CCValAssign, 16> RVLocs;
2401     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2402     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2403
2404     // Only handle a single return value.
2405     if (RVLocs.size() != 1)
2406       return false;
2407
2408     // Copy all of the result registers out of their specified physreg.
2409     MVT CopyVT = RVLocs[0].getValVT();
2410     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2411     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2412             TII.get(TargetOpcode::COPY), ResultReg)
2413         .addReg(RVLocs[0].getLocReg());
2414     CLI.InRegs.push_back(RVLocs[0].getLocReg());
2415
2416     CLI.ResultReg = ResultReg;
2417     CLI.NumResultRegs = 1;
2418   }
2419
2420   return true;
2421 }
2422
2423 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2424   CallingConv::ID CC  = CLI.CallConv;
2425   bool IsTailCall     = CLI.IsTailCall;
2426   bool IsVarArg       = CLI.IsVarArg;
2427   const Value *Callee = CLI.Callee;
2428   const char *SymName = CLI.SymName;
2429
2430   if (!Callee && !SymName)
2431     return false;
2432
2433   // Allow SelectionDAG isel to handle tail calls.
2434   if (IsTailCall)
2435     return false;
2436
2437   CodeModel::Model CM = TM.getCodeModel();
2438   // Only support the small and large code model.
2439   if (CM != CodeModel::Small && CM != CodeModel::Large)
2440     return false;
2441
2442   // FIXME: Add large code model support for ELF.
2443   if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2444     return false;
2445
2446   // Let SDISel handle vararg functions.
2447   if (IsVarArg)
2448     return false;
2449
2450   // FIXME: Only handle *simple* calls for now.
2451   MVT RetVT;
2452   if (CLI.RetTy->isVoidTy())
2453     RetVT = MVT::isVoid;
2454   else if (!isTypeLegal(CLI.RetTy, RetVT))
2455     return false;
2456
2457   for (auto Flag : CLI.OutFlags)
2458     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2459       return false;
2460
2461   // Set up the argument vectors.
2462   SmallVector<MVT, 16> OutVTs;
2463   OutVTs.reserve(CLI.OutVals.size());
2464
2465   for (auto *Val : CLI.OutVals) {
2466     MVT VT;
2467     if (!isTypeLegal(Val->getType(), VT) &&
2468         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2469       return false;
2470
2471     // We don't handle vector parameters yet.
2472     if (VT.isVector() || VT.getSizeInBits() > 64)
2473       return false;
2474
2475     OutVTs.push_back(VT);
2476   }
2477
2478   Address Addr;
2479   if (Callee && !computeCallAddress(Callee, Addr))
2480     return false;
2481
2482   // Handle the arguments now that we've gotten them.
2483   unsigned NumBytes;
2484   if (!processCallArgs(CLI, OutVTs, NumBytes))
2485     return false;
2486
2487   // Issue the call.
2488   MachineInstrBuilder MIB;
2489   if (CM == CodeModel::Small) {
2490     const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2491     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2492     if (SymName)
2493       MIB.addExternalSymbol(SymName, 0);
2494     else if (Addr.getGlobalValue())
2495       MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2496     else if (Addr.getReg()) {
2497       unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2498       MIB.addReg(Reg);
2499     } else
2500       return false;
2501   } else {
2502     unsigned CallReg = 0;
2503     if (SymName) {
2504       unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2505       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2506               ADRPReg)
2507         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2508
2509       CallReg = createResultReg(&AArch64::GPR64RegClass);
2510       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2511               CallReg)
2512         .addReg(ADRPReg)
2513         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2514                            AArch64II::MO_NC);
2515     } else if (Addr.getGlobalValue())
2516       CallReg = materializeGV(Addr.getGlobalValue());
2517     else if (Addr.getReg())
2518       CallReg = Addr.getReg();
2519
2520     if (!CallReg)
2521       return false;
2522
2523     const MCInstrDesc &II = TII.get(AArch64::BLR);
2524     CallReg = constrainOperandRegClass(II, CallReg, 0);
2525     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2526   }
2527
2528   // Add implicit physical register uses to the call.
2529   for (auto Reg : CLI.OutRegs)
2530     MIB.addReg(Reg, RegState::Implicit);
2531
2532   // Add a register mask with the call-preserved registers.
2533   // Proper defs for return values will be added by setPhysRegsDeadExcept().
2534   MIB.addRegMask(TRI.getCallPreservedMask(CC));
2535
2536   CLI.Call = MIB;
2537
2538   // Finish off the call including any return values.
2539   return finishCall(CLI, RetVT, NumBytes);
2540 }
2541
2542 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2543   if (Alignment)
2544     return Len / Alignment <= 4;
2545   else
2546     return Len < 32;
2547 }
2548
2549 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
2550                                          uint64_t Len, unsigned Alignment) {
2551   // Make sure we don't bloat code by inlining very large memcpy's.
2552   if (!isMemCpySmall(Len, Alignment))
2553     return false;
2554
2555   int64_t UnscaledOffset = 0;
2556   Address OrigDest = Dest;
2557   Address OrigSrc = Src;
2558
2559   while (Len) {
2560     MVT VT;
2561     if (!Alignment || Alignment >= 8) {
2562       if (Len >= 8)
2563         VT = MVT::i64;
2564       else if (Len >= 4)
2565         VT = MVT::i32;
2566       else if (Len >= 2)
2567         VT = MVT::i16;
2568       else {
2569         VT = MVT::i8;
2570       }
2571     } else {
2572       // Bound based on alignment.
2573       if (Len >= 4 && Alignment == 4)
2574         VT = MVT::i32;
2575       else if (Len >= 2 && Alignment == 2)
2576         VT = MVT::i16;
2577       else {
2578         VT = MVT::i8;
2579       }
2580     }
2581
2582     bool RV;
2583     unsigned ResultReg;
2584     RV = emitLoad(VT, ResultReg, Src);
2585     if (!RV)
2586       return false;
2587
2588     RV = emitStore(VT, ResultReg, Dest);
2589     if (!RV)
2590       return false;
2591
2592     int64_t Size = VT.getSizeInBits() / 8;
2593     Len -= Size;
2594     UnscaledOffset += Size;
2595
2596     // We need to recompute the unscaled offset for each iteration.
2597     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2598     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2599   }
2600
2601   return true;
2602 }
2603
2604 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2605 /// into the user. The condition code will only be updated on success.
2606 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2607                                         const Instruction *I,
2608                                         const Value *Cond) {
2609   if (!isa<ExtractValueInst>(Cond))
2610     return false;
2611
2612   const auto *EV = cast<ExtractValueInst>(Cond);
2613   if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2614     return false;
2615
2616   const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2617   MVT RetVT;
2618   const Function *Callee = II->getCalledFunction();
2619   Type *RetTy =
2620   cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2621   if (!isTypeLegal(RetTy, RetVT))
2622     return false;
2623
2624   if (RetVT != MVT::i32 && RetVT != MVT::i64)
2625     return false;
2626
2627   AArch64CC::CondCode TmpCC;
2628   switch (II->getIntrinsicID()) {
2629     default: return false;
2630     case Intrinsic::sadd_with_overflow:
2631     case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
2632     case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
2633     case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
2634     case Intrinsic::smul_with_overflow:
2635     case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
2636   }
2637
2638   // Check if both instructions are in the same basic block.
2639   if (!isValueAvailable(II))
2640     return false;
2641
2642   // Make sure nothing is in the way
2643   BasicBlock::const_iterator Start = I;
2644   BasicBlock::const_iterator End = II;
2645   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2646     // We only expect extractvalue instructions between the intrinsic and the
2647     // instruction to be selected.
2648     if (!isa<ExtractValueInst>(Itr))
2649       return false;
2650
2651     // Check that the extractvalue operand comes from the intrinsic.
2652     const auto *EVI = cast<ExtractValueInst>(Itr);
2653     if (EVI->getAggregateOperand() != II)
2654       return false;
2655   }
2656
2657   CC = TmpCC;
2658   return true;
2659 }
2660
2661 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2662   // FIXME: Handle more intrinsics.
2663   switch (II->getIntrinsicID()) {
2664   default: return false;
2665   case Intrinsic::frameaddress: {
2666     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2667     MFI->setFrameAddressIsTaken(true);
2668
2669     const AArch64RegisterInfo *RegInfo =
2670         static_cast<const AArch64RegisterInfo *>(
2671             TM.getSubtargetImpl()->getRegisterInfo());
2672     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2673     unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2674     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2675             TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
2676     // Recursively load frame address
2677     // ldr x0, [fp]
2678     // ldr x0, [x0]
2679     // ldr x0, [x0]
2680     // ...
2681     unsigned DestReg;
2682     unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2683     while (Depth--) {
2684       DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
2685                                 SrcReg, /*IsKill=*/true, 0);
2686       assert(DestReg && "Unexpected LDR instruction emission failure.");
2687       SrcReg = DestReg;
2688     }
2689
2690     updateValueMap(II, SrcReg);
2691     return true;
2692   }
2693   case Intrinsic::memcpy:
2694   case Intrinsic::memmove: {
2695     const auto *MTI = cast<MemTransferInst>(II);
2696     // Don't handle volatile.
2697     if (MTI->isVolatile())
2698       return false;
2699
2700     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2701     // we would emit dead code because we don't currently handle memmoves.
2702     bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
2703     if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
2704       // Small memcpy's are common enough that we want to do them without a call
2705       // if possible.
2706       uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
2707       unsigned Alignment = MTI->getAlignment();
2708       if (isMemCpySmall(Len, Alignment)) {
2709         Address Dest, Src;
2710         if (!computeAddress(MTI->getRawDest(), Dest) ||
2711             !computeAddress(MTI->getRawSource(), Src))
2712           return false;
2713         if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2714           return true;
2715       }
2716     }
2717
2718     if (!MTI->getLength()->getType()->isIntegerTy(64))
2719       return false;
2720
2721     if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
2722       // Fast instruction selection doesn't support the special
2723       // address spaces.
2724       return false;
2725
2726     const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
2727     return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
2728   }
2729   case Intrinsic::memset: {
2730     const MemSetInst *MSI = cast<MemSetInst>(II);
2731     // Don't handle volatile.
2732     if (MSI->isVolatile())
2733       return false;
2734
2735     if (!MSI->getLength()->getType()->isIntegerTy(64))
2736       return false;
2737
2738     if (MSI->getDestAddressSpace() > 255)
2739       // Fast instruction selection doesn't support the special
2740       // address spaces.
2741       return false;
2742
2743     return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2744   }
2745   case Intrinsic::sin:
2746   case Intrinsic::cos:
2747   case Intrinsic::pow: {
2748     MVT RetVT;
2749     if (!isTypeLegal(II->getType(), RetVT))
2750       return false;
2751
2752     if (RetVT != MVT::f32 && RetVT != MVT::f64)
2753       return false;
2754
2755     static const RTLIB::Libcall LibCallTable[3][2] = {
2756       { RTLIB::SIN_F32, RTLIB::SIN_F64 },
2757       { RTLIB::COS_F32, RTLIB::COS_F64 },
2758       { RTLIB::POW_F32, RTLIB::POW_F64 }
2759     };
2760     RTLIB::Libcall LC;
2761     bool Is64Bit = RetVT == MVT::f64;
2762     switch (II->getIntrinsicID()) {
2763     default:
2764       llvm_unreachable("Unexpected intrinsic.");
2765     case Intrinsic::sin:
2766       LC = LibCallTable[0][Is64Bit];
2767       break;
2768     case Intrinsic::cos:
2769       LC = LibCallTable[1][Is64Bit];
2770       break;
2771     case Intrinsic::pow:
2772       LC = LibCallTable[2][Is64Bit];
2773       break;
2774     }
2775
2776     ArgListTy Args;
2777     Args.reserve(II->getNumArgOperands());
2778
2779     // Populate the argument list.
2780     for (auto &Arg : II->arg_operands()) {
2781       ArgListEntry Entry;
2782       Entry.Val = Arg;
2783       Entry.Ty = Arg->getType();
2784       Args.push_back(Entry);
2785     }
2786
2787     CallLoweringInfo CLI;
2788     CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
2789                   TLI.getLibcallName(LC), std::move(Args));
2790     if (!lowerCallTo(CLI))
2791       return false;
2792     updateValueMap(II, CLI.ResultReg);
2793     return true;
2794   }
2795   case Intrinsic::trap: {
2796     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
2797         .addImm(1);
2798     return true;
2799   }
2800   case Intrinsic::sqrt: {
2801     Type *RetTy = II->getCalledFunction()->getReturnType();
2802
2803     MVT VT;
2804     if (!isTypeLegal(RetTy, VT))
2805       return false;
2806
2807     unsigned Op0Reg = getRegForValue(II->getOperand(0));
2808     if (!Op0Reg)
2809       return false;
2810     bool Op0IsKill = hasTrivialKill(II->getOperand(0));
2811
2812     unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
2813     if (!ResultReg)
2814       return false;
2815
2816     updateValueMap(II, ResultReg);
2817     return true;
2818   }
2819   case Intrinsic::sadd_with_overflow:
2820   case Intrinsic::uadd_with_overflow:
2821   case Intrinsic::ssub_with_overflow:
2822   case Intrinsic::usub_with_overflow:
2823   case Intrinsic::smul_with_overflow:
2824   case Intrinsic::umul_with_overflow: {
2825     // This implements the basic lowering of the xalu with overflow intrinsics.
2826     const Function *Callee = II->getCalledFunction();
2827     auto *Ty = cast<StructType>(Callee->getReturnType());
2828     Type *RetTy = Ty->getTypeAtIndex(0U);
2829
2830     MVT VT;
2831     if (!isTypeLegal(RetTy, VT))
2832       return false;
2833
2834     if (VT != MVT::i32 && VT != MVT::i64)
2835       return false;
2836
2837     const Value *LHS = II->getArgOperand(0);
2838     const Value *RHS = II->getArgOperand(1);
2839     // Canonicalize immediate to the RHS.
2840     if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2841         isCommutativeIntrinsic(II))
2842       std::swap(LHS, RHS);
2843
2844     unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
2845     AArch64CC::CondCode CC = AArch64CC::Invalid;
2846     switch (II->getIntrinsicID()) {
2847     default: llvm_unreachable("Unexpected intrinsic!");
2848     case Intrinsic::sadd_with_overflow:
2849       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2850       CC = AArch64CC::VS;
2851       break;
2852     case Intrinsic::uadd_with_overflow:
2853       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
2854       CC = AArch64CC::HS;
2855       break;
2856     case Intrinsic::ssub_with_overflow:
2857       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2858       CC = AArch64CC::VS;
2859       break;
2860     case Intrinsic::usub_with_overflow:
2861       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
2862       CC = AArch64CC::LO;
2863       break;
2864     case Intrinsic::smul_with_overflow: {
2865       CC = AArch64CC::NE;
2866       unsigned LHSReg = getRegForValue(LHS);
2867       if (!LHSReg)
2868         return false;
2869       bool LHSIsKill = hasTrivialKill(LHS);
2870
2871       unsigned RHSReg = getRegForValue(RHS);
2872       if (!RHSReg)
2873         return false;
2874       bool RHSIsKill = hasTrivialKill(RHS);
2875
2876       if (VT == MVT::i32) {
2877         MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2878         unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
2879                                        /*IsKill=*/false, 32);
2880         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2881                                             AArch64::sub_32);
2882         ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
2883                                               AArch64::sub_32);
2884         emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
2885                     AArch64_AM::ASR, 31, /*WantResult=*/false);
2886       } else {
2887         assert(VT == MVT::i64 && "Unexpected value type.");
2888         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2889         unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
2890                                         RHSReg, RHSIsKill);
2891         emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
2892                     AArch64_AM::ASR, 63, /*WantResult=*/false);
2893       }
2894       break;
2895     }
2896     case Intrinsic::umul_with_overflow: {
2897       CC = AArch64CC::NE;
2898       unsigned LHSReg = getRegForValue(LHS);
2899       if (!LHSReg)
2900         return false;
2901       bool LHSIsKill = hasTrivialKill(LHS);
2902
2903       unsigned RHSReg = getRegForValue(RHS);
2904       if (!RHSReg)
2905         return false;
2906       bool RHSIsKill = hasTrivialKill(RHS);
2907
2908       if (VT == MVT::i32) {
2909         MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2910         emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
2911                     /*IsKill=*/false, AArch64_AM::LSR, 32,
2912                     /*WantResult=*/false);
2913         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2914                                             AArch64::sub_32);
2915       } else {
2916         assert(VT == MVT::i64 && "Unexpected value type.");
2917         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2918         unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
2919                                         RHSReg, RHSIsKill);
2920         emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
2921                     /*IsKill=*/false, /*WantResult=*/false);
2922       }
2923       break;
2924     }
2925     }
2926
2927     if (MulReg) {
2928       ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
2929       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2930               TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
2931     }
2932
2933     ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
2934                                   AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
2935                                   /*IsKill=*/true, getInvertedCondCode(CC));
2936     assert((ResultReg1 + 1) == ResultReg2 &&
2937            "Nonconsecutive result registers.");
2938     updateValueMap(II, ResultReg1, 2);
2939     return true;
2940   }
2941   }
2942   return false;
2943 }
2944
2945 bool AArch64FastISel::selectRet(const Instruction *I) {
2946   const ReturnInst *Ret = cast<ReturnInst>(I);
2947   const Function &F = *I->getParent()->getParent();
2948
2949   if (!FuncInfo.CanLowerReturn)
2950     return false;
2951
2952   if (F.isVarArg())
2953     return false;
2954
2955   // Build a list of return value registers.
2956   SmallVector<unsigned, 4> RetRegs;
2957
2958   if (Ret->getNumOperands() > 0) {
2959     CallingConv::ID CC = F.getCallingConv();
2960     SmallVector<ISD::OutputArg, 4> Outs;
2961     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2962
2963     // Analyze operands of the call, assigning locations to each operand.
2964     SmallVector<CCValAssign, 16> ValLocs;
2965     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2966     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2967                                                      : RetCC_AArch64_AAPCS;
2968     CCInfo.AnalyzeReturn(Outs, RetCC);
2969
2970     // Only handle a single return value for now.
2971     if (ValLocs.size() != 1)
2972       return false;
2973
2974     CCValAssign &VA = ValLocs[0];
2975     const Value *RV = Ret->getOperand(0);
2976
2977     // Don't bother handling odd stuff for now.
2978     if ((VA.getLocInfo() != CCValAssign::Full) &&
2979         (VA.getLocInfo() != CCValAssign::BCvt))
2980       return false;
2981
2982     // Only handle register returns for now.
2983     if (!VA.isRegLoc())
2984       return false;
2985
2986     unsigned Reg = getRegForValue(RV);
2987     if (Reg == 0)
2988       return false;
2989
2990     unsigned SrcReg = Reg + VA.getValNo();
2991     unsigned DestReg = VA.getLocReg();
2992     // Avoid a cross-class copy. This is very unlikely.
2993     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
2994       return false;
2995
2996     EVT RVEVT = TLI.getValueType(RV->getType());
2997     if (!RVEVT.isSimple())
2998       return false;
2999
3000     // Vectors (of > 1 lane) in big endian need tricky handling.
3001     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3002         !Subtarget->isLittleEndian())
3003       return false;
3004
3005     MVT RVVT = RVEVT.getSimpleVT();
3006     if (RVVT == MVT::f128)
3007       return false;
3008
3009     MVT DestVT = VA.getValVT();
3010     // Special handling for extended integers.
3011     if (RVVT != DestVT) {
3012       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3013         return false;
3014
3015       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3016         return false;
3017
3018       bool IsZExt = Outs[0].Flags.isZExt();
3019       SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3020       if (SrcReg == 0)
3021         return false;
3022     }
3023
3024     // Make the copy.
3025     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3026             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3027
3028     // Add register to return instruction.
3029     RetRegs.push_back(VA.getLocReg());
3030   }
3031
3032   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3033                                     TII.get(AArch64::RET_ReallyLR));
3034   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3035     MIB.addReg(RetRegs[i], RegState::Implicit);
3036   return true;
3037 }
3038
3039 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3040   Type *DestTy = I->getType();
3041   Value *Op = I->getOperand(0);
3042   Type *SrcTy = Op->getType();
3043
3044   EVT SrcEVT = TLI.getValueType(SrcTy, true);
3045   EVT DestEVT = TLI.getValueType(DestTy, true);
3046   if (!SrcEVT.isSimple())
3047     return false;
3048   if (!DestEVT.isSimple())
3049     return false;
3050
3051   MVT SrcVT = SrcEVT.getSimpleVT();
3052   MVT DestVT = DestEVT.getSimpleVT();
3053
3054   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3055       SrcVT != MVT::i8)
3056     return false;
3057   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3058       DestVT != MVT::i1)
3059     return false;
3060
3061   unsigned SrcReg = getRegForValue(Op);
3062   if (!SrcReg)
3063     return false;
3064   bool SrcIsKill = hasTrivialKill(Op);
3065
3066   // If we're truncating from i64 to a smaller non-legal type then generate an
3067   // AND. Otherwise, we know the high bits are undefined and a truncate only
3068   // generate a COPY. We cannot mark the source register also as result
3069   // register, because this can incorrectly transfer the kill flag onto the
3070   // source register.
3071   unsigned ResultReg;
3072   if (SrcVT == MVT::i64) {
3073     uint64_t Mask = 0;
3074     switch (DestVT.SimpleTy) {
3075     default:
3076       // Trunc i64 to i32 is handled by the target-independent fast-isel.
3077       return false;
3078     case MVT::i1:
3079       Mask = 0x1;
3080       break;
3081     case MVT::i8:
3082       Mask = 0xff;
3083       break;
3084     case MVT::i16:
3085       Mask = 0xffff;
3086       break;
3087     }
3088     // Issue an extract_subreg to get the lower 32-bits.
3089     unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3090                                                 AArch64::sub_32);
3091     // Create the AND instruction which performs the actual truncation.
3092     ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3093     assert(ResultReg && "Unexpected AND instruction emission failure.");
3094   } else {
3095     ResultReg = createResultReg(&AArch64::GPR32RegClass);
3096     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3097             TII.get(TargetOpcode::COPY), ResultReg)
3098         .addReg(SrcReg, getKillRegState(SrcIsKill));
3099   }
3100
3101   updateValueMap(I, ResultReg);
3102   return true;
3103 }
3104
3105 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3106   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3107           DestVT == MVT::i64) &&
3108          "Unexpected value type.");
3109   // Handle i8 and i16 as i32.
3110   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3111     DestVT = MVT::i32;
3112
3113   if (IsZExt) {
3114     unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3115     assert(ResultReg && "Unexpected AND instruction emission failure.");
3116     if (DestVT == MVT::i64) {
3117       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
3118       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
3119       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3120       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3121               TII.get(AArch64::SUBREG_TO_REG), Reg64)
3122           .addImm(0)
3123           .addReg(ResultReg)
3124           .addImm(AArch64::sub_32);
3125       ResultReg = Reg64;
3126     }
3127     return ResultReg;
3128   } else {
3129     if (DestVT == MVT::i64) {
3130       // FIXME: We're SExt i1 to i64.
3131       return 0;
3132     }
3133     return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3134                             /*TODO:IsKill=*/false, 0, 0);
3135   }
3136 }
3137
3138 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3139                                       unsigned Op1, bool Op1IsKill) {
3140   unsigned Opc, ZReg;
3141   switch (RetVT.SimpleTy) {
3142   default: return 0;
3143   case MVT::i8:
3144   case MVT::i16:
3145   case MVT::i32:
3146     RetVT = MVT::i32;
3147     Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3148   case MVT::i64:
3149     Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3150   }
3151
3152   const TargetRegisterClass *RC =
3153       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3154   return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3155                           /*IsKill=*/ZReg, true);
3156 }
3157
3158 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3159                                         unsigned Op1, bool Op1IsKill) {
3160   if (RetVT != MVT::i64)
3161     return 0;
3162
3163   return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3164                           Op0, Op0IsKill, Op1, Op1IsKill,
3165                           AArch64::XZR, /*IsKill=*/true);
3166 }
3167
3168 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3169                                         unsigned Op1, bool Op1IsKill) {
3170   if (RetVT != MVT::i64)
3171     return 0;
3172
3173   return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3174                           Op0, Op0IsKill, Op1, Op1IsKill,
3175                           AArch64::XZR, /*IsKill=*/true);
3176 }
3177
3178 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3179                                      unsigned Op1Reg, bool Op1IsKill) {
3180   unsigned Opc = 0;
3181   bool NeedTrunc = false;
3182   uint64_t Mask = 0;
3183   switch (RetVT.SimpleTy) {
3184   default: return 0;
3185   case MVT::i8:  Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff;   break;
3186   case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3187   case MVT::i32: Opc = AArch64::LSLVWr;                                  break;
3188   case MVT::i64: Opc = AArch64::LSLVXr;                                  break;
3189   }
3190
3191   const TargetRegisterClass *RC =
3192       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3193   if (NeedTrunc) {
3194     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3195     Op1IsKill = true;
3196   }
3197   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3198                                        Op1IsKill);
3199   if (NeedTrunc)
3200     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3201   return ResultReg;
3202 }
3203
3204 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3205                                      bool Op0IsKill, uint64_t Shift,
3206                                      bool IsZext) {
3207   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3208          "Unexpected source/return type pair.");
3209   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3210           SrcVT == MVT::i64) && "Unexpected source value type.");
3211   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3212           RetVT == MVT::i64) && "Unexpected return value type.");
3213
3214   bool Is64Bit = (RetVT == MVT::i64);
3215   unsigned RegSize = Is64Bit ? 64 : 32;
3216   unsigned DstBits = RetVT.getSizeInBits();
3217   unsigned SrcBits = SrcVT.getSizeInBits();
3218
3219   // Don't deal with undefined shifts.
3220   if (Shift >= DstBits)
3221     return 0;
3222
3223   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3224   // {S|U}BFM Wd, Wn, #r, #s
3225   // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3226
3227   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3228   // %2 = shl i16 %1, 4
3229   // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3230   // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3231   // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3232   // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3233
3234   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3235   // %2 = shl i16 %1, 8
3236   // Wd<32+7-24,32-24> = Wn<7:0>
3237   // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3238   // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3239   // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3240
3241   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3242   // %2 = shl i16 %1, 12
3243   // Wd<32+3-20,32-20> = Wn<3:0>
3244   // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3245   // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3246   // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3247
3248   unsigned ImmR = RegSize - Shift;
3249   // Limit the width to the length of the source type.
3250   unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3251   static const unsigned OpcTable[2][2] = {
3252     {AArch64::SBFMWri, AArch64::SBFMXri},
3253     {AArch64::UBFMWri, AArch64::UBFMXri}
3254   };
3255   unsigned Opc = OpcTable[IsZext][Is64Bit];
3256   const TargetRegisterClass *RC =
3257       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3258   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3259     unsigned TmpReg = MRI.createVirtualRegister(RC);
3260     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3261             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3262         .addImm(0)
3263         .addReg(Op0, getKillRegState(Op0IsKill))
3264         .addImm(AArch64::sub_32);
3265     Op0 = TmpReg;
3266     Op0IsKill = true;
3267   }
3268   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3269 }
3270
3271 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3272                                      unsigned Op1Reg, bool Op1IsKill) {
3273   unsigned Opc = 0;
3274   bool NeedTrunc = false;
3275   uint64_t Mask = 0;
3276   switch (RetVT.SimpleTy) {
3277   default: return 0;
3278   case MVT::i8:  Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff;   break;
3279   case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3280   case MVT::i32: Opc = AArch64::LSRVWr; break;
3281   case MVT::i64: Opc = AArch64::LSRVXr; break;
3282   }
3283
3284   const TargetRegisterClass *RC =
3285       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3286   if (NeedTrunc) {
3287     Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3288     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3289     Op0IsKill = Op1IsKill = true;
3290   }
3291   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3292                                        Op1IsKill);
3293   if (NeedTrunc)
3294     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3295   return ResultReg;
3296 }
3297
3298 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3299                                      bool Op0IsKill, uint64_t Shift,
3300                                      bool IsZExt) {
3301   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3302          "Unexpected source/return type pair.");
3303   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3304           SrcVT == MVT::i64) && "Unexpected source value type.");
3305   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3306           RetVT == MVT::i64) && "Unexpected return value type.");
3307
3308   bool Is64Bit = (RetVT == MVT::i64);
3309   unsigned RegSize = Is64Bit ? 64 : 32;
3310   unsigned DstBits = RetVT.getSizeInBits();
3311   unsigned SrcBits = SrcVT.getSizeInBits();
3312
3313   // Don't deal with undefined shifts.
3314   if (Shift >= DstBits)
3315     return 0;
3316
3317   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3318   // {S|U}BFM Wd, Wn, #r, #s
3319   // Wd<s-r:0> = Wn<s:r> when r <= s
3320
3321   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3322   // %2 = lshr i16 %1, 4
3323   // Wd<7-4:0> = Wn<7:4>
3324   // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3325   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3326   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3327
3328   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3329   // %2 = lshr i16 %1, 8
3330   // Wd<7-7,0> = Wn<7:7>
3331   // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3332   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3333   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3334
3335   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3336   // %2 = lshr i16 %1, 12
3337   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3338   // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3339   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3340   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3341
3342   if (Shift >= SrcBits && IsZExt)
3343     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3344
3345   // It is not possible to fold a sign-extend into the LShr instruction. In this
3346   // case emit a sign-extend.
3347   if (!IsZExt) {
3348     Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3349     if (!Op0)
3350       return 0;
3351     Op0IsKill = true;
3352     SrcVT = RetVT;
3353     SrcBits = SrcVT.getSizeInBits();
3354     IsZExt = true;
3355   }
3356
3357   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3358   unsigned ImmS = SrcBits - 1;
3359   static const unsigned OpcTable[2][2] = {
3360     {AArch64::SBFMWri, AArch64::SBFMXri},
3361     {AArch64::UBFMWri, AArch64::UBFMXri}
3362   };
3363   unsigned Opc = OpcTable[IsZExt][Is64Bit];
3364   const TargetRegisterClass *RC =
3365       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3366   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3367     unsigned TmpReg = MRI.createVirtualRegister(RC);
3368     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3369             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3370         .addImm(0)
3371         .addReg(Op0, getKillRegState(Op0IsKill))
3372         .addImm(AArch64::sub_32);
3373     Op0 = TmpReg;
3374     Op0IsKill = true;
3375   }
3376   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3377 }
3378
3379 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3380                                      unsigned Op1Reg, bool Op1IsKill) {
3381   unsigned Opc = 0;
3382   bool NeedTrunc = false;
3383   uint64_t Mask = 0;
3384   switch (RetVT.SimpleTy) {
3385   default: return 0;
3386   case MVT::i8:  Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff;   break;
3387   case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3388   case MVT::i32: Opc = AArch64::ASRVWr;                                  break;
3389   case MVT::i64: Opc = AArch64::ASRVXr;                                  break;
3390   }
3391
3392   const TargetRegisterClass *RC =
3393       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3394   if (NeedTrunc) {
3395     Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3396     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3397     Op0IsKill = Op1IsKill = true;
3398   }
3399   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3400                                        Op1IsKill);
3401   if (NeedTrunc)
3402     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3403   return ResultReg;
3404 }
3405
3406 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3407                                      bool Op0IsKill, uint64_t Shift,
3408                                      bool IsZExt) {
3409   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3410          "Unexpected source/return type pair.");
3411   assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3412           SrcVT == MVT::i64) && "Unexpected source value type.");
3413   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3414           RetVT == MVT::i64) && "Unexpected return value type.");
3415
3416   bool Is64Bit = (RetVT == MVT::i64);
3417   unsigned RegSize = Is64Bit ? 64 : 32;
3418   unsigned DstBits = RetVT.getSizeInBits();
3419   unsigned SrcBits = SrcVT.getSizeInBits();
3420
3421   // Don't deal with undefined shifts.
3422   if (Shift >= DstBits)
3423     return 0;
3424
3425   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3426   // {S|U}BFM Wd, Wn, #r, #s
3427   // Wd<s-r:0> = Wn<s:r> when r <= s
3428
3429   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3430   // %2 = ashr i16 %1, 4
3431   // Wd<7-4:0> = Wn<7:4>
3432   // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3433   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3434   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3435
3436   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3437   // %2 = ashr i16 %1, 8
3438   // Wd<7-7,0> = Wn<7:7>
3439   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3440   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3441   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3442
3443   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3444   // %2 = ashr i16 %1, 12
3445   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3446   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3447   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3448   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3449
3450   if (Shift >= SrcBits && IsZExt)
3451     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3452
3453   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3454   unsigned ImmS = SrcBits - 1;
3455   static const unsigned OpcTable[2][2] = {
3456     {AArch64::SBFMWri, AArch64::SBFMXri},
3457     {AArch64::UBFMWri, AArch64::UBFMXri}
3458   };
3459   unsigned Opc = OpcTable[IsZExt][Is64Bit];
3460   const TargetRegisterClass *RC =
3461       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3462   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3463     unsigned TmpReg = MRI.createVirtualRegister(RC);
3464     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3465             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3466         .addImm(0)
3467         .addReg(Op0, getKillRegState(Op0IsKill))
3468         .addImm(AArch64::sub_32);
3469     Op0 = TmpReg;
3470     Op0IsKill = true;
3471   }
3472   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3473 }
3474
3475 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3476                                      bool IsZExt) {
3477   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3478
3479   // FastISel does not have plumbing to deal with extensions where the SrcVT or
3480   // DestVT are odd things, so test to make sure that they are both types we can
3481   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3482   // bail out to SelectionDAG.
3483   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3484        (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3485       ((SrcVT !=  MVT::i1) && (SrcVT !=  MVT::i8) &&
3486        (SrcVT !=  MVT::i16) && (SrcVT !=  MVT::i32)))
3487     return 0;
3488
3489   unsigned Opc;
3490   unsigned Imm = 0;
3491
3492   switch (SrcVT.SimpleTy) {
3493   default:
3494     return 0;
3495   case MVT::i1:
3496     return emiti1Ext(SrcReg, DestVT, IsZExt);
3497   case MVT::i8:
3498     if (DestVT == MVT::i64)
3499       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3500     else
3501       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3502     Imm = 7;
3503     break;
3504   case MVT::i16:
3505     if (DestVT == MVT::i64)
3506       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3507     else
3508       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3509     Imm = 15;
3510     break;
3511   case MVT::i32:
3512     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
3513     Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3514     Imm = 31;
3515     break;
3516   }
3517
3518   // Handle i8 and i16 as i32.
3519   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3520     DestVT = MVT::i32;
3521   else if (DestVT == MVT::i64) {
3522     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3523     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3524             TII.get(AArch64::SUBREG_TO_REG), Src64)
3525         .addImm(0)
3526         .addReg(SrcReg)
3527         .addImm(AArch64::sub_32);
3528     SrcReg = Src64;
3529   }
3530
3531   const TargetRegisterClass *RC =
3532       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3533   return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
3534 }
3535
3536 bool AArch64FastISel::selectIntExt(const Instruction *I) {
3537   // On ARM, in general, integer casts don't involve legal types; this code
3538   // handles promotable integers.  The high bits for a type smaller than
3539   // the register size are assumed to be undefined.
3540   Type *DestTy = I->getType();
3541   Value *Src = I->getOperand(0);
3542   Type *SrcTy = Src->getType();
3543
3544   unsigned SrcReg = getRegForValue(Src);
3545   if (!SrcReg)
3546     return false;
3547
3548   EVT SrcEVT = TLI.getValueType(SrcTy, true);
3549   EVT DestEVT = TLI.getValueType(DestTy, true);
3550   if (!SrcEVT.isSimple())
3551     return false;
3552   if (!DestEVT.isSimple())
3553     return false;
3554
3555   MVT SrcVT = SrcEVT.getSimpleVT();
3556   MVT DestVT = DestEVT.getSimpleVT();
3557   unsigned ResultReg = 0;
3558
3559   bool IsZExt = isa<ZExtInst>(I);
3560   // Check if it is an argument and if it is already zero/sign-extended.
3561   if (const auto *Arg = dyn_cast<Argument>(Src)) {
3562     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
3563       if (DestVT == MVT::i64) {
3564         ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
3565         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3566                 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3567           .addImm(0)
3568           .addReg(SrcReg)
3569           .addImm(AArch64::sub_32);
3570       } else
3571         ResultReg = SrcReg;
3572     }
3573   }
3574
3575   if (!ResultReg)
3576     ResultReg = emitIntExt(SrcVT, SrcReg, DestVT, IsZExt);
3577
3578   if (!ResultReg)
3579     return false;
3580
3581   updateValueMap(I, ResultReg);
3582   return true;
3583 }
3584
3585 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
3586   EVT DestEVT = TLI.getValueType(I->getType(), true);
3587   if (!DestEVT.isSimple())
3588     return false;
3589
3590   MVT DestVT = DestEVT.getSimpleVT();
3591   if (DestVT != MVT::i64 && DestVT != MVT::i32)
3592     return false;
3593
3594   unsigned DivOpc;
3595   bool Is64bit = (DestVT == MVT::i64);
3596   switch (ISDOpcode) {
3597   default:
3598     return false;
3599   case ISD::SREM:
3600     DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
3601     break;
3602   case ISD::UREM:
3603     DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
3604     break;
3605   }
3606   unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
3607   unsigned Src0Reg = getRegForValue(I->getOperand(0));
3608   if (!Src0Reg)
3609     return false;
3610   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3611
3612   unsigned Src1Reg = getRegForValue(I->getOperand(1));
3613   if (!Src1Reg)
3614     return false;
3615   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3616
3617   const TargetRegisterClass *RC =
3618       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3619   unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
3620                                      Src1Reg, /*IsKill=*/false);
3621   assert(QuotReg && "Unexpected DIV instruction emission failure.");
3622   // The remainder is computed as numerator - (quotient * denominator) using the
3623   // MSUB instruction.
3624   unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
3625                                         Src1Reg, Src1IsKill, Src0Reg,
3626                                         Src0IsKill);
3627   updateValueMap(I, ResultReg);
3628   return true;
3629 }
3630
3631 bool AArch64FastISel::selectMul(const Instruction *I) {
3632   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
3633   if (!SrcEVT.isSimple())
3634     return false;
3635   MVT SrcVT = SrcEVT.getSimpleVT();
3636
3637   // Must be simple value type.  Don't handle vectors.
3638   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3639       SrcVT != MVT::i8)
3640     return false;
3641
3642   unsigned Src0Reg = getRegForValue(I->getOperand(0));
3643   if (!Src0Reg)
3644     return false;
3645   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3646
3647   unsigned Src1Reg = getRegForValue(I->getOperand(1));
3648   if (!Src1Reg)
3649     return false;
3650   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
3651
3652   unsigned ResultReg =
3653       emitMul_rr(SrcVT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
3654
3655   if (!ResultReg)
3656     return false;
3657
3658   updateValueMap(I, ResultReg);
3659   return true;
3660 }
3661
3662 bool AArch64FastISel::selectShift(const Instruction *I) {
3663   MVT RetVT;
3664   if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
3665     return false;
3666
3667   if (RetVT.isVector())
3668     return selectOperator(I, I->getOpcode());
3669
3670   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
3671     unsigned ResultReg = 0;
3672     uint64_t ShiftVal = C->getZExtValue();
3673     MVT SrcVT = RetVT;
3674     bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
3675     const Value *Op0 = I->getOperand(0);
3676     if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
3677       MVT TmpVT;
3678       if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
3679         SrcVT = TmpVT;
3680         IsZExt = true;
3681         Op0 = ZExt->getOperand(0);
3682       }
3683     } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
3684       MVT TmpVT;
3685       if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
3686         SrcVT = TmpVT;
3687         IsZExt = false;
3688         Op0 = SExt->getOperand(0);
3689       }
3690     }
3691
3692     unsigned Op0Reg = getRegForValue(Op0);
3693     if (!Op0Reg)
3694       return false;
3695     bool Op0IsKill = hasTrivialKill(Op0);
3696
3697     switch (I->getOpcode()) {
3698     default: llvm_unreachable("Unexpected instruction.");
3699     case Instruction::Shl:
3700       ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3701       break;
3702     case Instruction::AShr:
3703       ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3704       break;
3705     case Instruction::LShr:
3706       ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
3707       break;
3708     }
3709     if (!ResultReg)
3710       return false;
3711
3712     updateValueMap(I, ResultReg);
3713     return true;
3714   }
3715
3716   unsigned Op0Reg = getRegForValue(I->getOperand(0));
3717   if (!Op0Reg)
3718     return false;
3719   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3720
3721   unsigned Op1Reg = getRegForValue(I->getOperand(1));
3722   if (!Op1Reg)
3723     return false;
3724   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
3725
3726   unsigned ResultReg = 0;
3727   switch (I->getOpcode()) {
3728   default: llvm_unreachable("Unexpected instruction.");
3729   case Instruction::Shl:
3730     ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3731     break;
3732   case Instruction::AShr:
3733     ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3734     break;
3735   case Instruction::LShr:
3736     ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
3737     break;
3738   }
3739
3740   if (!ResultReg)
3741     return false;
3742
3743   updateValueMap(I, ResultReg);
3744   return true;
3745 }
3746
3747 bool AArch64FastISel::selectBitCast(const Instruction *I) {
3748   MVT RetVT, SrcVT;
3749
3750   if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
3751     return false;
3752   if (!isTypeLegal(I->getType(), RetVT))
3753     return false;
3754
3755   unsigned Opc;
3756   if (RetVT == MVT::f32 && SrcVT == MVT::i32)
3757     Opc = AArch64::FMOVWSr;
3758   else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
3759     Opc = AArch64::FMOVXDr;
3760   else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
3761     Opc = AArch64::FMOVSWr;
3762   else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
3763     Opc = AArch64::FMOVDXr;
3764   else
3765     return false;
3766
3767   const TargetRegisterClass *RC = nullptr;
3768   switch (RetVT.SimpleTy) {
3769   default: llvm_unreachable("Unexpected value type.");
3770   case MVT::i32: RC = &AArch64::GPR32RegClass; break;
3771   case MVT::i64: RC = &AArch64::GPR64RegClass; break;
3772   case MVT::f32: RC = &AArch64::FPR32RegClass; break;
3773   case MVT::f64: RC = &AArch64::FPR64RegClass; break;
3774   }
3775   unsigned Op0Reg = getRegForValue(I->getOperand(0));
3776   if (!Op0Reg)
3777     return false;
3778   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
3779   unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
3780
3781   if (!ResultReg)
3782     return false;
3783
3784   updateValueMap(I, ResultReg);
3785   return true;
3786 }
3787
3788 bool AArch64FastISel::selectFRem(const Instruction *I) {
3789   MVT RetVT;
3790   if (!isTypeLegal(I->getType(), RetVT))
3791     return false;
3792
3793   RTLIB::Libcall LC;
3794   switch (RetVT.SimpleTy) {
3795   default:
3796     return false;
3797   case MVT::f32:
3798     LC = RTLIB::REM_F32;
3799     break;
3800   case MVT::f64:
3801     LC = RTLIB::REM_F64;
3802     break;
3803   }
3804
3805   ArgListTy Args;
3806   Args.reserve(I->getNumOperands());
3807
3808   // Populate the argument list.
3809   for (auto &Arg : I->operands()) {
3810     ArgListEntry Entry;
3811     Entry.Val = Arg;
3812     Entry.Ty = Arg->getType();
3813     Args.push_back(Entry);
3814   }
3815
3816   CallLoweringInfo CLI;
3817   CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
3818                 TLI.getLibcallName(LC), std::move(Args));
3819   if (!lowerCallTo(CLI))
3820     return false;
3821   updateValueMap(I, CLI.ResultReg);
3822   return true;
3823 }
3824
3825 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
3826   switch (I->getOpcode()) {
3827   default:
3828     break;
3829   case Instruction::Add:
3830   case Instruction::Sub:
3831     return selectAddSub(I);
3832   case Instruction::Mul:
3833     if (!selectBinaryOp(I, ISD::MUL))
3834       return selectMul(I);
3835     return true;
3836   case Instruction::SRem:
3837     if (!selectBinaryOp(I, ISD::SREM))
3838       return selectRem(I, ISD::SREM);
3839     return true;
3840   case Instruction::URem:
3841     if (!selectBinaryOp(I, ISD::UREM))
3842       return selectRem(I, ISD::UREM);
3843     return true;
3844   case Instruction::Shl:
3845   case Instruction::LShr:
3846   case Instruction::AShr:
3847     return selectShift(I);
3848   case Instruction::And:
3849   case Instruction::Or:
3850   case Instruction::Xor:
3851     return selectLogicalOp(I);
3852   case Instruction::Br:
3853     return selectBranch(I);
3854   case Instruction::IndirectBr:
3855     return selectIndirectBr(I);
3856   case Instruction::BitCast:
3857     if (!FastISel::selectBitCast(I))
3858       return selectBitCast(I);
3859     return true;
3860   case Instruction::FPToSI:
3861     if (!selectCast(I, ISD::FP_TO_SINT))
3862       return selectFPToInt(I, /*Signed=*/true);
3863     return true;
3864   case Instruction::FPToUI:
3865     return selectFPToInt(I, /*Signed=*/false);
3866   case Instruction::ZExt:
3867     if (!selectCast(I, ISD::ZERO_EXTEND))
3868       return selectIntExt(I);
3869     return true;
3870   case Instruction::SExt:
3871     if (!selectCast(I, ISD::SIGN_EXTEND))
3872       return selectIntExt(I);
3873     return true;
3874   case Instruction::Trunc:
3875     if (!selectCast(I, ISD::TRUNCATE))
3876       return selectTrunc(I);
3877     return true;
3878   case Instruction::FPExt:
3879     return selectFPExt(I);
3880   case Instruction::FPTrunc:
3881     return selectFPTrunc(I);
3882   case Instruction::SIToFP:
3883     if (!selectCast(I, ISD::SINT_TO_FP))
3884       return selectIntToFP(I, /*Signed=*/true);
3885     return true;
3886   case Instruction::UIToFP:
3887     return selectIntToFP(I, /*Signed=*/false);
3888   case Instruction::Load:
3889     return selectLoad(I);
3890   case Instruction::Store:
3891     return selectStore(I);
3892   case Instruction::FCmp:
3893   case Instruction::ICmp:
3894     return selectCmp(I);
3895   case Instruction::Select:
3896     return selectSelect(I);
3897   case Instruction::Ret:
3898     return selectRet(I);
3899   case Instruction::FRem:
3900     return selectFRem(I);
3901   }
3902
3903   // fall-back to target-independent instruction selection.
3904   return selectOperator(I, I->getOpcode());
3905   // Silence warnings.
3906   (void)&CC_AArch64_DarwinPCS_VarArg;
3907 }
3908
3909 namespace llvm {
3910 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
3911                                         const TargetLibraryInfo *LibInfo) {
3912   return new AArch64FastISel(FuncInfo, LibInfo);
3913 }
3914 }