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