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