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