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