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