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