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