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