[AArch64] Implement GHC calling convention
[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 "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/CommandLine.h"
40 using namespace llvm;
41
42 namespace {
43
44 class AArch64FastISel final : public FastISel {
45   class Address {
46   public:
47     typedef enum {
48       RegBase,
49       FrameIndexBase
50     } BaseKind;
51
52   private:
53     BaseKind Kind;
54     AArch64_AM::ShiftExtendType ExtType;
55     union {
56       unsigned Reg;
57       int FI;
58     } Base;
59     unsigned OffsetReg;
60     unsigned Shift;
61     int64_t Offset;
62     const GlobalValue *GV;
63
64   public:
65     Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
66       OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
67     void setKind(BaseKind K) { Kind = K; }
68     BaseKind getKind() const { return Kind; }
69     void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
70     AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
71     bool isRegBase() const { return Kind == RegBase; }
72     bool isFIBase() const { return Kind == FrameIndexBase; }
73     void setReg(unsigned Reg) {
74       assert(isRegBase() && "Invalid base register access!");
75       Base.Reg = Reg;
76     }
77     unsigned getReg() const {
78       assert(isRegBase() && "Invalid base register access!");
79       return Base.Reg;
80     }
81     void setOffsetReg(unsigned Reg) {
82       OffsetReg = Reg;
83     }
84     unsigned getOffsetReg() const {
85       return OffsetReg;
86     }
87     void setFI(unsigned FI) {
88       assert(isFIBase() && "Invalid base frame index  access!");
89       Base.FI = FI;
90     }
91     unsigned getFI() const {
92       assert(isFIBase() && "Invalid base frame index access!");
93       return Base.FI;
94     }
95     void setOffset(int64_t O) { Offset = O; }
96     int64_t getOffset() { return Offset; }
97     void setShift(unsigned S) { Shift = S; }
98     unsigned getShift() { return Shift; }
99
100     void setGlobalValue(const GlobalValue *G) { GV = G; }
101     const GlobalValue *getGlobalValue() { return GV; }
102   };
103
104   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
105   /// make the right decision when generating code for different targets.
106   const AArch64Subtarget *Subtarget;
107   LLVMContext *Context;
108
109   bool fastLowerArguments() override;
110   bool fastLowerCall(CallLoweringInfo &CLI) override;
111   bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
112
113 private:
114   // Selection routines.
115   bool selectAddSub(const Instruction *I);
116   bool selectLogicalOp(const Instruction *I);
117   bool selectLoad(const Instruction *I);
118   bool selectStore(const Instruction *I);
119   bool selectBranch(const Instruction *I);
120   bool selectIndirectBr(const Instruction *I);
121   bool selectCmp(const Instruction *I);
122   bool selectSelect(const Instruction *I);
123   bool selectFPExt(const Instruction *I);
124   bool selectFPTrunc(const Instruction *I);
125   bool selectFPToInt(const Instruction *I, bool Signed);
126   bool selectIntToFP(const Instruction *I, bool Signed);
127   bool selectRem(const Instruction *I, unsigned ISDOpcode);
128   bool selectRet(const Instruction *I);
129   bool selectTrunc(const Instruction *I);
130   bool selectIntExt(const Instruction *I);
131   bool selectMul(const Instruction *I);
132   bool selectShift(const Instruction *I);
133   bool selectBitCast(const Instruction *I);
134   bool selectFRem(const Instruction *I);
135   bool selectSDiv(const Instruction *I);
136   bool selectGetElementPtr(const Instruction *I);
137
138   // Utility helper routines.
139   bool isTypeLegal(Type *Ty, MVT &VT);
140   bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141   bool isValueAvailable(const Value *V) const;
142   bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143   bool computeCallAddress(const Value *V, Address &Addr);
144   bool simplifyAddress(Address &Addr, MVT VT);
145   void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146                             unsigned Flags, unsigned ScaleFactor,
147                             MachineMemOperand *MMO);
148   bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149   bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150                           unsigned Alignment);
151   bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152                          const Value *Cond);
153   bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154   bool optimizeSelect(const SelectInst *SI);
155   std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
156
157   // Emit helper routines.
158   unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
159                       const Value *RHS, bool SetFlags = false,
160                       bool WantResult = true,  bool IsZExt = false);
161   unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
162                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
163                          bool SetFlags = false, bool WantResult = true);
164   unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
165                          bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
166                          bool WantResult = true);
167   unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
168                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
169                          AArch64_AM::ShiftExtendType ShiftType,
170                          uint64_t ShiftImm, bool SetFlags = false,
171                          bool WantResult = true);
172   unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
173                          bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
174                           AArch64_AM::ShiftExtendType ExtType,
175                           uint64_t ShiftImm, bool SetFlags = false,
176                          bool WantResult = true);
177
178   // Emit functions.
179   bool emitCompareAndBranch(const BranchInst *BI);
180   bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
181   bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
182   bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
183   bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
184   unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
185                     MachineMemOperand *MMO = nullptr);
186   bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
187                  MachineMemOperand *MMO = nullptr);
188   unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
189   unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
190   unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
191                    bool SetFlags = false, bool WantResult = true,
192                    bool IsZExt = false);
193   unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
194   unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
195                    bool SetFlags = false, bool WantResult = true,
196                    bool IsZExt = false);
197   unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198                        unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
199   unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
200                        unsigned RHSReg, bool RHSIsKill,
201                        AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
202                        bool WantResult = true);
203   unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
204                          const Value *RHS);
205   unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206                             bool LHSIsKill, uint64_t Imm);
207   unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
208                             bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
209                             uint64_t ShiftImm);
210   unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
211   unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212                       unsigned Op1, bool Op1IsKill);
213   unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214                         unsigned Op1, bool Op1IsKill);
215   unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
216                         unsigned Op1, bool Op1IsKill);
217   unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218                       unsigned Op1Reg, bool Op1IsKill);
219   unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220                       uint64_t Imm, bool IsZExt = true);
221   unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222                       unsigned Op1Reg, bool Op1IsKill);
223   unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224                       uint64_t Imm, bool IsZExt = true);
225   unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
226                       unsigned Op1Reg, bool Op1IsKill);
227   unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
228                       uint64_t Imm, bool IsZExt = false);
229
230   unsigned materializeInt(const ConstantInt *CI, MVT VT);
231   unsigned materializeFP(const ConstantFP *CFP, MVT VT);
232   unsigned materializeGV(const GlobalValue *GV);
233
234   // Call handling routines.
235 private:
236   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
237   bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
238                        unsigned &NumBytes);
239   bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
240
241 public:
242   // Backend specific FastISel code.
243   unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
244   unsigned fastMaterializeConstant(const Constant *C) override;
245   unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
246
247   explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
248                          const TargetLibraryInfo *LibInfo)
249       : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
250     Subtarget = &TM.getSubtarget<AArch64Subtarget>();
251     Context = &FuncInfo.Fn->getContext();
252   }
253
254   bool fastSelectInstruction(const Instruction *I) override;
255
256 #include "AArch64GenFastISel.inc"
257 };
258
259 } // end anonymous namespace
260
261 #include "AArch64GenCallingConv.inc"
262
263 /// \brief Check if the sign-/zero-extend will be a noop.
264 static bool isIntExtFree(const Instruction *I) {
265   assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
266          "Unexpected integer extend instruction.");
267   assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
268          "Unexpected value type.");
269   bool IsZExt = isa<ZExtInst>(I);
270
271   if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
272     if (LI->hasOneUse())
273       return true;
274
275   if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
276     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
277       return true;
278
279   return false;
280 }
281
282 /// \brief Determine the implicit scale factor that is applied by a memory
283 /// operation for a given value type.
284 static unsigned getImplicitScaleFactor(MVT VT) {
285   switch (VT.SimpleTy) {
286   default:
287     return 0;    // invalid
288   case MVT::i1:  // fall-through
289   case MVT::i8:
290     return 1;
291   case MVT::i16:
292     return 2;
293   case MVT::i32: // fall-through
294   case MVT::f32:
295     return 4;
296   case MVT::i64: // fall-through
297   case MVT::f64:
298     return 8;
299   }
300 }
301
302 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
303   if (CC == CallingConv::WebKit_JS)
304     return CC_AArch64_WebKit_JS;
305   if (CC == CallingConv::GHC)
306     return CC_AArch64_GHC;
307   return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
308 }
309
310 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
311   assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
312          "Alloca should always return a pointer.");
313
314   // Don't handle dynamic allocas.
315   if (!FuncInfo.StaticAllocaMap.count(AI))
316     return 0;
317
318   DenseMap<const AllocaInst *, int>::iterator SI =
319       FuncInfo.StaticAllocaMap.find(AI);
320
321   if (SI != FuncInfo.StaticAllocaMap.end()) {
322     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
323     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
324             ResultReg)
325         .addFrameIndex(SI->second)
326         .addImm(0)
327         .addImm(0);
328     return ResultReg;
329   }
330
331   return 0;
332 }
333
334 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
335   if (VT > MVT::i64)
336     return 0;
337
338   if (!CI->isZero())
339     return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
340
341   // Create a copy from the zero register to materialize a "0" value.
342   const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
343                                                    : &AArch64::GPR32RegClass;
344   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
345   unsigned ResultReg = createResultReg(RC);
346   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
347           ResultReg).addReg(ZeroReg, getKillRegState(true));
348   return ResultReg;
349 }
350
351 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
352   // Positive zero (+0.0) has to be materialized with a fmov from the zero
353   // register, because the immediate version of fmov cannot encode zero.
354   if (CFP->isNullValue())
355     return fastMaterializeFloatZero(CFP);
356
357   if (VT != MVT::f32 && VT != MVT::f64)
358     return 0;
359
360   const APFloat Val = CFP->getValueAPF();
361   bool Is64Bit = (VT == MVT::f64);
362   // This checks to see if we can use FMOV instructions to materialize
363   // a constant, otherwise we have to materialize via the constant pool.
364   if (TLI.isFPImmLegal(Val, VT)) {
365     int Imm =
366         Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
367     assert((Imm != -1) && "Cannot encode floating-point constant.");
368     unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
369     return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
370   }
371
372   // For the MachO large code model materialize the FP constant in code.
373   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
374     unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
375     const TargetRegisterClass *RC = Is64Bit ?
376         &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
377
378     unsigned TmpReg = createResultReg(RC);
379     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
380         .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
381
382     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
383     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
384             TII.get(TargetOpcode::COPY), ResultReg)
385         .addReg(TmpReg, getKillRegState(true));
386
387     return ResultReg;
388   }
389
390   // Materialize via constant pool.  MachineConstantPool wants an explicit
391   // alignment.
392   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
393   if (Align == 0)
394     Align = DL.getTypeAllocSize(CFP->getType());
395
396   unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
397   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
398   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
399           ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
400
401   unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
402   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
403   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
404       .addReg(ADRPReg)
405       .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
406   return ResultReg;
407 }
408
409 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
410   // We can't handle thread-local variables quickly yet.
411   if (GV->isThreadLocal())
412     return 0;
413
414   // MachO still uses GOT for large code-model accesses, but ELF requires
415   // movz/movk sequences, which FastISel doesn't handle yet.
416   if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
417     return 0;
418
419   unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
420
421   EVT DestEVT = TLI.getValueType(GV->getType(), true);
422   if (!DestEVT.isSimple())
423     return 0;
424
425   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
426   unsigned ResultReg;
427
428   if (OpFlags & AArch64II::MO_GOT) {
429     // ADRP + LDRX
430     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
431             ADRPReg)
432       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
433
434     ResultReg = createResultReg(&AArch64::GPR64RegClass);
435     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
436             ResultReg)
437       .addReg(ADRPReg)
438       .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
439                         AArch64II::MO_NC);
440   } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
441     // We can't handle addresses loaded from a constant pool quickly yet.
442     return 0;
443   } else {
444     // ADRP + ADDX
445     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
446             ADRPReg)
447       .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
448
449     ResultReg = createResultReg(&AArch64::GPR64spRegClass);
450     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
451             ResultReg)
452       .addReg(ADRPReg)
453       .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
454       .addImm(0);
455   }
456   return ResultReg;
457 }
458
459 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
460   EVT CEVT = TLI.getValueType(C->getType(), true);
461
462   // Only handle simple types.
463   if (!CEVT.isSimple())
464     return 0;
465   MVT VT = CEVT.getSimpleVT();
466
467   if (const auto *CI = dyn_cast<ConstantInt>(C))
468     return materializeInt(CI, VT);
469   else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
470     return materializeFP(CFP, VT);
471   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
472     return materializeGV(GV);
473
474   return 0;
475 }
476
477 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
478   assert(CFP->isNullValue() &&
479          "Floating-point constant is not a positive zero.");
480   MVT VT;
481   if (!isTypeLegal(CFP->getType(), VT))
482     return 0;
483
484   if (VT != MVT::f32 && VT != MVT::f64)
485     return 0;
486
487   bool Is64Bit = (VT == MVT::f64);
488   unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
489   unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
490   return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
491 }
492
493 /// \brief Check if the multiply is by a power-of-2 constant.
494 static bool isMulPowOf2(const Value *I) {
495   if (const auto *MI = dyn_cast<MulOperator>(I)) {
496     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
497       if (C->getValue().isPowerOf2())
498         return true;
499     if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
500       if (C->getValue().isPowerOf2())
501         return true;
502   }
503   return false;
504 }
505
506 // Computes the address to get to an object.
507 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
508 {
509   const User *U = nullptr;
510   unsigned Opcode = Instruction::UserOp1;
511   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
512     // Don't walk into other basic blocks unless the object is an alloca from
513     // another block, otherwise it may not have a virtual register assigned.
514     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
515         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
516       Opcode = I->getOpcode();
517       U = I;
518     }
519   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
520     Opcode = C->getOpcode();
521     U = C;
522   }
523
524   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
525     if (Ty->getAddressSpace() > 255)
526       // Fast instruction selection doesn't support the special
527       // address spaces.
528       return false;
529
530   switch (Opcode) {
531   default:
532     break;
533   case Instruction::BitCast: {
534     // Look through bitcasts.
535     return computeAddress(U->getOperand(0), Addr, Ty);
536   }
537   case Instruction::IntToPtr: {
538     // Look past no-op inttoptrs.
539     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
540       return computeAddress(U->getOperand(0), Addr, Ty);
541     break;
542   }
543   case Instruction::PtrToInt: {
544     // Look past no-op ptrtoints.
545     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
546       return computeAddress(U->getOperand(0), Addr, Ty);
547     break;
548   }
549   case Instruction::GetElementPtr: {
550     Address SavedAddr = Addr;
551     uint64_t TmpOffset = Addr.getOffset();
552
553     // Iterate through the GEP folding the constants into offsets where
554     // we can.
555     gep_type_iterator GTI = gep_type_begin(U);
556     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
557          ++i, ++GTI) {
558       const Value *Op = *i;
559       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
560         const StructLayout *SL = DL.getStructLayout(STy);
561         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
562         TmpOffset += SL->getElementOffset(Idx);
563       } else {
564         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
565         for (;;) {
566           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
567             // Constant-offset addressing.
568             TmpOffset += CI->getSExtValue() * S;
569             break;
570           }
571           if (canFoldAddIntoGEP(U, Op)) {
572             // A compatible add with a constant operand. Fold the constant.
573             ConstantInt *CI =
574                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
575             TmpOffset += CI->getSExtValue() * S;
576             // Iterate on the other operand.
577             Op = cast<AddOperator>(Op)->getOperand(0);
578             continue;
579           }
580           // Unsupported
581           goto unsupported_gep;
582         }
583       }
584     }
585
586     // Try to grab the base operand now.
587     Addr.setOffset(TmpOffset);
588     if (computeAddress(U->getOperand(0), Addr, Ty))
589       return true;
590
591     // We failed, restore everything and try the other options.
592     Addr = SavedAddr;
593
594   unsupported_gep:
595     break;
596   }
597   case Instruction::Alloca: {
598     const AllocaInst *AI = cast<AllocaInst>(Obj);
599     DenseMap<const AllocaInst *, int>::iterator SI =
600         FuncInfo.StaticAllocaMap.find(AI);
601     if (SI != FuncInfo.StaticAllocaMap.end()) {
602       Addr.setKind(Address::FrameIndexBase);
603       Addr.setFI(SI->second);
604       return true;
605     }
606     break;
607   }
608   case Instruction::Add: {
609     // Adds of constants are common and easy enough.
610     const Value *LHS = U->getOperand(0);
611     const Value *RHS = U->getOperand(1);
612
613     if (isa<ConstantInt>(LHS))
614       std::swap(LHS, RHS);
615
616     if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
617       Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
618       return computeAddress(LHS, Addr, Ty);
619     }
620
621     Address Backup = Addr;
622     if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
623       return true;
624     Addr = Backup;
625
626     break;
627   }
628   case Instruction::Sub: {
629     // Subs of constants are common and easy enough.
630     const Value *LHS = U->getOperand(0);
631     const Value *RHS = U->getOperand(1);
632
633     if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
634       Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
635       return computeAddress(LHS, Addr, Ty);
636     }
637     break;
638   }
639   case Instruction::Shl: {
640     if (Addr.getOffsetReg())
641       break;
642
643     const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
644     if (!CI)
645       break;
646
647     unsigned Val = CI->getZExtValue();
648     if (Val < 1 || Val > 3)
649       break;
650
651     uint64_t NumBytes = 0;
652     if (Ty && Ty->isSized()) {
653       uint64_t NumBits = DL.getTypeSizeInBits(Ty);
654       NumBytes = NumBits / 8;
655       if (!isPowerOf2_64(NumBits))
656         NumBytes = 0;
657     }
658
659     if (NumBytes != (1ULL << Val))
660       break;
661
662     Addr.setShift(Val);
663     Addr.setExtendType(AArch64_AM::LSL);
664
665     const Value *Src = U->getOperand(0);
666     if (const auto *I = dyn_cast<Instruction>(Src))
667       if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
668         Src = I;
669
670     // Fold the zext or sext when it won't become a noop.
671     if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
672       if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
673           Addr.setExtendType(AArch64_AM::UXTW);
674           Src = ZE->getOperand(0);
675       }
676     } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
677       if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
678         Addr.setExtendType(AArch64_AM::SXTW);
679         Src = SE->getOperand(0);
680       }
681     }
682
683     if (const auto *AI = dyn_cast<BinaryOperator>(Src))
684       if (AI->getOpcode() == Instruction::And) {
685         const Value *LHS = AI->getOperand(0);
686         const Value *RHS = AI->getOperand(1);
687
688         if (const auto *C = dyn_cast<ConstantInt>(LHS))
689           if (C->getValue() == 0xffffffff)
690             std::swap(LHS, RHS);
691
692         if (const auto *C = dyn_cast<ConstantInt>(RHS))
693           if (C->getValue() == 0xffffffff) {
694             Addr.setExtendType(AArch64_AM::UXTW);
695             unsigned Reg = getRegForValue(LHS);
696             if (!Reg)
697               return false;
698             bool RegIsKill = hasTrivialKill(LHS);
699             Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
700                                              AArch64::sub_32);
701             Addr.setOffsetReg(Reg);
702             return true;
703           }
704       }
705
706     unsigned Reg = getRegForValue(Src);
707     if (!Reg)
708       return false;
709     Addr.setOffsetReg(Reg);
710     return true;
711   }
712   case Instruction::Mul: {
713     if (Addr.getOffsetReg())
714       break;
715
716     if (!isMulPowOf2(U))
717       break;
718
719     const Value *LHS = U->getOperand(0);
720     const Value *RHS = U->getOperand(1);
721
722     // Canonicalize power-of-2 value to the RHS.
723     if (const auto *C = dyn_cast<ConstantInt>(LHS))
724       if (C->getValue().isPowerOf2())
725         std::swap(LHS, RHS);
726
727     assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
728     const auto *C = cast<ConstantInt>(RHS);
729     unsigned Val = C->getValue().logBase2();
730     if (Val < 1 || Val > 3)
731       break;
732
733     uint64_t NumBytes = 0;
734     if (Ty && Ty->isSized()) {
735       uint64_t NumBits = DL.getTypeSizeInBits(Ty);
736       NumBytes = NumBits / 8;
737       if (!isPowerOf2_64(NumBits))
738         NumBytes = 0;
739     }
740
741     if (NumBytes != (1ULL << Val))
742       break;
743
744     Addr.setShift(Val);
745     Addr.setExtendType(AArch64_AM::LSL);
746
747     const Value *Src = LHS;
748     if (const auto *I = dyn_cast<Instruction>(Src))
749       if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
750         Src = I;
751
752
753     // Fold the zext or sext when it won't become a noop.
754     if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
755       if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
756         Addr.setExtendType(AArch64_AM::UXTW);
757         Src = ZE->getOperand(0);
758       }
759     } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
760       if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
761         Addr.setExtendType(AArch64_AM::SXTW);
762         Src = SE->getOperand(0);
763       }
764     }
765
766     unsigned Reg = getRegForValue(Src);
767     if (!Reg)
768       return false;
769     Addr.setOffsetReg(Reg);
770     return true;
771   }
772   case Instruction::And: {
773     if (Addr.getOffsetReg())
774       break;
775
776     if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
777       break;
778
779     const Value *LHS = U->getOperand(0);
780     const Value *RHS = U->getOperand(1);
781
782     if (const auto *C = dyn_cast<ConstantInt>(LHS))
783       if (C->getValue() == 0xffffffff)
784         std::swap(LHS, RHS);
785
786     if (const auto *C = dyn_cast<ConstantInt>(RHS))
787       if (C->getValue() == 0xffffffff) {
788         Addr.setShift(0);
789         Addr.setExtendType(AArch64_AM::LSL);
790         Addr.setExtendType(AArch64_AM::UXTW);
791
792         unsigned Reg = getRegForValue(LHS);
793         if (!Reg)
794           return false;
795         bool RegIsKill = hasTrivialKill(LHS);
796         Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
797                                          AArch64::sub_32);
798         Addr.setOffsetReg(Reg);
799         return true;
800       }
801     break;
802   }
803   case Instruction::SExt:
804   case Instruction::ZExt: {
805     if (!Addr.getReg() || Addr.getOffsetReg())
806       break;
807
808     const Value *Src = nullptr;
809     // Fold the zext or sext when it won't become a noop.
810     if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
811       if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
812         Addr.setExtendType(AArch64_AM::UXTW);
813         Src = ZE->getOperand(0);
814       }
815     } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
816       if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
817         Addr.setExtendType(AArch64_AM::SXTW);
818         Src = SE->getOperand(0);
819       }
820     }
821
822     if (!Src)
823       break;
824
825     Addr.setShift(0);
826     unsigned Reg = getRegForValue(Src);
827     if (!Reg)
828       return false;
829     Addr.setOffsetReg(Reg);
830     return true;
831   }
832   } // end switch
833
834   if (Addr.isRegBase() && !Addr.getReg()) {
835     unsigned Reg = getRegForValue(Obj);
836     if (!Reg)
837       return false;
838     Addr.setReg(Reg);
839     return true;
840   }
841
842   if (!Addr.getOffsetReg()) {
843     unsigned Reg = getRegForValue(Obj);
844     if (!Reg)
845       return false;
846     Addr.setOffsetReg(Reg);
847     return true;
848   }
849
850   return false;
851 }
852
853 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
854   const User *U = nullptr;
855   unsigned Opcode = Instruction::UserOp1;
856   bool InMBB = true;
857
858   if (const auto *I = dyn_cast<Instruction>(V)) {
859     Opcode = I->getOpcode();
860     U = I;
861     InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
862   } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
863     Opcode = C->getOpcode();
864     U = C;
865   }
866
867   switch (Opcode) {
868   default: break;
869   case Instruction::BitCast:
870     // Look past bitcasts if its operand is in the same BB.
871     if (InMBB)
872       return computeCallAddress(U->getOperand(0), Addr);
873     break;
874   case Instruction::IntToPtr:
875     // Look past no-op inttoptrs if its operand is in the same BB.
876     if (InMBB &&
877         TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
878       return computeCallAddress(U->getOperand(0), Addr);
879     break;
880   case Instruction::PtrToInt:
881     // Look past no-op ptrtoints if its operand is in the same BB.
882     if (InMBB &&
883         TLI.getValueType(U->getType()) == TLI.getPointerTy())
884       return computeCallAddress(U->getOperand(0), Addr);
885     break;
886   }
887
888   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
889     Addr.setGlobalValue(GV);
890     return true;
891   }
892
893   // If all else fails, try to materialize the value in a register.
894   if (!Addr.getGlobalValue()) {
895     Addr.setReg(getRegForValue(V));
896     return Addr.getReg() != 0;
897   }
898
899   return false;
900 }
901
902
903 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
904   EVT evt = TLI.getValueType(Ty, true);
905
906   // Only handle simple types.
907   if (evt == MVT::Other || !evt.isSimple())
908     return false;
909   VT = evt.getSimpleVT();
910
911   // This is a legal type, but it's not something we handle in fast-isel.
912   if (VT == MVT::f128)
913     return false;
914
915   // Handle all other legal types, i.e. a register that will directly hold this
916   // value.
917   return TLI.isTypeLegal(VT);
918 }
919
920 /// \brief Determine if the value type is supported by FastISel.
921 ///
922 /// FastISel for AArch64 can handle more value types than are legal. This adds
923 /// simple value type such as i1, i8, and i16.
924 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
925   if (Ty->isVectorTy() && !IsVectorAllowed)
926     return false;
927
928   if (isTypeLegal(Ty, VT))
929     return true;
930
931   // If this is a type than can be sign or zero-extended to a basic operation
932   // go ahead and accept it now.
933   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
934     return true;
935
936   return false;
937 }
938
939 bool AArch64FastISel::isValueAvailable(const Value *V) const {
940   if (!isa<Instruction>(V))
941     return true;
942
943   const auto *I = cast<Instruction>(V);
944   if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
945     return true;
946
947   return false;
948 }
949
950 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
951   unsigned ScaleFactor = getImplicitScaleFactor(VT);
952   if (!ScaleFactor)
953     return false;
954
955   bool ImmediateOffsetNeedsLowering = false;
956   bool RegisterOffsetNeedsLowering = false;
957   int64_t Offset = Addr.getOffset();
958   if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
959     ImmediateOffsetNeedsLowering = true;
960   else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
961            !isUInt<12>(Offset / ScaleFactor))
962     ImmediateOffsetNeedsLowering = true;
963
964   // Cannot encode an offset register and an immediate offset in the same
965   // instruction. Fold the immediate offset into the load/store instruction and
966   // emit an additonal add to take care of the offset register.
967   if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
968     RegisterOffsetNeedsLowering = true;
969
970   // Cannot encode zero register as base.
971   if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
972     RegisterOffsetNeedsLowering = true;
973
974   // If this is a stack pointer and the offset needs to be simplified then put
975   // the alloca address into a register, set the base type back to register and
976   // continue. This should almost never happen.
977   if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
978   {
979     unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
980     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
981             ResultReg)
982       .addFrameIndex(Addr.getFI())
983       .addImm(0)
984       .addImm(0);
985     Addr.setKind(Address::RegBase);
986     Addr.setReg(ResultReg);
987   }
988
989   if (RegisterOffsetNeedsLowering) {
990     unsigned ResultReg = 0;
991     if (Addr.getReg()) {
992       if (Addr.getExtendType() == AArch64_AM::SXTW ||
993           Addr.getExtendType() == AArch64_AM::UXTW   )
994         ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
995                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
996                                   /*TODO:IsKill=*/false, Addr.getExtendType(),
997                                   Addr.getShift());
998       else
999         ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1000                                   /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1001                                   /*TODO:IsKill=*/false, AArch64_AM::LSL,
1002                                   Addr.getShift());
1003     } else {
1004       if (Addr.getExtendType() == AArch64_AM::UXTW)
1005         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1006                                /*Op0IsKill=*/false, Addr.getShift(),
1007                                /*IsZExt=*/true);
1008       else if (Addr.getExtendType() == AArch64_AM::SXTW)
1009         ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1010                                /*Op0IsKill=*/false, Addr.getShift(),
1011                                /*IsZExt=*/false);
1012       else
1013         ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1014                                /*Op0IsKill=*/false, Addr.getShift());
1015     }
1016     if (!ResultReg)
1017       return false;
1018
1019     Addr.setReg(ResultReg);
1020     Addr.setOffsetReg(0);
1021     Addr.setShift(0);
1022     Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1023   }
1024
1025   // Since the offset is too large for the load/store instruction get the
1026   // reg+offset into a register.
1027   if (ImmediateOffsetNeedsLowering) {
1028     unsigned ResultReg;
1029     if (Addr.getReg())
1030       // Try to fold the immediate into the add instruction.
1031       ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1032     else
1033       ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1034
1035     if (!ResultReg)
1036       return false;
1037     Addr.setReg(ResultReg);
1038     Addr.setOffset(0);
1039   }
1040   return true;
1041 }
1042
1043 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1044                                            const MachineInstrBuilder &MIB,
1045                                            unsigned Flags,
1046                                            unsigned ScaleFactor,
1047                                            MachineMemOperand *MMO) {
1048   int64_t Offset = Addr.getOffset() / ScaleFactor;
1049   // Frame base works a bit differently. Handle it separately.
1050   if (Addr.isFIBase()) {
1051     int FI = Addr.getFI();
1052     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
1053     // and alignment should be based on the VT.
1054     MMO = FuncInfo.MF->getMachineMemOperand(
1055       MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1056       MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1057     // Now add the rest of the operands.
1058     MIB.addFrameIndex(FI).addImm(Offset);
1059   } else {
1060     assert(Addr.isRegBase() && "Unexpected address kind.");
1061     const MCInstrDesc &II = MIB->getDesc();
1062     unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1063     Addr.setReg(
1064       constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1065     Addr.setOffsetReg(
1066       constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1067     if (Addr.getOffsetReg()) {
1068       assert(Addr.getOffset() == 0 && "Unexpected offset");
1069       bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1070                       Addr.getExtendType() == AArch64_AM::SXTX;
1071       MIB.addReg(Addr.getReg());
1072       MIB.addReg(Addr.getOffsetReg());
1073       MIB.addImm(IsSigned);
1074       MIB.addImm(Addr.getShift() != 0);
1075     } else
1076       MIB.addReg(Addr.getReg()).addImm(Offset);
1077   }
1078
1079   if (MMO)
1080     MIB.addMemOperand(MMO);
1081 }
1082
1083 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1084                                      const Value *RHS, bool SetFlags,
1085                                      bool WantResult,  bool IsZExt) {
1086   AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1087   bool NeedExtend = false;
1088   switch (RetVT.SimpleTy) {
1089   default:
1090     return 0;
1091   case MVT::i1:
1092     NeedExtend = true;
1093     break;
1094   case MVT::i8:
1095     NeedExtend = true;
1096     ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1097     break;
1098   case MVT::i16:
1099     NeedExtend = true;
1100     ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1101     break;
1102   case MVT::i32:  // fall-through
1103   case MVT::i64:
1104     break;
1105   }
1106   MVT SrcVT = RetVT;
1107   RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1108
1109   // Canonicalize immediates to the RHS first.
1110   if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1111     std::swap(LHS, RHS);
1112
1113   // Canonicalize mul by power of 2 to the RHS.
1114   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1115     if (isMulPowOf2(LHS))
1116       std::swap(LHS, RHS);
1117
1118   // Canonicalize shift immediate to the RHS.
1119   if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1120     if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1121       if (isa<ConstantInt>(SI->getOperand(1)))
1122         if (SI->getOpcode() == Instruction::Shl  ||
1123             SI->getOpcode() == Instruction::LShr ||
1124             SI->getOpcode() == Instruction::AShr   )
1125           std::swap(LHS, RHS);
1126
1127   unsigned LHSReg = getRegForValue(LHS);
1128   if (!LHSReg)
1129     return 0;
1130   bool LHSIsKill = hasTrivialKill(LHS);
1131
1132   if (NeedExtend)
1133     LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1134
1135   unsigned ResultReg = 0;
1136   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1137     uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1138     if (C->isNegative())
1139       ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1140                                 SetFlags, WantResult);
1141     else
1142       ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1143                                 WantResult);
1144   } else if (const auto *C = dyn_cast<Constant>(RHS))
1145     if (C->isNullValue())
1146       ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1147                                 WantResult);
1148
1149   if (ResultReg)
1150     return ResultReg;
1151
1152   // Only extend the RHS within the instruction if there is a valid extend type.
1153   if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1154       isValueAvailable(RHS)) {
1155     if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1156       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1157         if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1158           unsigned RHSReg = getRegForValue(SI->getOperand(0));
1159           if (!RHSReg)
1160             return 0;
1161           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1162           return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1163                                RHSIsKill, ExtendType, C->getZExtValue(),
1164                                SetFlags, WantResult);
1165         }
1166     unsigned RHSReg = getRegForValue(RHS);
1167     if (!RHSReg)
1168       return 0;
1169     bool RHSIsKill = hasTrivialKill(RHS);
1170     return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1171                          ExtendType, 0, SetFlags, WantResult);
1172   }
1173
1174   // Check if the mul can be folded into the instruction.
1175   if (RHS->hasOneUse() && isValueAvailable(RHS))
1176     if (isMulPowOf2(RHS)) {
1177       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1178       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1179
1180       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1181         if (C->getValue().isPowerOf2())
1182           std::swap(MulLHS, MulRHS);
1183
1184       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1185       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1186       unsigned RHSReg = getRegForValue(MulLHS);
1187       if (!RHSReg)
1188         return 0;
1189       bool RHSIsKill = hasTrivialKill(MulLHS);
1190       return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1191                            AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1192     }
1193
1194   // Check if the shift can be folded into the instruction.
1195   if (RHS->hasOneUse() && isValueAvailable(RHS))
1196     if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1197       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1198         AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1199         switch (SI->getOpcode()) {
1200         default: break;
1201         case Instruction::Shl:  ShiftType = AArch64_AM::LSL; break;
1202         case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1203         case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1204         }
1205         uint64_t ShiftVal = C->getZExtValue();
1206         if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1207           unsigned RHSReg = getRegForValue(SI->getOperand(0));
1208           if (!RHSReg)
1209             return 0;
1210           bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1211           return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1212                                RHSIsKill, ShiftType, ShiftVal, SetFlags,
1213                                WantResult);
1214         }
1215       }
1216     }
1217
1218   unsigned RHSReg = getRegForValue(RHS);
1219   if (!RHSReg)
1220     return 0;
1221   bool RHSIsKill = hasTrivialKill(RHS);
1222
1223   if (NeedExtend)
1224     RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1225
1226   return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1227                        SetFlags, WantResult);
1228 }
1229
1230 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1231                                         bool LHSIsKill, unsigned RHSReg,
1232                                         bool RHSIsKill, bool SetFlags,
1233                                         bool WantResult) {
1234   assert(LHSReg && RHSReg && "Invalid register number.");
1235
1236   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1237     return 0;
1238
1239   static const unsigned OpcTable[2][2][2] = {
1240     { { AArch64::SUBWrr,  AArch64::SUBXrr  },
1241       { AArch64::ADDWrr,  AArch64::ADDXrr  }  },
1242     { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1243       { AArch64::ADDSWrr, AArch64::ADDSXrr }  }
1244   };
1245   bool Is64Bit = RetVT == MVT::i64;
1246   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1247   const TargetRegisterClass *RC =
1248       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1249   unsigned ResultReg;
1250   if (WantResult)
1251     ResultReg = createResultReg(RC);
1252   else
1253     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1254
1255   const MCInstrDesc &II = TII.get(Opc);
1256   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1257   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1258   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1259       .addReg(LHSReg, getKillRegState(LHSIsKill))
1260       .addReg(RHSReg, getKillRegState(RHSIsKill));
1261   return ResultReg;
1262 }
1263
1264 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1265                                         bool LHSIsKill, uint64_t Imm,
1266                                         bool SetFlags, bool WantResult) {
1267   assert(LHSReg && "Invalid register number.");
1268
1269   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1270     return 0;
1271
1272   unsigned ShiftImm;
1273   if (isUInt<12>(Imm))
1274     ShiftImm = 0;
1275   else if ((Imm & 0xfff000) == Imm) {
1276     ShiftImm = 12;
1277     Imm >>= 12;
1278   } else
1279     return 0;
1280
1281   static const unsigned OpcTable[2][2][2] = {
1282     { { AArch64::SUBWri,  AArch64::SUBXri  },
1283       { AArch64::ADDWri,  AArch64::ADDXri  }  },
1284     { { AArch64::SUBSWri, AArch64::SUBSXri },
1285       { AArch64::ADDSWri, AArch64::ADDSXri }  }
1286   };
1287   bool Is64Bit = RetVT == MVT::i64;
1288   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1289   const TargetRegisterClass *RC;
1290   if (SetFlags)
1291     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1292   else
1293     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1294   unsigned ResultReg;
1295   if (WantResult)
1296     ResultReg = createResultReg(RC);
1297   else
1298     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1299
1300   const MCInstrDesc &II = TII.get(Opc);
1301   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1302   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1303       .addReg(LHSReg, getKillRegState(LHSIsKill))
1304       .addImm(Imm)
1305       .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1306   return ResultReg;
1307 }
1308
1309 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1310                                         bool LHSIsKill, unsigned RHSReg,
1311                                         bool RHSIsKill,
1312                                         AArch64_AM::ShiftExtendType ShiftType,
1313                                         uint64_t ShiftImm, bool SetFlags,
1314                                         bool WantResult) {
1315   assert(LHSReg && RHSReg && "Invalid register number.");
1316
1317   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1318     return 0;
1319
1320   static const unsigned OpcTable[2][2][2] = {
1321     { { AArch64::SUBWrs,  AArch64::SUBXrs  },
1322       { AArch64::ADDWrs,  AArch64::ADDXrs  }  },
1323     { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1324       { AArch64::ADDSWrs, AArch64::ADDSXrs }  }
1325   };
1326   bool Is64Bit = RetVT == MVT::i64;
1327   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1328   const TargetRegisterClass *RC =
1329       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1330   unsigned ResultReg;
1331   if (WantResult)
1332     ResultReg = createResultReg(RC);
1333   else
1334     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1335
1336   const MCInstrDesc &II = TII.get(Opc);
1337   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1338   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1339   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1340       .addReg(LHSReg, getKillRegState(LHSIsKill))
1341       .addReg(RHSReg, getKillRegState(RHSIsKill))
1342       .addImm(getShifterImm(ShiftType, ShiftImm));
1343   return ResultReg;
1344 }
1345
1346 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1347                                         bool LHSIsKill, unsigned RHSReg,
1348                                         bool RHSIsKill,
1349                                         AArch64_AM::ShiftExtendType ExtType,
1350                                         uint64_t ShiftImm, bool SetFlags,
1351                                         bool WantResult) {
1352   assert(LHSReg && RHSReg && "Invalid register number.");
1353
1354   if (RetVT != MVT::i32 && RetVT != MVT::i64)
1355     return 0;
1356
1357   static const unsigned OpcTable[2][2][2] = {
1358     { { AArch64::SUBWrx,  AArch64::SUBXrx  },
1359       { AArch64::ADDWrx,  AArch64::ADDXrx  }  },
1360     { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1361       { AArch64::ADDSWrx, AArch64::ADDSXrx }  }
1362   };
1363   bool Is64Bit = RetVT == MVT::i64;
1364   unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1365   const TargetRegisterClass *RC = nullptr;
1366   if (SetFlags)
1367     RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1368   else
1369     RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1370   unsigned ResultReg;
1371   if (WantResult)
1372     ResultReg = createResultReg(RC);
1373   else
1374     ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1375
1376   const MCInstrDesc &II = TII.get(Opc);
1377   LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1378   RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1379   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1380       .addReg(LHSReg, getKillRegState(LHSIsKill))
1381       .addReg(RHSReg, getKillRegState(RHSIsKill))
1382       .addImm(getArithExtendImm(ExtType, ShiftImm));
1383   return ResultReg;
1384 }
1385
1386 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1387   Type *Ty = LHS->getType();
1388   EVT EVT = TLI.getValueType(Ty, true);
1389   if (!EVT.isSimple())
1390     return false;
1391   MVT VT = EVT.getSimpleVT();
1392
1393   switch (VT.SimpleTy) {
1394   default:
1395     return false;
1396   case MVT::i1:
1397   case MVT::i8:
1398   case MVT::i16:
1399   case MVT::i32:
1400   case MVT::i64:
1401     return emitICmp(VT, LHS, RHS, IsZExt);
1402   case MVT::f32:
1403   case MVT::f64:
1404     return emitFCmp(VT, LHS, RHS);
1405   }
1406 }
1407
1408 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1409                                bool IsZExt) {
1410   return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1411                  IsZExt) != 0;
1412 }
1413
1414 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1415                                   uint64_t Imm) {
1416   return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1417                        /*SetFlags=*/true, /*WantResult=*/false) != 0;
1418 }
1419
1420 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1421   if (RetVT != MVT::f32 && RetVT != MVT::f64)
1422     return false;
1423
1424   // Check to see if the 2nd operand is a constant that we can encode directly
1425   // in the compare.
1426   bool UseImm = false;
1427   if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1428     if (CFP->isZero() && !CFP->isNegative())
1429       UseImm = true;
1430
1431   unsigned LHSReg = getRegForValue(LHS);
1432   if (!LHSReg)
1433     return false;
1434   bool LHSIsKill = hasTrivialKill(LHS);
1435
1436   if (UseImm) {
1437     unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1438     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1439         .addReg(LHSReg, getKillRegState(LHSIsKill));
1440     return true;
1441   }
1442
1443   unsigned RHSReg = getRegForValue(RHS);
1444   if (!RHSReg)
1445     return false;
1446   bool RHSIsKill = hasTrivialKill(RHS);
1447
1448   unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1449   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1450       .addReg(LHSReg, getKillRegState(LHSIsKill))
1451       .addReg(RHSReg, getKillRegState(RHSIsKill));
1452   return true;
1453 }
1454
1455 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1456                                   bool SetFlags, bool WantResult, bool IsZExt) {
1457   return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1458                     IsZExt);
1459 }
1460
1461 /// \brief This method is a wrapper to simplify add emission.
1462 ///
1463 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1464 /// that fails, then try to materialize the immediate into a register and use
1465 /// emitAddSub_rr instead.
1466 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1467                                       int64_t Imm) {
1468   unsigned ResultReg;
1469   if (Imm < 0)
1470     ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1471   else
1472     ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1473
1474   if (ResultReg)
1475     return ResultReg;
1476
1477   unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1478   if (!CReg)
1479     return 0;
1480
1481   ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1482   return ResultReg;
1483 }
1484
1485 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1486                                   bool SetFlags, bool WantResult, bool IsZExt) {
1487   return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1488                     IsZExt);
1489 }
1490
1491 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1492                                       bool LHSIsKill, unsigned RHSReg,
1493                                       bool RHSIsKill, bool WantResult) {
1494   return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1495                        RHSIsKill, /*SetFlags=*/true, WantResult);
1496 }
1497
1498 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1499                                       bool LHSIsKill, unsigned RHSReg,
1500                                       bool RHSIsKill,
1501                                       AArch64_AM::ShiftExtendType ShiftType,
1502                                       uint64_t ShiftImm, bool WantResult) {
1503   return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1504                        RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1505                        WantResult);
1506 }
1507
1508 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1509                                         const Value *LHS, const Value *RHS) {
1510   // Canonicalize immediates to the RHS first.
1511   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1512     std::swap(LHS, RHS);
1513
1514   // Canonicalize mul by power-of-2 to the RHS.
1515   if (LHS->hasOneUse() && isValueAvailable(LHS))
1516     if (isMulPowOf2(LHS))
1517       std::swap(LHS, RHS);
1518
1519   // Canonicalize shift immediate to the RHS.
1520   if (LHS->hasOneUse() && isValueAvailable(LHS))
1521     if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1522       if (isa<ConstantInt>(SI->getOperand(1)))
1523         std::swap(LHS, RHS);
1524
1525   unsigned LHSReg = getRegForValue(LHS);
1526   if (!LHSReg)
1527     return 0;
1528   bool LHSIsKill = hasTrivialKill(LHS);
1529
1530   unsigned ResultReg = 0;
1531   if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1532     uint64_t Imm = C->getZExtValue();
1533     ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1534   }
1535   if (ResultReg)
1536     return ResultReg;
1537
1538   // Check if the mul can be folded into the instruction.
1539   if (RHS->hasOneUse() && isValueAvailable(RHS))
1540     if (isMulPowOf2(RHS)) {
1541       const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1542       const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1543
1544       if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1545         if (C->getValue().isPowerOf2())
1546           std::swap(MulLHS, MulRHS);
1547
1548       assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1549       uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1550
1551       unsigned RHSReg = getRegForValue(MulLHS);
1552       if (!RHSReg)
1553         return 0;
1554       bool RHSIsKill = hasTrivialKill(MulLHS);
1555       return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1556                               RHSIsKill, ShiftVal);
1557     }
1558
1559   // Check if the shift can be folded into the instruction.
1560   if (RHS->hasOneUse() && isValueAvailable(RHS))
1561     if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1562       if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1563         uint64_t ShiftVal = C->getZExtValue();
1564         unsigned RHSReg = getRegForValue(SI->getOperand(0));
1565         if (!RHSReg)
1566           return 0;
1567         bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1568         return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1569                                 RHSIsKill, ShiftVal);
1570       }
1571
1572   unsigned RHSReg = getRegForValue(RHS);
1573   if (!RHSReg)
1574     return 0;
1575   bool RHSIsKill = hasTrivialKill(RHS);
1576
1577   MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1578   ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1579   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1580     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1581     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1582   }
1583   return ResultReg;
1584 }
1585
1586 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1587                                            unsigned LHSReg, bool LHSIsKill,
1588                                            uint64_t Imm) {
1589   assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1590          "ISD nodes are not consecutive!");
1591   static const unsigned OpcTable[3][2] = {
1592     { AArch64::ANDWri, AArch64::ANDXri },
1593     { AArch64::ORRWri, AArch64::ORRXri },
1594     { AArch64::EORWri, AArch64::EORXri }
1595   };
1596   const TargetRegisterClass *RC;
1597   unsigned Opc;
1598   unsigned RegSize;
1599   switch (RetVT.SimpleTy) {
1600   default:
1601     return 0;
1602   case MVT::i1:
1603   case MVT::i8:
1604   case MVT::i16:
1605   case MVT::i32: {
1606     unsigned Idx = ISDOpc - ISD::AND;
1607     Opc = OpcTable[Idx][0];
1608     RC = &AArch64::GPR32spRegClass;
1609     RegSize = 32;
1610     break;
1611   }
1612   case MVT::i64:
1613     Opc = OpcTable[ISDOpc - ISD::AND][1];
1614     RC = &AArch64::GPR64spRegClass;
1615     RegSize = 64;
1616     break;
1617   }
1618
1619   if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1620     return 0;
1621
1622   unsigned ResultReg =
1623       fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1624                       AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1625   if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1626     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1627     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1628   }
1629   return ResultReg;
1630 }
1631
1632 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1633                                            unsigned LHSReg, bool LHSIsKill,
1634                                            unsigned RHSReg, bool RHSIsKill,
1635                                            uint64_t ShiftImm) {
1636   assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1637          "ISD nodes are not consecutive!");
1638   static const unsigned OpcTable[3][2] = {
1639     { AArch64::ANDWrs, AArch64::ANDXrs },
1640     { AArch64::ORRWrs, AArch64::ORRXrs },
1641     { AArch64::EORWrs, AArch64::EORXrs }
1642   };
1643   const TargetRegisterClass *RC;
1644   unsigned Opc;
1645   switch (RetVT.SimpleTy) {
1646   default:
1647     return 0;
1648   case MVT::i1:
1649   case MVT::i8:
1650   case MVT::i16:
1651   case MVT::i32:
1652     Opc = OpcTable[ISDOpc - ISD::AND][0];
1653     RC = &AArch64::GPR32RegClass;
1654     break;
1655   case MVT::i64:
1656     Opc = OpcTable[ISDOpc - ISD::AND][1];
1657     RC = &AArch64::GPR64RegClass;
1658     break;
1659   }
1660   unsigned ResultReg =
1661       fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1662                        AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1663   if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1664     uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1665     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1666   }
1667   return ResultReg;
1668 }
1669
1670 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1671                                      uint64_t Imm) {
1672   return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1673 }
1674
1675 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1676                                    bool WantZExt, MachineMemOperand *MMO) {
1677   // Simplify this down to something we can handle.
1678   if (!simplifyAddress(Addr, VT))
1679     return 0;
1680
1681   unsigned ScaleFactor = getImplicitScaleFactor(VT);
1682   if (!ScaleFactor)
1683     llvm_unreachable("Unexpected value type.");
1684
1685   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1686   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1687   bool UseScaled = true;
1688   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1689     UseScaled = false;
1690     ScaleFactor = 1;
1691   }
1692
1693   static const unsigned GPOpcTable[2][8][4] = {
1694     // Sign-extend.
1695     { { AArch64::LDURSBWi,  AArch64::LDURSHWi,  AArch64::LDURWi,
1696         AArch64::LDURXi  },
1697       { AArch64::LDURSBXi,  AArch64::LDURSHXi,  AArch64::LDURSWi,
1698         AArch64::LDURXi  },
1699       { AArch64::LDRSBWui,  AArch64::LDRSHWui,  AArch64::LDRWui,
1700         AArch64::LDRXui  },
1701       { AArch64::LDRSBXui,  AArch64::LDRSHXui,  AArch64::LDRSWui,
1702         AArch64::LDRXui  },
1703       { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1704         AArch64::LDRXroX },
1705       { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1706         AArch64::LDRXroX },
1707       { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1708         AArch64::LDRXroW },
1709       { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1710         AArch64::LDRXroW }
1711     },
1712     // Zero-extend.
1713     { { AArch64::LDURBBi,   AArch64::LDURHHi,   AArch64::LDURWi,
1714         AArch64::LDURXi  },
1715       { AArch64::LDURBBi,   AArch64::LDURHHi,   AArch64::LDURWi,
1716         AArch64::LDURXi  },
1717       { AArch64::LDRBBui,   AArch64::LDRHHui,   AArch64::LDRWui,
1718         AArch64::LDRXui  },
1719       { AArch64::LDRBBui,   AArch64::LDRHHui,   AArch64::LDRWui,
1720         AArch64::LDRXui  },
1721       { AArch64::LDRBBroX,  AArch64::LDRHHroX,  AArch64::LDRWroX,
1722         AArch64::LDRXroX },
1723       { AArch64::LDRBBroX,  AArch64::LDRHHroX,  AArch64::LDRWroX,
1724         AArch64::LDRXroX },
1725       { AArch64::LDRBBroW,  AArch64::LDRHHroW,  AArch64::LDRWroW,
1726         AArch64::LDRXroW },
1727       { AArch64::LDRBBroW,  AArch64::LDRHHroW,  AArch64::LDRWroW,
1728         AArch64::LDRXroW }
1729     }
1730   };
1731
1732   static const unsigned FPOpcTable[4][2] = {
1733     { AArch64::LDURSi,  AArch64::LDURDi  },
1734     { AArch64::LDRSui,  AArch64::LDRDui  },
1735     { AArch64::LDRSroX, AArch64::LDRDroX },
1736     { AArch64::LDRSroW, AArch64::LDRDroW }
1737   };
1738
1739   unsigned Opc;
1740   const TargetRegisterClass *RC;
1741   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1742                       Addr.getOffsetReg();
1743   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1744   if (Addr.getExtendType() == AArch64_AM::UXTW ||
1745       Addr.getExtendType() == AArch64_AM::SXTW)
1746     Idx++;
1747
1748   bool IsRet64Bit = RetVT == MVT::i64;
1749   switch (VT.SimpleTy) {
1750   default:
1751     llvm_unreachable("Unexpected value type.");
1752   case MVT::i1: // Intentional fall-through.
1753   case MVT::i8:
1754     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1755     RC = (IsRet64Bit && !WantZExt) ?
1756              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1757     break;
1758   case MVT::i16:
1759     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1760     RC = (IsRet64Bit && !WantZExt) ?
1761              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1762     break;
1763   case MVT::i32:
1764     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1765     RC = (IsRet64Bit && !WantZExt) ?
1766              &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1767     break;
1768   case MVT::i64:
1769     Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1770     RC = &AArch64::GPR64RegClass;
1771     break;
1772   case MVT::f32:
1773     Opc = FPOpcTable[Idx][0];
1774     RC = &AArch64::FPR32RegClass;
1775     break;
1776   case MVT::f64:
1777     Opc = FPOpcTable[Idx][1];
1778     RC = &AArch64::FPR64RegClass;
1779     break;
1780   }
1781
1782   // Create the base instruction, then add the operands.
1783   unsigned ResultReg = createResultReg(RC);
1784   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1785                                     TII.get(Opc), ResultReg);
1786   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1787
1788   // Loading an i1 requires special handling.
1789   if (VT == MVT::i1) {
1790     unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1791     assert(ANDReg && "Unexpected AND instruction emission failure.");
1792     ResultReg = ANDReg;
1793   }
1794
1795   // For zero-extending loads to 64bit we emit a 32bit load and then convert
1796   // the 32bit reg to a 64bit reg.
1797   if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1798     unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1799     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1800             TII.get(AArch64::SUBREG_TO_REG), Reg64)
1801         .addImm(0)
1802         .addReg(ResultReg, getKillRegState(true))
1803         .addImm(AArch64::sub_32);
1804     ResultReg = Reg64;
1805   }
1806   return ResultReg;
1807 }
1808
1809 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1810   MVT VT;
1811   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1812     return false;
1813
1814   if (VT.isVector())
1815     return selectOperator(I, I->getOpcode());
1816
1817   unsigned ResultReg;
1818   switch (I->getOpcode()) {
1819   default:
1820     llvm_unreachable("Unexpected instruction.");
1821   case Instruction::Add:
1822     ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1823     break;
1824   case Instruction::Sub:
1825     ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1826     break;
1827   }
1828   if (!ResultReg)
1829     return false;
1830
1831   updateValueMap(I, ResultReg);
1832   return true;
1833 }
1834
1835 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1836   MVT VT;
1837   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1838     return false;
1839
1840   if (VT.isVector())
1841     return selectOperator(I, I->getOpcode());
1842
1843   unsigned ResultReg;
1844   switch (I->getOpcode()) {
1845   default:
1846     llvm_unreachable("Unexpected instruction.");
1847   case Instruction::And:
1848     ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1849     break;
1850   case Instruction::Or:
1851     ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1852     break;
1853   case Instruction::Xor:
1854     ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1855     break;
1856   }
1857   if (!ResultReg)
1858     return false;
1859
1860   updateValueMap(I, ResultReg);
1861   return true;
1862 }
1863
1864 bool AArch64FastISel::selectLoad(const Instruction *I) {
1865   MVT VT;
1866   // Verify we have a legal type before going any further.  Currently, we handle
1867   // simple types that will directly fit in a register (i32/f32/i64/f64) or
1868   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1869   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1870       cast<LoadInst>(I)->isAtomic())
1871     return false;
1872
1873   // See if we can handle this address.
1874   Address Addr;
1875   if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1876     return false;
1877
1878   // Fold the following sign-/zero-extend into the load instruction.
1879   bool WantZExt = true;
1880   MVT RetVT = VT;
1881   const Value *IntExtVal = nullptr;
1882   if (I->hasOneUse()) {
1883     if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1884       if (isTypeSupported(ZE->getType(), RetVT))
1885         IntExtVal = ZE;
1886       else
1887         RetVT = VT;
1888     } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1889       if (isTypeSupported(SE->getType(), RetVT))
1890         IntExtVal = SE;
1891       else
1892         RetVT = VT;
1893       WantZExt = false;
1894     }
1895   }
1896
1897   unsigned ResultReg =
1898       emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1899   if (!ResultReg)
1900     return false;
1901
1902   // There are a few different cases we have to handle, because the load or the
1903   // sign-/zero-extend might not be selected by FastISel if we fall-back to
1904   // SelectionDAG. There is also an ordering issue when both instructions are in
1905   // different basic blocks.
1906   // 1.) The load instruction is selected by FastISel, but the integer extend
1907   //     not. This usually happens when the integer extend is in a different
1908   //     basic block and SelectionDAG took over for that basic block.
1909   // 2.) The load instruction is selected before the integer extend. This only
1910   //     happens when the integer extend is in a different basic block.
1911   // 3.) The load instruction is selected by SelectionDAG and the integer extend
1912   //     by FastISel. This happens if there are instructions between the load
1913   //     and the integer extend that couldn't be selected by FastISel.
1914   if (IntExtVal) {
1915     // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1916     // could select it. Emit a copy to subreg if necessary. FastISel will remove
1917     // it when it selects the integer extend.
1918     unsigned Reg = lookUpRegForValue(IntExtVal);
1919     if (!Reg) {
1920       if (RetVT == MVT::i64 && VT <= MVT::i32) {
1921         if (WantZExt) {
1922           // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1923           std::prev(FuncInfo.InsertPt)->eraseFromParent();
1924           ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1925         } else
1926           ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1927                                                  /*IsKill=*/true,
1928                                                  AArch64::sub_32);
1929       }
1930       updateValueMap(I, ResultReg);
1931       return true;
1932     }
1933
1934     // The integer extend has already been emitted - delete all the instructions
1935     // that have been emitted by the integer extend lowering code and use the
1936     // result from the load instruction directly.
1937     while (Reg) {
1938       auto *MI = MRI.getUniqueVRegDef(Reg);
1939       if (!MI)
1940         break;
1941       Reg = 0;
1942       for (auto &Opnd : MI->uses()) {
1943         if (Opnd.isReg()) {
1944           Reg = Opnd.getReg();
1945           break;
1946         }
1947       }
1948       MI->eraseFromParent();
1949     }
1950     updateValueMap(IntExtVal, ResultReg);
1951     return true;
1952   }
1953
1954   updateValueMap(I, ResultReg);
1955   return true;
1956 }
1957
1958 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1959                                 MachineMemOperand *MMO) {
1960   // Simplify this down to something we can handle.
1961   if (!simplifyAddress(Addr, VT))
1962     return false;
1963
1964   unsigned ScaleFactor = getImplicitScaleFactor(VT);
1965   if (!ScaleFactor)
1966     llvm_unreachable("Unexpected value type.");
1967
1968   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1969   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1970   bool UseScaled = true;
1971   if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1972     UseScaled = false;
1973     ScaleFactor = 1;
1974   }
1975
1976   static const unsigned OpcTable[4][6] = {
1977     { AArch64::STURBBi,  AArch64::STURHHi,  AArch64::STURWi,  AArch64::STURXi,
1978       AArch64::STURSi,   AArch64::STURDi },
1979     { AArch64::STRBBui,  AArch64::STRHHui,  AArch64::STRWui,  AArch64::STRXui,
1980       AArch64::STRSui,   AArch64::STRDui },
1981     { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1982       AArch64::STRSroX,  AArch64::STRDroX },
1983     { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1984       AArch64::STRSroW,  AArch64::STRDroW }
1985   };
1986
1987   unsigned Opc;
1988   bool VTIsi1 = false;
1989   bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1990                       Addr.getOffsetReg();
1991   unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1992   if (Addr.getExtendType() == AArch64_AM::UXTW ||
1993       Addr.getExtendType() == AArch64_AM::SXTW)
1994     Idx++;
1995
1996   switch (VT.SimpleTy) {
1997   default: llvm_unreachable("Unexpected value type.");
1998   case MVT::i1:  VTIsi1 = true;
1999   case MVT::i8:  Opc = OpcTable[Idx][0]; break;
2000   case MVT::i16: Opc = OpcTable[Idx][1]; break;
2001   case MVT::i32: Opc = OpcTable[Idx][2]; break;
2002   case MVT::i64: Opc = OpcTable[Idx][3]; break;
2003   case MVT::f32: Opc = OpcTable[Idx][4]; break;
2004   case MVT::f64: Opc = OpcTable[Idx][5]; break;
2005   }
2006
2007   // Storing an i1 requires special handling.
2008   if (VTIsi1 && SrcReg != AArch64::WZR) {
2009     unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2010     assert(ANDReg && "Unexpected AND instruction emission failure.");
2011     SrcReg = ANDReg;
2012   }
2013   // Create the base instruction, then add the operands.
2014   const MCInstrDesc &II = TII.get(Opc);
2015   SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2016   MachineInstrBuilder MIB =
2017       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2018   addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2019
2020   return true;
2021 }
2022
2023 bool AArch64FastISel::selectStore(const Instruction *I) {
2024   MVT VT;
2025   const Value *Op0 = I->getOperand(0);
2026   // Verify we have a legal type before going any further.  Currently, we handle
2027   // simple types that will directly fit in a register (i32/f32/i64/f64) or
2028   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2029   if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2030       cast<StoreInst>(I)->isAtomic())
2031     return false;
2032
2033   // Get the value to be stored into a register. Use the zero register directly
2034   // when possible to avoid an unnecessary copy and a wasted register.
2035   unsigned SrcReg = 0;
2036   if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2037     if (CI->isZero())
2038       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2039   } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2040     if (CF->isZero() && !CF->isNegative()) {
2041       VT = MVT::getIntegerVT(VT.getSizeInBits());
2042       SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2043     }
2044   }
2045
2046   if (!SrcReg)
2047     SrcReg = getRegForValue(Op0);
2048
2049   if (!SrcReg)
2050     return false;
2051
2052   // See if we can handle this address.
2053   Address Addr;
2054   if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2055     return false;
2056
2057   if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2058     return false;
2059   return true;
2060 }
2061
2062 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2063   switch (Pred) {
2064   case CmpInst::FCMP_ONE:
2065   case CmpInst::FCMP_UEQ:
2066   default:
2067     // AL is our "false" for now. The other two need more compares.
2068     return AArch64CC::AL;
2069   case CmpInst::ICMP_EQ:
2070   case CmpInst::FCMP_OEQ:
2071     return AArch64CC::EQ;
2072   case CmpInst::ICMP_SGT:
2073   case CmpInst::FCMP_OGT:
2074     return AArch64CC::GT;
2075   case CmpInst::ICMP_SGE:
2076   case CmpInst::FCMP_OGE:
2077     return AArch64CC::GE;
2078   case CmpInst::ICMP_UGT:
2079   case CmpInst::FCMP_UGT:
2080     return AArch64CC::HI;
2081   case CmpInst::FCMP_OLT:
2082     return AArch64CC::MI;
2083   case CmpInst::ICMP_ULE:
2084   case CmpInst::FCMP_OLE:
2085     return AArch64CC::LS;
2086   case CmpInst::FCMP_ORD:
2087     return AArch64CC::VC;
2088   case CmpInst::FCMP_UNO:
2089     return AArch64CC::VS;
2090   case CmpInst::FCMP_UGE:
2091     return AArch64CC::PL;
2092   case CmpInst::ICMP_SLT:
2093   case CmpInst::FCMP_ULT:
2094     return AArch64CC::LT;
2095   case CmpInst::ICMP_SLE:
2096   case CmpInst::FCMP_ULE:
2097     return AArch64CC::LE;
2098   case CmpInst::FCMP_UNE:
2099   case CmpInst::ICMP_NE:
2100     return AArch64CC::NE;
2101   case CmpInst::ICMP_UGE:
2102     return AArch64CC::HS;
2103   case CmpInst::ICMP_ULT:
2104     return AArch64CC::LO;
2105   }
2106 }
2107
2108 /// \brief Try to emit a combined compare-and-branch instruction.
2109 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2110   assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2111   const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2112   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2113
2114   const Value *LHS = CI->getOperand(0);
2115   const Value *RHS = CI->getOperand(1);
2116
2117   MVT VT;
2118   if (!isTypeSupported(LHS->getType(), VT))
2119     return false;
2120
2121   unsigned BW = VT.getSizeInBits();
2122   if (BW > 64)
2123     return false;
2124
2125   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2126   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2127
2128   // Try to take advantage of fallthrough opportunities.
2129   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2130     std::swap(TBB, FBB);
2131     Predicate = CmpInst::getInversePredicate(Predicate);
2132   }
2133
2134   int TestBit = -1;
2135   bool IsCmpNE;
2136   switch (Predicate) {
2137   default:
2138     return false;
2139   case CmpInst::ICMP_EQ:
2140   case CmpInst::ICMP_NE:
2141     if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2142       std::swap(LHS, RHS);
2143
2144     if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2145       return false;
2146
2147     if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2148       if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2149         const Value *AndLHS = AI->getOperand(0);
2150         const Value *AndRHS = AI->getOperand(1);
2151
2152         if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2153           if (C->getValue().isPowerOf2())
2154             std::swap(AndLHS, AndRHS);
2155
2156         if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2157           if (C->getValue().isPowerOf2()) {
2158             TestBit = C->getValue().logBase2();
2159             LHS = AndLHS;
2160           }
2161       }
2162
2163     if (VT == MVT::i1)
2164       TestBit = 0;
2165
2166     IsCmpNE = Predicate == CmpInst::ICMP_NE;
2167     break;
2168   case CmpInst::ICMP_SLT:
2169   case CmpInst::ICMP_SGE:
2170     if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2171       return false;
2172
2173     TestBit = BW - 1;
2174     IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2175     break;
2176   case CmpInst::ICMP_SGT:
2177   case CmpInst::ICMP_SLE:
2178     if (!isa<ConstantInt>(RHS))
2179       return false;
2180
2181     if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2182       return false;
2183
2184     TestBit = BW - 1;
2185     IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2186     break;
2187   } // end switch
2188
2189   static const unsigned OpcTable[2][2][2] = {
2190     { {AArch64::CBZW,  AArch64::CBZX },
2191       {AArch64::CBNZW, AArch64::CBNZX} },
2192     { {AArch64::TBZW,  AArch64::TBZX },
2193       {AArch64::TBNZW, AArch64::TBNZX} }
2194   };
2195
2196   bool IsBitTest = TestBit != -1;
2197   bool Is64Bit = BW == 64;
2198   if (TestBit < 32 && TestBit >= 0)
2199     Is64Bit = false;
2200
2201   unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2202   const MCInstrDesc &II = TII.get(Opc);
2203
2204   unsigned SrcReg = getRegForValue(LHS);
2205   if (!SrcReg)
2206     return false;
2207   bool SrcIsKill = hasTrivialKill(LHS);
2208
2209   if (BW == 64 && !Is64Bit)
2210     SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2211                                         AArch64::sub_32);
2212
2213   if ((BW < 32) && !IsBitTest)
2214     SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2215
2216   // Emit the combined compare and branch instruction.
2217   SrcReg = constrainOperandRegClass(II, SrcReg,  II.getNumDefs());
2218   MachineInstrBuilder MIB =
2219       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2220           .addReg(SrcReg, getKillRegState(SrcIsKill));
2221   if (IsBitTest)
2222     MIB.addImm(TestBit);
2223   MIB.addMBB(TBB);
2224
2225   // Obtain the branch weight and add the TrueBB to the successor list.
2226   uint32_t BranchWeight = 0;
2227   if (FuncInfo.BPI)
2228     BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2229                                                TBB->getBasicBlock());
2230   FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2231   fastEmitBranch(FBB, DbgLoc);
2232
2233   return true;
2234 }
2235
2236 bool AArch64FastISel::selectBranch(const Instruction *I) {
2237   const BranchInst *BI = cast<BranchInst>(I);
2238   if (BI->isUnconditional()) {
2239     MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2240     fastEmitBranch(MSucc, BI->getDebugLoc());
2241     return true;
2242   }
2243
2244   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2245   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2246
2247   AArch64CC::CondCode CC = AArch64CC::NE;
2248   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2249     if (CI->hasOneUse() && isValueAvailable(CI)) {
2250       // Try to optimize or fold the cmp.
2251       CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2252       switch (Predicate) {
2253       default:
2254         break;
2255       case CmpInst::FCMP_FALSE:
2256         fastEmitBranch(FBB, DbgLoc);
2257         return true;
2258       case CmpInst::FCMP_TRUE:
2259         fastEmitBranch(TBB, DbgLoc);
2260         return true;
2261       }
2262
2263       // Try to emit a combined compare-and-branch first.
2264       if (emitCompareAndBranch(BI))
2265         return true;
2266
2267       // Try to take advantage of fallthrough opportunities.
2268       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2269         std::swap(TBB, FBB);
2270         Predicate = CmpInst::getInversePredicate(Predicate);
2271       }
2272
2273       // Emit the cmp.
2274       if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2275         return false;
2276
2277       // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2278       // instruction.
2279       CC = getCompareCC(Predicate);
2280       AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2281       switch (Predicate) {
2282       default:
2283         break;
2284       case CmpInst::FCMP_UEQ:
2285         ExtraCC = AArch64CC::EQ;
2286         CC = AArch64CC::VS;
2287         break;
2288       case CmpInst::FCMP_ONE:
2289         ExtraCC = AArch64CC::MI;
2290         CC = AArch64CC::GT;
2291         break;
2292       }
2293       assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2294
2295       // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2296       if (ExtraCC != AArch64CC::AL) {
2297         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2298             .addImm(ExtraCC)
2299             .addMBB(TBB);
2300       }
2301
2302       // Emit the branch.
2303       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2304           .addImm(CC)
2305           .addMBB(TBB);
2306
2307       // Obtain the branch weight and add the TrueBB to the successor list.
2308       uint32_t BranchWeight = 0;
2309       if (FuncInfo.BPI)
2310         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2311                                                   TBB->getBasicBlock());
2312       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2313
2314       fastEmitBranch(FBB, DbgLoc);
2315       return true;
2316     }
2317   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2318     MVT SrcVT;
2319     if (TI->hasOneUse() && isValueAvailable(TI) &&
2320         isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2321       unsigned CondReg = getRegForValue(TI->getOperand(0));
2322       if (!CondReg)
2323         return false;
2324       bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2325
2326       // Issue an extract_subreg to get the lower 32-bits.
2327       if (SrcVT == MVT::i64) {
2328         CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2329                                              AArch64::sub_32);
2330         CondIsKill = true;
2331       }
2332
2333       unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2334       assert(ANDReg && "Unexpected AND instruction emission failure.");
2335       emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2336
2337       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2338         std::swap(TBB, FBB);
2339         CC = AArch64CC::EQ;
2340       }
2341       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2342           .addImm(CC)
2343           .addMBB(TBB);
2344
2345       // Obtain the branch weight and add the TrueBB to the successor list.
2346       uint32_t BranchWeight = 0;
2347       if (FuncInfo.BPI)
2348         BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2349                                                   TBB->getBasicBlock());
2350       FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2351
2352       fastEmitBranch(FBB, DbgLoc);
2353       return true;
2354     }
2355   } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2356     uint64_t Imm = CI->getZExtValue();
2357     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2358     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2359         .addMBB(Target);
2360
2361     // Obtain the branch weight and add the target to the successor list.
2362     uint32_t BranchWeight = 0;
2363     if (FuncInfo.BPI)
2364       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2365                                                  Target->getBasicBlock());
2366     FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2367     return true;
2368   } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2369     // Fake request the condition, otherwise the intrinsic might be completely
2370     // optimized away.
2371     unsigned CondReg = getRegForValue(BI->getCondition());
2372     if (!CondReg)
2373       return false;
2374
2375     // Emit the branch.
2376     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2377       .addImm(CC)
2378       .addMBB(TBB);
2379
2380     // Obtain the branch weight and add the TrueBB to the successor list.
2381     uint32_t BranchWeight = 0;
2382     if (FuncInfo.BPI)
2383       BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2384                                                  TBB->getBasicBlock());
2385     FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2386
2387     fastEmitBranch(FBB, DbgLoc);
2388     return true;
2389   }
2390
2391   unsigned CondReg = getRegForValue(BI->getCondition());
2392   if (CondReg == 0)
2393     return false;
2394   bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2395
2396   // We've been divorced from our compare!  Our block was split, and
2397   // now our compare lives in a predecessor block.  We musn't
2398   // re-compare here, as the children of the compare aren't guaranteed
2399   // live across the block boundary (we *could* check for this).
2400   // Regardless, the compare has been done in the predecessor block,
2401   // and it left a value for us in a virtual register.  Ergo, we test
2402   // the one-bit value left in the virtual register.
2403   emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2404
2405   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2406     std::swap(TBB, FBB);
2407     CC = AArch64CC::EQ;
2408   }
2409
2410   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2411       .addImm(CC)
2412       .addMBB(TBB);
2413
2414   // Obtain the branch weight and add the TrueBB to the successor list.
2415   uint32_t BranchWeight = 0;
2416   if (FuncInfo.BPI)
2417     BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2418                                                TBB->getBasicBlock());
2419   FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2420
2421   fastEmitBranch(FBB, DbgLoc);
2422   return true;
2423 }
2424
2425 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2426   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2427   unsigned AddrReg = getRegForValue(BI->getOperand(0));
2428   if (AddrReg == 0)
2429     return false;
2430
2431   // Emit the indirect branch.
2432   const MCInstrDesc &II = TII.get(AArch64::BR);
2433   AddrReg = constrainOperandRegClass(II, AddrReg,  II.getNumDefs());
2434   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2435
2436   // Make sure the CFG is up-to-date.
2437   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2438     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2439
2440   return true;
2441 }
2442
2443 bool AArch64FastISel::selectCmp(const Instruction *I) {
2444   const CmpInst *CI = cast<CmpInst>(I);
2445
2446   // Try to optimize or fold the cmp.
2447   CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2448   unsigned ResultReg = 0;
2449   switch (Predicate) {
2450   default:
2451     break;
2452   case CmpInst::FCMP_FALSE:
2453     ResultReg = createResultReg(&AArch64::GPR32RegClass);
2454     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2455             TII.get(TargetOpcode::COPY), ResultReg)
2456         .addReg(AArch64::WZR, getKillRegState(true));
2457     break;
2458   case CmpInst::FCMP_TRUE:
2459     ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2460     break;
2461   }
2462
2463   if (ResultReg) {
2464     updateValueMap(I, ResultReg);
2465     return true;
2466   }
2467
2468   // Emit the cmp.
2469   if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2470     return false;
2471
2472   ResultReg = createResultReg(&AArch64::GPR32RegClass);
2473
2474   // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2475   // condition codes are inverted, because they are used by CSINC.
2476   static unsigned CondCodeTable[2][2] = {
2477     { AArch64CC::NE, AArch64CC::VC },
2478     { AArch64CC::PL, AArch64CC::LE }
2479   };
2480   unsigned *CondCodes = nullptr;
2481   switch (Predicate) {
2482   default:
2483     break;
2484   case CmpInst::FCMP_UEQ:
2485     CondCodes = &CondCodeTable[0][0];
2486     break;
2487   case CmpInst::FCMP_ONE:
2488     CondCodes = &CondCodeTable[1][0];
2489     break;
2490   }
2491
2492   if (CondCodes) {
2493     unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2494     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2495             TmpReg1)
2496         .addReg(AArch64::WZR, getKillRegState(true))
2497         .addReg(AArch64::WZR, getKillRegState(true))
2498         .addImm(CondCodes[0]);
2499     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2500             ResultReg)
2501         .addReg(TmpReg1, getKillRegState(true))
2502         .addReg(AArch64::WZR, getKillRegState(true))
2503         .addImm(CondCodes[1]);
2504
2505     updateValueMap(I, ResultReg);
2506     return true;
2507   }
2508
2509   // Now set a register based on the comparison.
2510   AArch64CC::CondCode CC = getCompareCC(Predicate);
2511   assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2512   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2513   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2514           ResultReg)
2515       .addReg(AArch64::WZR, getKillRegState(true))
2516       .addReg(AArch64::WZR, getKillRegState(true))
2517       .addImm(invertedCC);
2518
2519   updateValueMap(I, ResultReg);
2520   return true;
2521 }
2522
2523 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2524 /// value.
2525 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2526   if (!SI->getType()->isIntegerTy(1))
2527     return false;
2528
2529   const Value *Src1Val, *Src2Val;
2530   unsigned Opc = 0;
2531   bool NeedExtraOp = false;
2532   if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2533     if (CI->isOne()) {
2534       Src1Val = SI->getCondition();
2535       Src2Val = SI->getFalseValue();
2536       Opc = AArch64::ORRWrr;
2537     } else {
2538       assert(CI->isZero());
2539       Src1Val = SI->getFalseValue();
2540       Src2Val = SI->getCondition();
2541       Opc = AArch64::BICWrr;
2542     }
2543   } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2544     if (CI->isOne()) {
2545       Src1Val = SI->getCondition();
2546       Src2Val = SI->getTrueValue();
2547       Opc = AArch64::ORRWrr;
2548       NeedExtraOp = true;
2549     } else {
2550       assert(CI->isZero());
2551       Src1Val = SI->getCondition();
2552       Src2Val = SI->getTrueValue();
2553       Opc = AArch64::ANDWrr;
2554     }
2555   }
2556
2557   if (!Opc)
2558     return false;
2559
2560   unsigned Src1Reg = getRegForValue(Src1Val);
2561   if (!Src1Reg)
2562     return false;
2563   bool Src1IsKill = hasTrivialKill(Src1Val);
2564
2565   unsigned Src2Reg = getRegForValue(Src2Val);
2566   if (!Src2Reg)
2567     return false;
2568   bool Src2IsKill = hasTrivialKill(Src2Val);
2569
2570   if (NeedExtraOp) {
2571     Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2572     Src1IsKill = true;
2573   }
2574   unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32spRegClass, Src1Reg,
2575                                        Src1IsKill, Src2Reg, Src2IsKill);
2576   updateValueMap(SI, ResultReg);
2577   return true;
2578 }
2579
2580 bool AArch64FastISel::selectSelect(const Instruction *I) {
2581   assert(isa<SelectInst>(I) && "Expected a select instruction.");
2582   MVT VT;
2583   if (!isTypeSupported(I->getType(), VT))
2584     return false;
2585
2586   unsigned Opc;
2587   const TargetRegisterClass *RC;
2588   switch (VT.SimpleTy) {
2589   default:
2590     return false;
2591   case MVT::i1:
2592   case MVT::i8:
2593   case MVT::i16:
2594   case MVT::i32:
2595     Opc = AArch64::CSELWr;
2596     RC = &AArch64::GPR32RegClass;
2597     break;
2598   case MVT::i64:
2599     Opc = AArch64::CSELXr;
2600     RC = &AArch64::GPR64RegClass;
2601     break;
2602   case MVT::f32:
2603     Opc = AArch64::FCSELSrrr;
2604     RC = &AArch64::FPR32RegClass;
2605     break;
2606   case MVT::f64:
2607     Opc = AArch64::FCSELDrrr;
2608     RC = &AArch64::FPR64RegClass;
2609     break;
2610   }
2611
2612   const SelectInst *SI = cast<SelectInst>(I);
2613   const Value *Cond = SI->getCondition();
2614   AArch64CC::CondCode CC = AArch64CC::NE;
2615   AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2616
2617   if (optimizeSelect(SI))
2618     return true;
2619
2620   // Try to pickup the flags, so we don't have to emit another compare.
2621   if (foldXALUIntrinsic(CC, I, Cond)) {
2622     // Fake request the condition to force emission of the XALU intrinsic.
2623     unsigned CondReg = getRegForValue(Cond);
2624     if (!CondReg)
2625       return false;
2626   } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2627              isValueAvailable(Cond)) {
2628     const auto *Cmp = cast<CmpInst>(Cond);
2629     // Try to optimize or fold the cmp.
2630     CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2631     const Value *FoldSelect = nullptr;
2632     switch (Predicate) {
2633     default:
2634       break;
2635     case CmpInst::FCMP_FALSE:
2636       FoldSelect = SI->getFalseValue();
2637       break;
2638     case CmpInst::FCMP_TRUE:
2639       FoldSelect = SI->getTrueValue();
2640       break;
2641     }
2642
2643     if (FoldSelect) {
2644       unsigned SrcReg = getRegForValue(FoldSelect);
2645       if (!SrcReg)
2646         return false;
2647       unsigned UseReg = lookUpRegForValue(SI);
2648       if (UseReg)
2649         MRI.clearKillFlags(UseReg);
2650
2651       updateValueMap(I, SrcReg);
2652       return true;
2653     }
2654
2655     // Emit the cmp.
2656     if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2657       return false;
2658
2659     // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2660     CC = getCompareCC(Predicate);
2661     switch (Predicate) {
2662     default:
2663       break;
2664     case CmpInst::FCMP_UEQ:
2665       ExtraCC = AArch64CC::EQ;
2666       CC = AArch64CC::VS;
2667       break;
2668     case CmpInst::FCMP_ONE:
2669       ExtraCC = AArch64CC::MI;
2670       CC = AArch64CC::GT;
2671       break;
2672     }
2673     assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2674   } else {
2675     unsigned CondReg = getRegForValue(Cond);
2676     if (!CondReg)
2677       return false;
2678     bool CondIsKill = hasTrivialKill(Cond);
2679
2680     // Emit a TST instruction (ANDS wzr, reg, #imm).
2681     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2682             AArch64::WZR)
2683         .addReg(CondReg, getKillRegState(CondIsKill))
2684         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2685   }
2686
2687   unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2688   bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2689
2690   unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2691   bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2692
2693   if (!Src1Reg || !Src2Reg)
2694     return false;
2695
2696   if (ExtraCC != AArch64CC::AL) {
2697     Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2698                                Src2IsKill, ExtraCC);
2699     Src2IsKill = true;
2700   }
2701   unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2702                                         Src2IsKill, CC);
2703   updateValueMap(I, ResultReg);
2704   return true;
2705 }
2706
2707 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2708   Value *V = I->getOperand(0);
2709   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2710     return false;
2711
2712   unsigned Op = getRegForValue(V);
2713   if (Op == 0)
2714     return false;
2715
2716   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2717   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2718           ResultReg).addReg(Op);
2719   updateValueMap(I, ResultReg);
2720   return true;
2721 }
2722
2723 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2724   Value *V = I->getOperand(0);
2725   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2726     return false;
2727
2728   unsigned Op = getRegForValue(V);
2729   if (Op == 0)
2730     return false;
2731
2732   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2733   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2734           ResultReg).addReg(Op);
2735   updateValueMap(I, ResultReg);
2736   return true;
2737 }
2738
2739 // FPToUI and FPToSI
2740 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2741   MVT DestVT;
2742   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2743     return false;
2744
2745   unsigned SrcReg = getRegForValue(I->getOperand(0));
2746   if (SrcReg == 0)
2747     return false;
2748
2749   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2750   if (SrcVT == MVT::f128)
2751     return false;
2752
2753   unsigned Opc;
2754   if (SrcVT == MVT::f64) {
2755     if (Signed)
2756       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2757     else
2758       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2759   } else {
2760     if (Signed)
2761       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2762     else
2763       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2764   }
2765   unsigned ResultReg = createResultReg(
2766       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2767   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2768       .addReg(SrcReg);
2769   updateValueMap(I, ResultReg);
2770   return true;
2771 }
2772
2773 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2774   MVT DestVT;
2775   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2776     return false;
2777   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2778           "Unexpected value type.");
2779
2780   unsigned SrcReg = getRegForValue(I->getOperand(0));
2781   if (!SrcReg)
2782     return false;
2783   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2784
2785   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2786
2787   // Handle sign-extension.
2788   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2789     SrcReg =
2790         emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2791     if (!SrcReg)
2792       return false;
2793     SrcIsKill = true;
2794   }
2795
2796   unsigned Opc;
2797   if (SrcVT == MVT::i64) {
2798     if (Signed)
2799       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2800     else
2801       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2802   } else {
2803     if (Signed)
2804       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2805     else
2806       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2807   }
2808
2809   unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2810                                       SrcIsKill);
2811   updateValueMap(I, ResultReg);
2812   return true;
2813 }
2814
2815 bool AArch64FastISel::fastLowerArguments() {
2816   if (!FuncInfo.CanLowerReturn)
2817     return false;
2818
2819   const Function *F = FuncInfo.Fn;
2820   if (F->isVarArg())
2821     return false;
2822
2823   CallingConv::ID CC = F->getCallingConv();
2824   if (CC != CallingConv::C)
2825     return false;
2826
2827   // Only handle simple cases of up to 8 GPR and FPR each.
2828   unsigned GPRCnt = 0;
2829   unsigned FPRCnt = 0;
2830   unsigned Idx = 0;
2831   for (auto const &Arg : F->args()) {
2832     // The first argument is at index 1.
2833     ++Idx;
2834     if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2835         F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2836         F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2837         F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2838       return false;
2839
2840     Type *ArgTy = Arg.getType();
2841     if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2842       return false;
2843
2844     EVT ArgVT = TLI.getValueType(ArgTy);
2845     if (!ArgVT.isSimple())
2846       return false;
2847
2848     MVT VT = ArgVT.getSimpleVT().SimpleTy;
2849     if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2850       return false;
2851
2852     if (VT.isVector() &&
2853         (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2854       return false;
2855
2856     if (VT >= MVT::i1 && VT <= MVT::i64)
2857       ++GPRCnt;
2858     else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2859              VT.is128BitVector())
2860       ++FPRCnt;
2861     else
2862       return false;
2863
2864     if (GPRCnt > 8 || FPRCnt > 8)
2865       return false;
2866   }
2867
2868   static const MCPhysReg Registers[6][8] = {
2869     { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2870       AArch64::W5, AArch64::W6, AArch64::W7 },
2871     { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2872       AArch64::X5, AArch64::X6, AArch64::X7 },
2873     { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2874       AArch64::H5, AArch64::H6, AArch64::H7 },
2875     { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2876       AArch64::S5, AArch64::S6, AArch64::S7 },
2877     { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2878       AArch64::D5, AArch64::D6, AArch64::D7 },
2879     { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2880       AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2881   };
2882
2883   unsigned GPRIdx = 0;
2884   unsigned FPRIdx = 0;
2885   for (auto const &Arg : F->args()) {
2886     MVT VT = TLI.getSimpleValueType(Arg.getType());
2887     unsigned SrcReg;
2888     const TargetRegisterClass *RC;
2889     if (VT >= MVT::i1 && VT <= MVT::i32) {
2890       SrcReg = Registers[0][GPRIdx++];
2891       RC = &AArch64::GPR32RegClass;
2892       VT = MVT::i32;
2893     } else if (VT == MVT::i64) {
2894       SrcReg = Registers[1][GPRIdx++];
2895       RC = &AArch64::GPR64RegClass;
2896     } else if (VT == MVT::f16) {
2897       SrcReg = Registers[2][FPRIdx++];
2898       RC = &AArch64::FPR16RegClass;
2899     } else if (VT ==  MVT::f32) {
2900       SrcReg = Registers[3][FPRIdx++];
2901       RC = &AArch64::FPR32RegClass;
2902     } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2903       SrcReg = Registers[4][FPRIdx++];
2904       RC = &AArch64::FPR64RegClass;
2905     } else if (VT.is128BitVector()) {
2906       SrcReg = Registers[5][FPRIdx++];
2907       RC = &AArch64::FPR128RegClass;
2908     } else
2909       llvm_unreachable("Unexpected value type.");
2910
2911     unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2912     // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2913     // Without this, EmitLiveInCopies may eliminate the livein if its only
2914     // use is a bitcast (which isn't turned into an instruction).
2915     unsigned ResultReg = createResultReg(RC);
2916     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2917             TII.get(TargetOpcode::COPY), ResultReg)
2918         .addReg(DstReg, getKillRegState(true));
2919     updateValueMap(&Arg, ResultReg);
2920   }
2921   return true;
2922 }
2923
2924 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2925                                       SmallVectorImpl<MVT> &OutVTs,
2926                                       unsigned &NumBytes) {
2927   CallingConv::ID CC = CLI.CallConv;
2928   SmallVector<CCValAssign, 16> ArgLocs;
2929   CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2930   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2931
2932   // Get a count of how many bytes are to be pushed on the stack.
2933   NumBytes = CCInfo.getNextStackOffset();
2934
2935   // Issue CALLSEQ_START
2936   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2937   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2938     .addImm(NumBytes);
2939
2940   // Process the args.
2941   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2942     CCValAssign &VA = ArgLocs[i];
2943     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2944     MVT ArgVT = OutVTs[VA.getValNo()];
2945
2946     unsigned ArgReg = getRegForValue(ArgVal);
2947     if (!ArgReg)
2948       return false;
2949
2950     // Handle arg promotion: SExt, ZExt, AExt.
2951     switch (VA.getLocInfo()) {
2952     case CCValAssign::Full:
2953       break;
2954     case CCValAssign::SExt: {
2955       MVT DestVT = VA.getLocVT();
2956       MVT SrcVT = ArgVT;
2957       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2958       if (!ArgReg)
2959         return false;
2960       break;
2961     }
2962     case CCValAssign::AExt:
2963     // Intentional fall-through.
2964     case CCValAssign::ZExt: {
2965       MVT DestVT = VA.getLocVT();
2966       MVT SrcVT = ArgVT;
2967       ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2968       if (!ArgReg)
2969         return false;
2970       break;
2971     }
2972     default:
2973       llvm_unreachable("Unknown arg promotion!");
2974     }
2975
2976     // Now copy/store arg to correct locations.
2977     if (VA.isRegLoc() && !VA.needsCustom()) {
2978       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2979               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2980       CLI.OutRegs.push_back(VA.getLocReg());
2981     } else if (VA.needsCustom()) {
2982       // FIXME: Handle custom args.
2983       return false;
2984     } else {
2985       assert(VA.isMemLoc() && "Assuming store on stack.");
2986
2987       // Don't emit stores for undef values.
2988       if (isa<UndefValue>(ArgVal))
2989         continue;
2990
2991       // Need to store on the stack.
2992       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2993
2994       unsigned BEAlign = 0;
2995       if (ArgSize < 8 && !Subtarget->isLittleEndian())
2996         BEAlign = 8 - ArgSize;
2997
2998       Address Addr;
2999       Addr.setKind(Address::RegBase);
3000       Addr.setReg(AArch64::SP);
3001       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3002
3003       unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3004       MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3005         MachinePointerInfo::getStack(Addr.getOffset()),
3006         MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3007
3008       if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3009         return false;
3010     }
3011   }
3012   return true;
3013 }
3014
3015 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3016                                  unsigned NumBytes) {
3017   CallingConv::ID CC = CLI.CallConv;
3018
3019   // Issue CALLSEQ_END
3020   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3021   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3022     .addImm(NumBytes).addImm(0);
3023
3024   // Now the return value.
3025   if (RetVT != MVT::isVoid) {
3026     SmallVector<CCValAssign, 16> RVLocs;
3027     CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3028     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3029
3030     // Only handle a single return value.
3031     if (RVLocs.size() != 1)
3032       return false;
3033
3034     // Copy all of the result registers out of their specified physreg.
3035     MVT CopyVT = RVLocs[0].getValVT();
3036     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3037     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3038             TII.get(TargetOpcode::COPY), ResultReg)
3039         .addReg(RVLocs[0].getLocReg());
3040     CLI.InRegs.push_back(RVLocs[0].getLocReg());
3041
3042     CLI.ResultReg = ResultReg;
3043     CLI.NumResultRegs = 1;
3044   }
3045
3046   return true;
3047 }
3048
3049 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3050   CallingConv::ID CC  = CLI.CallConv;
3051   bool IsTailCall     = CLI.IsTailCall;
3052   bool IsVarArg       = CLI.IsVarArg;
3053   const Value *Callee = CLI.Callee;
3054   const char *SymName = CLI.SymName;
3055
3056   if (!Callee && !SymName)
3057     return false;
3058
3059   // Allow SelectionDAG isel to handle tail calls.
3060   if (IsTailCall)
3061     return false;
3062
3063   CodeModel::Model CM = TM.getCodeModel();
3064   // Only support the small and large code model.
3065   if (CM != CodeModel::Small && CM != CodeModel::Large)
3066     return false;
3067
3068   // FIXME: Add large code model support for ELF.
3069   if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3070     return false;
3071
3072   // Let SDISel handle vararg functions.
3073   if (IsVarArg)
3074     return false;
3075
3076   // FIXME: Only handle *simple* calls for now.
3077   MVT RetVT;
3078   if (CLI.RetTy->isVoidTy())
3079     RetVT = MVT::isVoid;
3080   else if (!isTypeLegal(CLI.RetTy, RetVT))
3081     return false;
3082
3083   for (auto Flag : CLI.OutFlags)
3084     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3085       return false;
3086
3087   // Set up the argument vectors.
3088   SmallVector<MVT, 16> OutVTs;
3089   OutVTs.reserve(CLI.OutVals.size());
3090
3091   for (auto *Val : CLI.OutVals) {
3092     MVT VT;
3093     if (!isTypeLegal(Val->getType(), VT) &&
3094         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3095       return false;
3096
3097     // We don't handle vector parameters yet.
3098     if (VT.isVector() || VT.getSizeInBits() > 64)
3099       return false;
3100
3101     OutVTs.push_back(VT);
3102   }
3103
3104   Address Addr;
3105   if (Callee && !computeCallAddress(Callee, Addr))
3106     return false;
3107
3108   // Handle the arguments now that we've gotten them.
3109   unsigned NumBytes;
3110   if (!processCallArgs(CLI, OutVTs, NumBytes))
3111     return false;
3112
3113   // Issue the call.
3114   MachineInstrBuilder MIB;
3115   if (CM == CodeModel::Small) {
3116     const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3117     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3118     if (SymName)
3119       MIB.addExternalSymbol(SymName, 0);
3120     else if (Addr.getGlobalValue())
3121       MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3122     else if (Addr.getReg()) {
3123       unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3124       MIB.addReg(Reg);
3125     } else
3126       return false;
3127   } else {
3128     unsigned CallReg = 0;
3129     if (SymName) {
3130       unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3131       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3132               ADRPReg)
3133         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3134
3135       CallReg = createResultReg(&AArch64::GPR64RegClass);
3136       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3137               CallReg)
3138         .addReg(ADRPReg)
3139         .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3140                            AArch64II::MO_NC);
3141     } else if (Addr.getGlobalValue())
3142       CallReg = materializeGV(Addr.getGlobalValue());
3143     else if (Addr.getReg())
3144       CallReg = Addr.getReg();
3145
3146     if (!CallReg)
3147       return false;
3148
3149     const MCInstrDesc &II = TII.get(AArch64::BLR);
3150     CallReg = constrainOperandRegClass(II, CallReg, 0);
3151     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3152   }
3153
3154   // Add implicit physical register uses to the call.
3155   for (auto Reg : CLI.OutRegs)
3156     MIB.addReg(Reg, RegState::Implicit);
3157
3158   // Add a register mask with the call-preserved registers.
3159   // Proper defs for return values will be added by setPhysRegsDeadExcept().
3160   MIB.addRegMask(TRI.getCallPreservedMask(CC));
3161
3162   CLI.Call = MIB;
3163
3164   // Finish off the call including any return values.
3165   return finishCall(CLI, RetVT, NumBytes);
3166 }
3167
3168 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3169   if (Alignment)
3170     return Len / Alignment <= 4;
3171   else
3172     return Len < 32;
3173 }
3174
3175 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3176                                          uint64_t Len, unsigned Alignment) {
3177   // Make sure we don't bloat code by inlining very large memcpy's.
3178   if (!isMemCpySmall(Len, Alignment))
3179     return false;
3180
3181   int64_t UnscaledOffset = 0;
3182   Address OrigDest = Dest;
3183   Address OrigSrc = Src;
3184
3185   while (Len) {
3186     MVT VT;
3187     if (!Alignment || Alignment >= 8) {
3188       if (Len >= 8)
3189         VT = MVT::i64;
3190       else if (Len >= 4)
3191         VT = MVT::i32;
3192       else if (Len >= 2)
3193         VT = MVT::i16;
3194       else {
3195         VT = MVT::i8;
3196       }
3197     } else {
3198       // Bound based on alignment.
3199       if (Len >= 4 && Alignment == 4)
3200         VT = MVT::i32;
3201       else if (Len >= 2 && Alignment == 2)
3202         VT = MVT::i16;
3203       else {
3204         VT = MVT::i8;
3205       }
3206     }
3207
3208     unsigned ResultReg = emitLoad(VT, VT, Src);
3209     if (!ResultReg)
3210       return false;
3211
3212     if (!emitStore(VT, ResultReg, Dest))
3213       return false;
3214
3215     int64_t Size = VT.getSizeInBits() / 8;
3216     Len -= Size;
3217     UnscaledOffset += Size;
3218
3219     // We need to recompute the unscaled offset for each iteration.
3220     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3221     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3222   }
3223
3224   return true;
3225 }
3226
3227 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3228 /// into the user. The condition code will only be updated on success.
3229 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3230                                         const Instruction *I,
3231                                         const Value *Cond) {
3232   if (!isa<ExtractValueInst>(Cond))
3233     return false;
3234
3235   const auto *EV = cast<ExtractValueInst>(Cond);
3236   if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3237     return false;
3238
3239   const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3240   MVT RetVT;
3241   const Function *Callee = II->getCalledFunction();
3242   Type *RetTy =
3243   cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3244   if (!isTypeLegal(RetTy, RetVT))
3245     return false;
3246
3247   if (RetVT != MVT::i32 && RetVT != MVT::i64)
3248     return false;
3249
3250   const Value *LHS = II->getArgOperand(0);
3251   const Value *RHS = II->getArgOperand(1);
3252
3253   // Canonicalize immediate to the RHS.
3254   if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3255       isCommutativeIntrinsic(II))
3256     std::swap(LHS, RHS);
3257
3258   // Simplify multiplies.
3259   unsigned IID = II->getIntrinsicID();
3260   switch (IID) {
3261   default:
3262     break;
3263   case Intrinsic::smul_with_overflow:
3264     if (const auto *C = dyn_cast<ConstantInt>(RHS))
3265       if (C->getValue() == 2)
3266         IID = Intrinsic::sadd_with_overflow;
3267     break;
3268   case Intrinsic::umul_with_overflow:
3269     if (const auto *C = dyn_cast<ConstantInt>(RHS))
3270       if (C->getValue() == 2)
3271         IID = Intrinsic::uadd_with_overflow;
3272     break;
3273   }
3274
3275   AArch64CC::CondCode TmpCC;
3276   switch (IID) {
3277   default:
3278     return false;
3279   case Intrinsic::sadd_with_overflow:
3280   case Intrinsic::ssub_with_overflow:
3281     TmpCC = AArch64CC::VS;
3282     break;
3283   case Intrinsic::uadd_with_overflow:
3284     TmpCC = AArch64CC::HS;
3285     break;
3286   case Intrinsic::usub_with_overflow:
3287     TmpCC = AArch64CC::LO;
3288     break;
3289   case Intrinsic::smul_with_overflow:
3290   case Intrinsic::umul_with_overflow:
3291     TmpCC = AArch64CC::NE;
3292     break;
3293   }
3294
3295   // Check if both instructions are in the same basic block.
3296   if (!isValueAvailable(II))
3297     return false;
3298
3299   // Make sure nothing is in the way
3300   BasicBlock::const_iterator Start = I;
3301   BasicBlock::const_iterator End = II;
3302   for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3303     // We only expect extractvalue instructions between the intrinsic and the
3304     // instruction to be selected.
3305     if (!isa<ExtractValueInst>(Itr))
3306       return false;
3307
3308     // Check that the extractvalue operand comes from the intrinsic.
3309     const auto *EVI = cast<ExtractValueInst>(Itr);
3310     if (EVI->getAggregateOperand() != II)
3311       return false;
3312   }
3313
3314   CC = TmpCC;
3315   return true;
3316 }
3317
3318 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3319   // FIXME: Handle more intrinsics.
3320   switch (II->getIntrinsicID()) {
3321   default: return false;
3322   case Intrinsic::frameaddress: {
3323     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3324     MFI->setFrameAddressIsTaken(true);
3325
3326     const AArch64RegisterInfo *RegInfo =
3327         static_cast<const AArch64RegisterInfo *>(
3328             TM.getSubtargetImpl()->getRegisterInfo());
3329     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3330     unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3331     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3332             TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3333     // Recursively load frame address
3334     // ldr x0, [fp]
3335     // ldr x0, [x0]
3336     // ldr x0, [x0]
3337     // ...
3338     unsigned DestReg;
3339     unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3340     while (Depth--) {
3341       DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3342                                 SrcReg, /*IsKill=*/true, 0);
3343       assert(DestReg && "Unexpected LDR instruction emission failure.");
3344       SrcReg = DestReg;
3345     }
3346
3347     updateValueMap(II, SrcReg);
3348     return true;
3349   }
3350   case Intrinsic::memcpy:
3351   case Intrinsic::memmove: {
3352     const auto *MTI = cast<MemTransferInst>(II);
3353     // Don't handle volatile.
3354     if (MTI->isVolatile())
3355       return false;
3356
3357     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
3358     // we would emit dead code because we don't currently handle memmoves.
3359     bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3360     if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3361       // Small memcpy's are common enough that we want to do them without a call
3362       // if possible.
3363       uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3364       unsigned Alignment = MTI->getAlignment();
3365       if (isMemCpySmall(Len, Alignment)) {
3366         Address Dest, Src;
3367         if (!computeAddress(MTI->getRawDest(), Dest) ||
3368             !computeAddress(MTI->getRawSource(), Src))
3369           return false;
3370         if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3371           return true;
3372       }
3373     }
3374
3375     if (!MTI->getLength()->getType()->isIntegerTy(64))
3376       return false;
3377
3378     if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3379       // Fast instruction selection doesn't support the special
3380       // address spaces.
3381       return false;
3382
3383     const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3384     return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3385   }
3386   case Intrinsic::memset: {
3387     const MemSetInst *MSI = cast<MemSetInst>(II);
3388     // Don't handle volatile.
3389     if (MSI->isVolatile())
3390       return false;
3391
3392     if (!MSI->getLength()->getType()->isIntegerTy(64))
3393       return false;
3394
3395     if (MSI->getDestAddressSpace() > 255)
3396       // Fast instruction selection doesn't support the special
3397       // address spaces.
3398       return false;
3399
3400     return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3401   }
3402   case Intrinsic::sin:
3403   case Intrinsic::cos:
3404   case Intrinsic::pow: {
3405     MVT RetVT;
3406     if (!isTypeLegal(II->getType(), RetVT))
3407       return false;
3408
3409     if (RetVT != MVT::f32 && RetVT != MVT::f64)
3410       return false;
3411
3412     static const RTLIB::Libcall LibCallTable[3][2] = {
3413       { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3414       { RTLIB::COS_F32, RTLIB::COS_F64 },
3415       { RTLIB::POW_F32, RTLIB::POW_F64 }
3416     };
3417     RTLIB::Libcall LC;
3418     bool Is64Bit = RetVT == MVT::f64;
3419     switch (II->getIntrinsicID()) {
3420     default:
3421       llvm_unreachable("Unexpected intrinsic.");
3422     case Intrinsic::sin:
3423       LC = LibCallTable[0][Is64Bit];
3424       break;
3425     case Intrinsic::cos:
3426       LC = LibCallTable[1][Is64Bit];
3427       break;
3428     case Intrinsic::pow:
3429       LC = LibCallTable[2][Is64Bit];
3430       break;
3431     }
3432
3433     ArgListTy Args;
3434     Args.reserve(II->getNumArgOperands());
3435
3436     // Populate the argument list.
3437     for (auto &Arg : II->arg_operands()) {
3438       ArgListEntry Entry;
3439       Entry.Val = Arg;
3440       Entry.Ty = Arg->getType();
3441       Args.push_back(Entry);
3442     }
3443
3444     CallLoweringInfo CLI;
3445     CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3446                   TLI.getLibcallName(LC), std::move(Args));
3447     if (!lowerCallTo(CLI))
3448       return false;
3449     updateValueMap(II, CLI.ResultReg);
3450     return true;
3451   }
3452   case Intrinsic::fabs: {
3453     MVT VT;
3454     if (!isTypeLegal(II->getType(), VT))
3455       return false;
3456
3457     unsigned Opc;
3458     switch (VT.SimpleTy) {
3459     default:
3460       return false;
3461     case MVT::f32:
3462       Opc = AArch64::FABSSr;
3463       break;
3464     case MVT::f64:
3465       Opc = AArch64::FABSDr;
3466       break;
3467     }
3468     unsigned SrcReg = getRegForValue(II->getOperand(0));
3469     if (!SrcReg)
3470       return false;
3471     bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3472     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3473     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3474       .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3475     updateValueMap(II, ResultReg);
3476     return true;
3477   }
3478   case Intrinsic::trap: {
3479     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3480         .addImm(1);
3481     return true;
3482   }
3483   case Intrinsic::sqrt: {
3484     Type *RetTy = II->getCalledFunction()->getReturnType();
3485
3486     MVT VT;
3487     if (!isTypeLegal(RetTy, VT))
3488       return false;
3489
3490     unsigned Op0Reg = getRegForValue(II->getOperand(0));
3491     if (!Op0Reg)
3492       return false;
3493     bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3494
3495     unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3496     if (!ResultReg)
3497       return false;
3498
3499     updateValueMap(II, ResultReg);
3500     return true;
3501   }
3502   case Intrinsic::sadd_with_overflow:
3503   case Intrinsic::uadd_with_overflow:
3504   case Intrinsic::ssub_with_overflow:
3505   case Intrinsic::usub_with_overflow:
3506   case Intrinsic::smul_with_overflow:
3507   case Intrinsic::umul_with_overflow: {
3508     // This implements the basic lowering of the xalu with overflow intrinsics.
3509     const Function *Callee = II->getCalledFunction();
3510     auto *Ty = cast<StructType>(Callee->getReturnType());
3511     Type *RetTy = Ty->getTypeAtIndex(0U);
3512
3513     MVT VT;
3514     if (!isTypeLegal(RetTy, VT))
3515       return false;
3516
3517     if (VT != MVT::i32 && VT != MVT::i64)
3518       return false;
3519
3520     const Value *LHS = II->getArgOperand(0);
3521     const Value *RHS = II->getArgOperand(1);
3522     // Canonicalize immediate to the RHS.
3523     if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3524         isCommutativeIntrinsic(II))
3525       std::swap(LHS, RHS);
3526
3527     // Simplify multiplies.
3528     unsigned IID = II->getIntrinsicID();
3529     switch (IID) {
3530     default:
3531       break;
3532     case Intrinsic::smul_with_overflow:
3533       if (const auto *C = dyn_cast<ConstantInt>(RHS))
3534         if (C->getValue() == 2) {
3535           IID = Intrinsic::sadd_with_overflow;
3536           RHS = LHS;
3537         }
3538       break;
3539     case Intrinsic::umul_with_overflow:
3540       if (const auto *C = dyn_cast<ConstantInt>(RHS))
3541         if (C->getValue() == 2) {
3542           IID = Intrinsic::uadd_with_overflow;
3543           RHS = LHS;
3544         }
3545       break;
3546     }
3547
3548     unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3549     AArch64CC::CondCode CC = AArch64CC::Invalid;
3550     switch (IID) {
3551     default: llvm_unreachable("Unexpected intrinsic!");
3552     case Intrinsic::sadd_with_overflow:
3553       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3554       CC = AArch64CC::VS;
3555       break;
3556     case Intrinsic::uadd_with_overflow:
3557       ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3558       CC = AArch64CC::HS;
3559       break;
3560     case Intrinsic::ssub_with_overflow:
3561       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3562       CC = AArch64CC::VS;
3563       break;
3564     case Intrinsic::usub_with_overflow:
3565       ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3566       CC = AArch64CC::LO;
3567       break;
3568     case Intrinsic::smul_with_overflow: {
3569       CC = AArch64CC::NE;
3570       unsigned LHSReg = getRegForValue(LHS);
3571       if (!LHSReg)
3572         return false;
3573       bool LHSIsKill = hasTrivialKill(LHS);
3574
3575       unsigned RHSReg = getRegForValue(RHS);
3576       if (!RHSReg)
3577         return false;
3578       bool RHSIsKill = hasTrivialKill(RHS);
3579
3580       if (VT == MVT::i32) {
3581         MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3582         unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3583                                        /*IsKill=*/false, 32);
3584         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3585                                             AArch64::sub_32);
3586         ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3587                                               AArch64::sub_32);
3588         emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3589                     AArch64_AM::ASR, 31, /*WantResult=*/false);
3590       } else {
3591         assert(VT == MVT::i64 && "Unexpected value type.");
3592         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3593         unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3594                                         RHSReg, RHSIsKill);
3595         emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3596                     AArch64_AM::ASR, 63, /*WantResult=*/false);
3597       }
3598       break;
3599     }
3600     case Intrinsic::umul_with_overflow: {
3601       CC = AArch64CC::NE;
3602       unsigned LHSReg = getRegForValue(LHS);
3603       if (!LHSReg)
3604         return false;
3605       bool LHSIsKill = hasTrivialKill(LHS);
3606
3607       unsigned RHSReg = getRegForValue(RHS);
3608       if (!RHSReg)
3609         return false;
3610       bool RHSIsKill = hasTrivialKill(RHS);
3611
3612       if (VT == MVT::i32) {
3613         MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3614         emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3615                     /*IsKill=*/false, AArch64_AM::LSR, 32,
3616                     /*WantResult=*/false);
3617         MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3618                                             AArch64::sub_32);
3619       } else {
3620         assert(VT == MVT::i64 && "Unexpected value type.");
3621         MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3622         unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3623                                         RHSReg, RHSIsKill);
3624         emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3625                     /*IsKill=*/false, /*WantResult=*/false);
3626       }
3627       break;
3628     }
3629     }
3630
3631     if (MulReg) {
3632       ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3633       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3634               TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3635     }
3636
3637     ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3638                                   AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3639                                   /*IsKill=*/true, getInvertedCondCode(CC));
3640     (void)ResultReg2;
3641     assert((ResultReg1 + 1) == ResultReg2 &&
3642            "Nonconsecutive result registers.");
3643     updateValueMap(II, ResultReg1, 2);
3644     return true;
3645   }
3646   }
3647   return false;
3648 }
3649
3650 bool AArch64FastISel::selectRet(const Instruction *I) {
3651   const ReturnInst *Ret = cast<ReturnInst>(I);
3652   const Function &F = *I->getParent()->getParent();
3653
3654   if (!FuncInfo.CanLowerReturn)
3655     return false;
3656
3657   if (F.isVarArg())
3658     return false;
3659
3660   // Build a list of return value registers.
3661   SmallVector<unsigned, 4> RetRegs;
3662
3663   if (Ret->getNumOperands() > 0) {
3664     CallingConv::ID CC = F.getCallingConv();
3665     SmallVector<ISD::OutputArg, 4> Outs;
3666     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3667
3668     // Analyze operands of the call, assigning locations to each operand.
3669     SmallVector<CCValAssign, 16> ValLocs;
3670     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3671     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3672                                                      : RetCC_AArch64_AAPCS;
3673     CCInfo.AnalyzeReturn(Outs, RetCC);
3674
3675     // Only handle a single return value for now.
3676     if (ValLocs.size() != 1)
3677       return false;
3678
3679     CCValAssign &VA = ValLocs[0];
3680     const Value *RV = Ret->getOperand(0);
3681
3682     // Don't bother handling odd stuff for now.
3683     if ((VA.getLocInfo() != CCValAssign::Full) &&
3684         (VA.getLocInfo() != CCValAssign::BCvt))
3685       return false;
3686
3687     // Only handle register returns for now.
3688     if (!VA.isRegLoc())
3689       return false;
3690
3691     unsigned Reg = getRegForValue(RV);
3692     if (Reg == 0)
3693       return false;
3694
3695     unsigned SrcReg = Reg + VA.getValNo();
3696     unsigned DestReg = VA.getLocReg();
3697     // Avoid a cross-class copy. This is very unlikely.
3698     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3699       return false;
3700
3701     EVT RVEVT = TLI.getValueType(RV->getType());
3702     if (!RVEVT.isSimple())
3703       return false;
3704
3705     // Vectors (of > 1 lane) in big endian need tricky handling.
3706     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3707         !Subtarget->isLittleEndian())
3708       return false;
3709
3710     MVT RVVT = RVEVT.getSimpleVT();
3711     if (RVVT == MVT::f128)
3712       return false;
3713
3714     MVT DestVT = VA.getValVT();
3715     // Special handling for extended integers.
3716     if (RVVT != DestVT) {
3717       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3718         return false;
3719
3720       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3721         return false;
3722
3723       bool IsZExt = Outs[0].Flags.isZExt();
3724       SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3725       if (SrcReg == 0)
3726         return false;
3727     }
3728
3729     // Make the copy.
3730     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3731             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3732
3733     // Add register to return instruction.
3734     RetRegs.push_back(VA.getLocReg());
3735   }
3736
3737   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3738                                     TII.get(AArch64::RET_ReallyLR));
3739   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3740     MIB.addReg(RetRegs[i], RegState::Implicit);
3741   return true;
3742 }
3743
3744 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3745   Type *DestTy = I->getType();
3746   Value *Op = I->getOperand(0);
3747   Type *SrcTy = Op->getType();
3748
3749   EVT SrcEVT = TLI.getValueType(SrcTy, true);
3750   EVT DestEVT = TLI.getValueType(DestTy, true);
3751   if (!SrcEVT.isSimple())
3752     return false;
3753   if (!DestEVT.isSimple())
3754     return false;
3755
3756   MVT SrcVT = SrcEVT.getSimpleVT();
3757   MVT DestVT = DestEVT.getSimpleVT();
3758
3759   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3760       SrcVT != MVT::i8)
3761     return false;
3762   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3763       DestVT != MVT::i1)
3764     return false;
3765
3766   unsigned SrcReg = getRegForValue(Op);
3767   if (!SrcReg)
3768     return false;
3769   bool SrcIsKill = hasTrivialKill(Op);
3770
3771   // If we're truncating from i64 to a smaller non-legal type then generate an
3772   // AND. Otherwise, we know the high bits are undefined and a truncate only
3773   // generate a COPY. We cannot mark the source register also as result
3774   // register, because this can incorrectly transfer the kill flag onto the
3775   // source register.
3776   unsigned ResultReg;
3777   if (SrcVT == MVT::i64) {
3778     uint64_t Mask = 0;
3779     switch (DestVT.SimpleTy) {
3780     default:
3781       // Trunc i64 to i32 is handled by the target-independent fast-isel.
3782       return false;
3783     case MVT::i1:
3784       Mask = 0x1;
3785       break;
3786     case MVT::i8:
3787       Mask = 0xff;
3788       break;
3789     case MVT::i16:
3790       Mask = 0xffff;
3791       break;
3792     }
3793     // Issue an extract_subreg to get the lower 32-bits.
3794     unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3795                                                 AArch64::sub_32);
3796     // Create the AND instruction which performs the actual truncation.
3797     ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3798     assert(ResultReg && "Unexpected AND instruction emission failure.");
3799   } else {
3800     ResultReg = createResultReg(&AArch64::GPR32RegClass);
3801     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3802             TII.get(TargetOpcode::COPY), ResultReg)
3803         .addReg(SrcReg, getKillRegState(SrcIsKill));
3804   }
3805
3806   updateValueMap(I, ResultReg);
3807   return true;
3808 }
3809
3810 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3811   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3812           DestVT == MVT::i64) &&
3813          "Unexpected value type.");
3814   // Handle i8 and i16 as i32.
3815   if (DestVT == MVT::i8 || DestVT == MVT::i16)
3816     DestVT = MVT::i32;
3817
3818   if (IsZExt) {
3819     unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3820     assert(ResultReg && "Unexpected AND instruction emission failure.");
3821     if (DestVT == MVT::i64) {
3822       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
3823       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
3824       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3825       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3826               TII.get(AArch64::SUBREG_TO_REG), Reg64)
3827           .addImm(0)
3828           .addReg(ResultReg)
3829           .addImm(AArch64::sub_32);
3830       ResultReg = Reg64;
3831     }
3832     return ResultReg;
3833   } else {
3834     if (DestVT == MVT::i64) {
3835       // FIXME: We're SExt i1 to i64.
3836       return 0;
3837     }
3838     return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3839                             /*TODO:IsKill=*/false, 0, 0);
3840   }
3841 }
3842
3843 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3844                                       unsigned Op1, bool Op1IsKill) {
3845   unsigned Opc, ZReg;
3846   switch (RetVT.SimpleTy) {
3847   default: return 0;
3848   case MVT::i8:
3849   case MVT::i16:
3850   case MVT::i32:
3851     RetVT = MVT::i32;
3852     Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3853   case MVT::i64:
3854     Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3855   }
3856
3857   const TargetRegisterClass *RC =
3858       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3859   return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3860                           /*IsKill=*/ZReg, true);
3861 }
3862
3863 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3864                                         unsigned Op1, bool Op1IsKill) {
3865   if (RetVT != MVT::i64)
3866     return 0;
3867
3868   return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3869                           Op0, Op0IsKill, Op1, Op1IsKill,
3870                           AArch64::XZR, /*IsKill=*/true);
3871 }
3872
3873 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3874                                         unsigned Op1, bool Op1IsKill) {
3875   if (RetVT != MVT::i64)
3876     return 0;
3877
3878   return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3879                           Op0, Op0IsKill, Op1, Op1IsKill,
3880                           AArch64::XZR, /*IsKill=*/true);
3881 }
3882
3883 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3884                                      unsigned Op1Reg, bool Op1IsKill) {
3885   unsigned Opc = 0;
3886   bool NeedTrunc = false;
3887   uint64_t Mask = 0;
3888   switch (RetVT.SimpleTy) {
3889   default: return 0;
3890   case MVT::i8:  Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff;   break;
3891   case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3892   case MVT::i32: Opc = AArch64::LSLVWr;                                  break;
3893   case MVT::i64: Opc = AArch64::LSLVXr;                                  break;
3894   }
3895
3896   const TargetRegisterClass *RC =
3897       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3898   if (NeedTrunc) {
3899     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3900     Op1IsKill = true;
3901   }
3902   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3903                                        Op1IsKill);
3904   if (NeedTrunc)
3905     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3906   return ResultReg;
3907 }
3908
3909 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3910                                      bool Op0IsKill, uint64_t Shift,
3911                                      bool IsZExt) {
3912   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3913          "Unexpected source/return type pair.");
3914   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3915           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3916          "Unexpected source value type.");
3917   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3918           RetVT == MVT::i64) && "Unexpected return value type.");
3919
3920   bool Is64Bit = (RetVT == MVT::i64);
3921   unsigned RegSize = Is64Bit ? 64 : 32;
3922   unsigned DstBits = RetVT.getSizeInBits();
3923   unsigned SrcBits = SrcVT.getSizeInBits();
3924   const TargetRegisterClass *RC =
3925       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3926
3927   // Just emit a copy for "zero" shifts.
3928   if (Shift == 0) {
3929     if (RetVT == SrcVT) {
3930       unsigned ResultReg = createResultReg(RC);
3931       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3932               TII.get(TargetOpcode::COPY), ResultReg)
3933           .addReg(Op0, getKillRegState(Op0IsKill));
3934       return ResultReg;
3935     } else
3936       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3937   }
3938
3939   // Don't deal with undefined shifts.
3940   if (Shift >= DstBits)
3941     return 0;
3942
3943   // For immediate shifts we can fold the zero-/sign-extension into the shift.
3944   // {S|U}BFM Wd, Wn, #r, #s
3945   // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3946
3947   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3948   // %2 = shl i16 %1, 4
3949   // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3950   // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3951   // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3952   // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3953
3954   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3955   // %2 = shl i16 %1, 8
3956   // Wd<32+7-24,32-24> = Wn<7:0>
3957   // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3958   // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3959   // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3960
3961   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3962   // %2 = shl i16 %1, 12
3963   // Wd<32+3-20,32-20> = Wn<3:0>
3964   // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3965   // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3966   // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3967
3968   unsigned ImmR = RegSize - Shift;
3969   // Limit the width to the length of the source type.
3970   unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3971   static const unsigned OpcTable[2][2] = {
3972     {AArch64::SBFMWri, AArch64::SBFMXri},
3973     {AArch64::UBFMWri, AArch64::UBFMXri}
3974   };
3975   unsigned Opc = OpcTable[IsZExt][Is64Bit];
3976   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3977     unsigned TmpReg = MRI.createVirtualRegister(RC);
3978     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3979             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3980         .addImm(0)
3981         .addReg(Op0, getKillRegState(Op0IsKill))
3982         .addImm(AArch64::sub_32);
3983     Op0 = TmpReg;
3984     Op0IsKill = true;
3985   }
3986   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3987 }
3988
3989 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3990                                      unsigned Op1Reg, bool Op1IsKill) {
3991   unsigned Opc = 0;
3992   bool NeedTrunc = false;
3993   uint64_t Mask = 0;
3994   switch (RetVT.SimpleTy) {
3995   default: return 0;
3996   case MVT::i8:  Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff;   break;
3997   case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3998   case MVT::i32: Opc = AArch64::LSRVWr; break;
3999   case MVT::i64: Opc = AArch64::LSRVXr; break;
4000   }
4001
4002   const TargetRegisterClass *RC =
4003       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4004   if (NeedTrunc) {
4005     Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4006     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4007     Op0IsKill = Op1IsKill = true;
4008   }
4009   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4010                                        Op1IsKill);
4011   if (NeedTrunc)
4012     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4013   return ResultReg;
4014 }
4015
4016 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4017                                      bool Op0IsKill, uint64_t Shift,
4018                                      bool IsZExt) {
4019   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4020          "Unexpected source/return type pair.");
4021   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4022           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4023          "Unexpected source value type.");
4024   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4025           RetVT == MVT::i64) && "Unexpected return value type.");
4026
4027   bool Is64Bit = (RetVT == MVT::i64);
4028   unsigned RegSize = Is64Bit ? 64 : 32;
4029   unsigned DstBits = RetVT.getSizeInBits();
4030   unsigned SrcBits = SrcVT.getSizeInBits();
4031   const TargetRegisterClass *RC =
4032       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4033
4034   // Just emit a copy for "zero" shifts.
4035   if (Shift == 0) {
4036     if (RetVT == SrcVT) {
4037       unsigned ResultReg = createResultReg(RC);
4038       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4039               TII.get(TargetOpcode::COPY), ResultReg)
4040       .addReg(Op0, getKillRegState(Op0IsKill));
4041       return ResultReg;
4042     } else
4043       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4044   }
4045
4046   // Don't deal with undefined shifts.
4047   if (Shift >= DstBits)
4048     return 0;
4049
4050   // For immediate shifts we can fold the zero-/sign-extension into the shift.
4051   // {S|U}BFM Wd, Wn, #r, #s
4052   // Wd<s-r:0> = Wn<s:r> when r <= s
4053
4054   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4055   // %2 = lshr i16 %1, 4
4056   // Wd<7-4:0> = Wn<7:4>
4057   // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4058   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4059   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4060
4061   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4062   // %2 = lshr i16 %1, 8
4063   // Wd<7-7,0> = Wn<7:7>
4064   // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4065   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4066   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4067
4068   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4069   // %2 = lshr i16 %1, 12
4070   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4071   // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4072   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4073   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4074
4075   if (Shift >= SrcBits && IsZExt)
4076     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4077
4078   // It is not possible to fold a sign-extend into the LShr instruction. In this
4079   // case emit a sign-extend.
4080   if (!IsZExt) {
4081     Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4082     if (!Op0)
4083       return 0;
4084     Op0IsKill = true;
4085     SrcVT = RetVT;
4086     SrcBits = SrcVT.getSizeInBits();
4087     IsZExt = true;
4088   }
4089
4090   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4091   unsigned ImmS = SrcBits - 1;
4092   static const unsigned OpcTable[2][2] = {
4093     {AArch64::SBFMWri, AArch64::SBFMXri},
4094     {AArch64::UBFMWri, AArch64::UBFMXri}
4095   };
4096   unsigned Opc = OpcTable[IsZExt][Is64Bit];
4097   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4098     unsigned TmpReg = MRI.createVirtualRegister(RC);
4099     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4100             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4101         .addImm(0)
4102         .addReg(Op0, getKillRegState(Op0IsKill))
4103         .addImm(AArch64::sub_32);
4104     Op0 = TmpReg;
4105     Op0IsKill = true;
4106   }
4107   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4108 }
4109
4110 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4111                                      unsigned Op1Reg, bool Op1IsKill) {
4112   unsigned Opc = 0;
4113   bool NeedTrunc = false;
4114   uint64_t Mask = 0;
4115   switch (RetVT.SimpleTy) {
4116   default: return 0;
4117   case MVT::i8:  Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff;   break;
4118   case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4119   case MVT::i32: Opc = AArch64::ASRVWr;                                  break;
4120   case MVT::i64: Opc = AArch64::ASRVXr;                                  break;
4121   }
4122
4123   const TargetRegisterClass *RC =
4124       (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4125   if (NeedTrunc) {
4126     Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4127     Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4128     Op0IsKill = Op1IsKill = true;
4129   }
4130   unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4131                                        Op1IsKill);
4132   if (NeedTrunc)
4133     ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4134   return ResultReg;
4135 }
4136
4137 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4138                                      bool Op0IsKill, uint64_t Shift,
4139                                      bool IsZExt) {
4140   assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4141          "Unexpected source/return type pair.");
4142   assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4143           SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4144          "Unexpected source value type.");
4145   assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4146           RetVT == MVT::i64) && "Unexpected return value type.");
4147
4148   bool Is64Bit = (RetVT == MVT::i64);
4149   unsigned RegSize = Is64Bit ? 64 : 32;
4150   unsigned DstBits = RetVT.getSizeInBits();
4151   unsigned SrcBits = SrcVT.getSizeInBits();
4152   const TargetRegisterClass *RC =
4153       Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4154
4155   // Just emit a copy for "zero" shifts.
4156   if (Shift == 0) {
4157     if (RetVT == SrcVT) {
4158       unsigned ResultReg = createResultReg(RC);
4159       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4160               TII.get(TargetOpcode::COPY), ResultReg)
4161       .addReg(Op0, getKillRegState(Op0IsKill));
4162       return ResultReg;
4163     } else
4164       return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4165   }
4166
4167   // Don't deal with undefined shifts.
4168   if (Shift >= DstBits)
4169     return 0;
4170
4171   // For immediate shifts we can fold the zero-/sign-extension into the shift.
4172   // {S|U}BFM Wd, Wn, #r, #s
4173   // Wd<s-r:0> = Wn<s:r> when r <= s
4174
4175   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4176   // %2 = ashr i16 %1, 4
4177   // Wd<7-4:0> = Wn<7:4>
4178   // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4179   // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4180   // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4181
4182   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4183   // %2 = ashr i16 %1, 8
4184   // Wd<7-7,0> = Wn<7:7>
4185   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4186   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4187   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4188
4189   // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4190   // %2 = ashr i16 %1, 12
4191   // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4192   // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4193   // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4194   // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4195
4196   if (Shift >= SrcBits && IsZExt)
4197     return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4198
4199   unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4200   unsigned ImmS = SrcBits - 1;
4201   static const unsigned OpcTable[2][2] = {
4202     {AArch64::SBFMWri, AArch64::SBFMXri},
4203     {AArch64::UBFMWri, AArch64::UBFMXri}
4204   };
4205   unsigned Opc = OpcTable[IsZExt][Is64Bit];
4206   if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4207     unsigned TmpReg = MRI.createVirtualRegister(RC);
4208     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4209             TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4210         .addImm(0)
4211         .addReg(Op0, getKillRegState(Op0IsKill))
4212         .addImm(AArch64::sub_32);
4213     Op0 = TmpReg;
4214     Op0IsKill = true;
4215   }
4216   return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4217 }
4218
4219 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4220                                      bool IsZExt) {
4221   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4222
4223   // FastISel does not have plumbing to deal with extensions where the SrcVT or
4224   // DestVT are odd things, so test to make sure that they are both types we can
4225   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4226   // bail out to SelectionDAG.
4227   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4228        (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4229       ((SrcVT !=  MVT::i1) && (SrcVT !=  MVT::i8) &&
4230        (SrcVT !=  MVT::i16) && (SrcVT !=  MVT::i32)))
4231     return 0;
4232
4233   unsigned Opc;
4234   unsigned Imm = 0;
4235
4236   switch (SrcVT.SimpleTy) {
4237   default:
4238     return 0;
4239   case MVT::i1:
4240     return emiti1Ext(SrcReg, DestVT, IsZExt);
4241   case MVT::i8:
4242     if (DestVT == MVT::i64)
4243       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4244     else
4245       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4246     Imm = 7;
4247     break;
4248   case MVT::i16:
4249     if (DestVT == MVT::i64)
4250       Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4251     else
4252       Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4253     Imm = 15;
4254     break;
4255   case MVT::i32:
4256     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4257     Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4258     Imm = 31;
4259     break;
4260   }
4261
4262   // Handle i8 and i16 as i32.
4263   if (DestVT == MVT::i8 || DestVT == MVT::i16)
4264     DestVT = MVT::i32;
4265   else if (DestVT == MVT::i64) {
4266     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4267     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4268             TII.get(AArch64::SUBREG_TO_REG), Src64)
4269         .addImm(0)
4270         .addReg(SrcReg)
4271         .addImm(AArch64::sub_32);
4272     SrcReg = Src64;
4273   }
4274
4275   const TargetRegisterClass *RC =
4276       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4277   return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4278 }
4279
4280 static bool isZExtLoad(const MachineInstr *LI) {
4281   switch (LI->getOpcode()) {
4282   default:
4283     return false;
4284   case AArch64::LDURBBi:
4285   case AArch64::LDURHHi:
4286   case AArch64::LDURWi:
4287   case AArch64::LDRBBui:
4288   case AArch64::LDRHHui:
4289   case AArch64::LDRWui:
4290   case AArch64::LDRBBroX:
4291   case AArch64::LDRHHroX:
4292   case AArch64::LDRWroX:
4293   case AArch64::LDRBBroW:
4294   case AArch64::LDRHHroW:
4295   case AArch64::LDRWroW:
4296     return true;
4297   }
4298 }
4299
4300 static bool isSExtLoad(const MachineInstr *LI) {
4301   switch (LI->getOpcode()) {
4302   default:
4303     return false;
4304   case AArch64::LDURSBWi:
4305   case AArch64::LDURSHWi:
4306   case AArch64::LDURSBXi:
4307   case AArch64::LDURSHXi:
4308   case AArch64::LDURSWi:
4309   case AArch64::LDRSBWui:
4310   case AArch64::LDRSHWui:
4311   case AArch64::LDRSBXui:
4312   case AArch64::LDRSHXui:
4313   case AArch64::LDRSWui:
4314   case AArch64::LDRSBWroX:
4315   case AArch64::LDRSHWroX:
4316   case AArch64::LDRSBXroX:
4317   case AArch64::LDRSHXroX:
4318   case AArch64::LDRSWroX:
4319   case AArch64::LDRSBWroW:
4320   case AArch64::LDRSHWroW:
4321   case AArch64::LDRSBXroW:
4322   case AArch64::LDRSHXroW:
4323   case AArch64::LDRSWroW:
4324     return true;
4325   }
4326 }
4327
4328 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4329                                          MVT SrcVT) {
4330   const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4331   if (!LI || !LI->hasOneUse())
4332     return false;
4333
4334   // Check if the load instruction has already been selected.
4335   unsigned Reg = lookUpRegForValue(LI);
4336   if (!Reg)
4337     return false;
4338
4339   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4340   if (!MI)
4341     return false;
4342
4343   // Check if the correct load instruction has been emitted - SelectionDAG might
4344   // have emitted a zero-extending load, but we need a sign-extending load.
4345   bool IsZExt = isa<ZExtInst>(I);
4346   const auto *LoadMI = MI;
4347   if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4348       LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4349     unsigned LoadReg = MI->getOperand(1).getReg();
4350     LoadMI = MRI.getUniqueVRegDef(LoadReg);
4351     assert(LoadMI && "Expected valid instruction");
4352   }
4353   if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4354     return false;
4355
4356   // Nothing to be done.
4357   if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4358     updateValueMap(I, Reg);
4359     return true;
4360   }
4361
4362   if (IsZExt) {
4363     unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4364     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4365             TII.get(AArch64::SUBREG_TO_REG), Reg64)
4366         .addImm(0)
4367         .addReg(Reg, getKillRegState(true))
4368         .addImm(AArch64::sub_32);
4369     Reg = Reg64;
4370   } else {
4371     assert((MI->getOpcode() == TargetOpcode::COPY &&
4372             MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4373            "Expected copy instruction");
4374     Reg = MI->getOperand(1).getReg();
4375     MI->eraseFromParent();
4376   }
4377   updateValueMap(I, Reg);
4378   return true;
4379 }
4380
4381 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4382   assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4383          "Unexpected integer extend instruction.");
4384   MVT RetVT;
4385   MVT SrcVT;
4386   if (!isTypeSupported(I->getType(), RetVT))
4387     return false;
4388
4389   if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4390     return false;
4391
4392   // Try to optimize already sign-/zero-extended values from load instructions.
4393   if (optimizeIntExtLoad(I, RetVT, SrcVT))
4394     return true;
4395
4396   unsigned SrcReg = getRegForValue(I->getOperand(0));
4397   if (!SrcReg)
4398     return false;
4399   bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4400
4401   // Try to optimize already sign-/zero-extended values from function arguments.
4402   bool IsZExt = isa<ZExtInst>(I);
4403   if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4404     if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4405       if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4406         unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4407         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4408                 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4409             .addImm(0)
4410             .addReg(SrcReg, getKillRegState(SrcIsKill))
4411             .addImm(AArch64::sub_32);
4412         SrcReg = ResultReg;
4413       }
4414       // Conservatively clear all kill flags from all uses, because we are
4415       // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4416       // level. The result of the instruction at IR level might have been
4417       // trivially dead, which is now not longer true.
4418       unsigned UseReg = lookUpRegForValue(I);
4419       if (UseReg)
4420         MRI.clearKillFlags(UseReg);
4421
4422       updateValueMap(I, SrcReg);
4423       return true;
4424     }
4425   }
4426
4427   unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4428   if (!ResultReg)
4429     return false;
4430
4431   updateValueMap(I, ResultReg);
4432   return true;
4433 }
4434
4435 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4436   EVT DestEVT = TLI.getValueType(I->getType(), true);
4437   if (!DestEVT.isSimple())
4438     return false;
4439
4440   MVT DestVT = DestEVT.getSimpleVT();
4441   if (DestVT != MVT::i64 && DestVT != MVT::i32)
4442     return false;
4443
4444   unsigned DivOpc;
4445   bool Is64bit = (DestVT == MVT::i64);
4446   switch (ISDOpcode) {
4447   default:
4448     return false;
4449   case ISD::SREM:
4450     DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4451     break;
4452   case ISD::UREM:
4453     DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4454     break;
4455   }
4456   unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4457   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4458   if (!Src0Reg)
4459     return false;
4460   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4461
4462   unsigned Src1Reg = getRegForValue(I->getOperand(1));
4463   if (!Src1Reg)
4464     return false;
4465   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4466
4467   const TargetRegisterClass *RC =
4468       (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4469   unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4470                                      Src1Reg, /*IsKill=*/false);
4471   assert(QuotReg && "Unexpected DIV instruction emission failure.");
4472   // The remainder is computed as numerator - (quotient * denominator) using the
4473   // MSUB instruction.
4474   unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4475                                         Src1Reg, Src1IsKill, Src0Reg,
4476                                         Src0IsKill);
4477   updateValueMap(I, ResultReg);
4478   return true;
4479 }
4480
4481 bool AArch64FastISel::selectMul(const Instruction *I) {
4482   MVT VT;
4483   if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4484     return false;
4485
4486   if (VT.isVector())
4487     return selectBinaryOp(I, ISD::MUL);
4488
4489   const Value *Src0 = I->getOperand(0);
4490   const Value *Src1 = I->getOperand(1);
4491   if (const auto *C = dyn_cast<ConstantInt>(Src0))
4492     if (C->getValue().isPowerOf2())
4493       std::swap(Src0, Src1);
4494
4495   // Try to simplify to a shift instruction.
4496   if (const auto *C = dyn_cast<ConstantInt>(Src1))
4497     if (C->getValue().isPowerOf2()) {
4498       uint64_t ShiftVal = C->getValue().logBase2();
4499       MVT SrcVT = VT;
4500       bool IsZExt = true;
4501       if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4502         if (!isIntExtFree(ZExt)) {
4503           MVT VT;
4504           if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4505             SrcVT = VT;
4506             IsZExt = true;
4507             Src0 = ZExt->getOperand(0);
4508           }
4509         }
4510       } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4511         if (!isIntExtFree(SExt)) {
4512           MVT VT;
4513           if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4514             SrcVT = VT;
4515             IsZExt = false;
4516             Src0 = SExt->getOperand(0);
4517           }
4518         }
4519       }
4520
4521       unsigned Src0Reg = getRegForValue(Src0);
4522       if (!Src0Reg)
4523         return false;
4524       bool Src0IsKill = hasTrivialKill(Src0);
4525
4526       unsigned ResultReg =
4527           emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4528
4529       if (ResultReg) {
4530         updateValueMap(I, ResultReg);
4531         return true;
4532       }
4533     }
4534
4535   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4536   if (!Src0Reg)
4537     return false;
4538   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4539
4540   unsigned Src1Reg = getRegForValue(I->getOperand(1));
4541   if (!Src1Reg)
4542     return false;
4543   bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4544
4545   unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4546
4547   if (!ResultReg)
4548     return false;
4549
4550   updateValueMap(I, ResultReg);
4551   return true;
4552 }
4553
4554 bool AArch64FastISel::selectShift(const Instruction *I) {
4555   MVT RetVT;
4556   if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4557     return false;
4558
4559   if (RetVT.isVector())
4560     return selectOperator(I, I->getOpcode());
4561
4562   if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4563     unsigned ResultReg = 0;
4564     uint64_t ShiftVal = C->getZExtValue();
4565     MVT SrcVT = RetVT;
4566     bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4567     const Value *Op0 = I->getOperand(0);
4568     if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4569       if (!isIntExtFree(ZExt)) {
4570         MVT TmpVT;
4571         if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4572           SrcVT = TmpVT;
4573           IsZExt = true;
4574           Op0 = ZExt->getOperand(0);
4575         }
4576       }
4577     } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4578       if (!isIntExtFree(SExt)) {
4579         MVT TmpVT;
4580         if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4581           SrcVT = TmpVT;
4582           IsZExt = false;
4583           Op0 = SExt->getOperand(0);
4584         }
4585       }
4586     }
4587
4588     unsigned Op0Reg = getRegForValue(Op0);
4589     if (!Op0Reg)
4590       return false;
4591     bool Op0IsKill = hasTrivialKill(Op0);
4592
4593     switch (I->getOpcode()) {
4594     default: llvm_unreachable("Unexpected instruction.");
4595     case Instruction::Shl:
4596       ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4597       break;
4598     case Instruction::AShr:
4599       ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4600       break;
4601     case Instruction::LShr:
4602       ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4603       break;
4604     }
4605     if (!ResultReg)
4606       return false;
4607
4608     updateValueMap(I, ResultReg);
4609     return true;
4610   }
4611
4612   unsigned Op0Reg = getRegForValue(I->getOperand(0));
4613   if (!Op0Reg)
4614     return false;
4615   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4616
4617   unsigned Op1Reg = getRegForValue(I->getOperand(1));
4618   if (!Op1Reg)
4619     return false;
4620   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4621
4622   unsigned ResultReg = 0;
4623   switch (I->getOpcode()) {
4624   default: llvm_unreachable("Unexpected instruction.");
4625   case Instruction::Shl:
4626     ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4627     break;
4628   case Instruction::AShr:
4629     ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4630     break;
4631   case Instruction::LShr:
4632     ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4633     break;
4634   }
4635
4636   if (!ResultReg)
4637     return false;
4638
4639   updateValueMap(I, ResultReg);
4640   return true;
4641 }
4642
4643 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4644   MVT RetVT, SrcVT;
4645
4646   if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4647     return false;
4648   if (!isTypeLegal(I->getType(), RetVT))
4649     return false;
4650
4651   unsigned Opc;
4652   if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4653     Opc = AArch64::FMOVWSr;
4654   else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4655     Opc = AArch64::FMOVXDr;
4656   else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4657     Opc = AArch64::FMOVSWr;
4658   else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4659     Opc = AArch64::FMOVDXr;
4660   else
4661     return false;
4662
4663   const TargetRegisterClass *RC = nullptr;
4664   switch (RetVT.SimpleTy) {
4665   default: llvm_unreachable("Unexpected value type.");
4666   case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4667   case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4668   case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4669   case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4670   }
4671   unsigned Op0Reg = getRegForValue(I->getOperand(0));
4672   if (!Op0Reg)
4673     return false;
4674   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4675   unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4676
4677   if (!ResultReg)
4678     return false;
4679
4680   updateValueMap(I, ResultReg);
4681   return true;
4682 }
4683
4684 bool AArch64FastISel::selectFRem(const Instruction *I) {
4685   MVT RetVT;
4686   if (!isTypeLegal(I->getType(), RetVT))
4687     return false;
4688
4689   RTLIB::Libcall LC;
4690   switch (RetVT.SimpleTy) {
4691   default:
4692     return false;
4693   case MVT::f32:
4694     LC = RTLIB::REM_F32;
4695     break;
4696   case MVT::f64:
4697     LC = RTLIB::REM_F64;
4698     break;
4699   }
4700
4701   ArgListTy Args;
4702   Args.reserve(I->getNumOperands());
4703
4704   // Populate the argument list.
4705   for (auto &Arg : I->operands()) {
4706     ArgListEntry Entry;
4707     Entry.Val = Arg;
4708     Entry.Ty = Arg->getType();
4709     Args.push_back(Entry);
4710   }
4711
4712   CallLoweringInfo CLI;
4713   CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4714                 TLI.getLibcallName(LC), std::move(Args));
4715   if (!lowerCallTo(CLI))
4716     return false;
4717   updateValueMap(I, CLI.ResultReg);
4718   return true;
4719 }
4720
4721 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4722   MVT VT;
4723   if (!isTypeLegal(I->getType(), VT))
4724     return false;
4725
4726   if (!isa<ConstantInt>(I->getOperand(1)))
4727     return selectBinaryOp(I, ISD::SDIV);
4728
4729   const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4730   if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4731       !(C.isPowerOf2() || (-C).isPowerOf2()))
4732     return selectBinaryOp(I, ISD::SDIV);
4733
4734   unsigned Lg2 = C.countTrailingZeros();
4735   unsigned Src0Reg = getRegForValue(I->getOperand(0));
4736   if (!Src0Reg)
4737     return false;
4738   bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4739
4740   if (cast<BinaryOperator>(I)->isExact()) {
4741     unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4742     if (!ResultReg)
4743       return false;
4744     updateValueMap(I, ResultReg);
4745     return true;
4746   }
4747
4748   int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4749   unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4750   if (!AddReg)
4751     return false;
4752
4753   // (Src0 < 0) ? Pow2 - 1 : 0;
4754   if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4755     return false;
4756
4757   unsigned SelectOpc;
4758   const TargetRegisterClass *RC;
4759   if (VT == MVT::i64) {
4760     SelectOpc = AArch64::CSELXr;
4761     RC = &AArch64::GPR64RegClass;
4762   } else {
4763     SelectOpc = AArch64::CSELWr;
4764     RC = &AArch64::GPR32RegClass;
4765   }
4766   unsigned SelectReg =
4767       fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4768                        Src0IsKill, AArch64CC::LT);
4769   if (!SelectReg)
4770     return false;
4771
4772   // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4773   // negate the result.
4774   unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4775   unsigned ResultReg;
4776   if (C.isNegative())
4777     ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4778                               SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4779   else
4780     ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4781
4782   if (!ResultReg)
4783     return false;
4784
4785   updateValueMap(I, ResultReg);
4786   return true;
4787 }
4788
4789 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4790 /// have to duplicate it for AArch64, because otherwise we would fail during the
4791 /// sign-extend emission.
4792 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4793   unsigned IdxN = getRegForValue(Idx);
4794   if (IdxN == 0)
4795     // Unhandled operand. Halt "fast" selection and bail.
4796     return std::pair<unsigned, bool>(0, false);
4797
4798   bool IdxNIsKill = hasTrivialKill(Idx);
4799
4800   // If the index is smaller or larger than intptr_t, truncate or extend it.
4801   MVT PtrVT = TLI.getPointerTy();
4802   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4803   if (IdxVT.bitsLT(PtrVT)) {
4804     IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4805     IdxNIsKill = true;
4806   } else if (IdxVT.bitsGT(PtrVT))
4807     llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4808   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4809 }
4810
4811 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4812 /// duplicate it for AArch64, because otherwise we would bail out even for
4813 /// simple cases. This is because the standard fastEmit functions don't cover
4814 /// MUL at all and ADD is lowered very inefficientily.
4815 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4816   unsigned N = getRegForValue(I->getOperand(0));
4817   if (!N)
4818     return false;
4819   bool NIsKill = hasTrivialKill(I->getOperand(0));
4820
4821   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4822   // into a single N = N + TotalOffset.
4823   uint64_t TotalOffs = 0;
4824   Type *Ty = I->getOperand(0)->getType();
4825   MVT VT = TLI.getPointerTy();
4826   for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4827     const Value *Idx = *OI;
4828     if (auto *StTy = dyn_cast<StructType>(Ty)) {
4829       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4830       // N = N + Offset
4831       if (Field)
4832         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4833       Ty = StTy->getElementType(Field);
4834     } else {
4835       Ty = cast<SequentialType>(Ty)->getElementType();
4836       // If this is a constant subscript, handle it quickly.
4837       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4838         if (CI->isZero())
4839           continue;
4840         // N = N + Offset
4841         TotalOffs +=
4842             DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4843         continue;
4844       }
4845       if (TotalOffs) {
4846         N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4847         if (!N)
4848           return false;
4849         NIsKill = true;
4850         TotalOffs = 0;
4851       }
4852
4853       // N = N + Idx * ElementSize;
4854       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4855       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4856       unsigned IdxN = Pair.first;
4857       bool IdxNIsKill = Pair.second;
4858       if (!IdxN)
4859         return false;
4860
4861       if (ElementSize != 1) {
4862         unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4863         if (!C)
4864           return false;
4865         IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4866         if (!IdxN)
4867           return false;
4868         IdxNIsKill = true;
4869       }
4870       N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4871       if (!N)
4872         return false;
4873     }
4874   }
4875   if (TotalOffs) {
4876     N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4877     if (!N)
4878       return false;
4879   }
4880   updateValueMap(I, N);
4881   return true;
4882 }
4883
4884 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4885   switch (I->getOpcode()) {
4886   default:
4887     break;
4888   case Instruction::Add:
4889   case Instruction::Sub:
4890     return selectAddSub(I);
4891   case Instruction::Mul:
4892     return selectMul(I);
4893   case Instruction::SDiv:
4894     return selectSDiv(I);
4895   case Instruction::SRem:
4896     if (!selectBinaryOp(I, ISD::SREM))
4897       return selectRem(I, ISD::SREM);
4898     return true;
4899   case Instruction::URem:
4900     if (!selectBinaryOp(I, ISD::UREM))
4901       return selectRem(I, ISD::UREM);
4902     return true;
4903   case Instruction::Shl:
4904   case Instruction::LShr:
4905   case Instruction::AShr:
4906     return selectShift(I);
4907   case Instruction::And:
4908   case Instruction::Or:
4909   case Instruction::Xor:
4910     return selectLogicalOp(I);
4911   case Instruction::Br:
4912     return selectBranch(I);
4913   case Instruction::IndirectBr:
4914     return selectIndirectBr(I);
4915   case Instruction::BitCast:
4916     if (!FastISel::selectBitCast(I))
4917       return selectBitCast(I);
4918     return true;
4919   case Instruction::FPToSI:
4920     if (!selectCast(I, ISD::FP_TO_SINT))
4921       return selectFPToInt(I, /*Signed=*/true);
4922     return true;
4923   case Instruction::FPToUI:
4924     return selectFPToInt(I, /*Signed=*/false);
4925   case Instruction::ZExt:
4926   case Instruction::SExt:
4927     return selectIntExt(I);
4928   case Instruction::Trunc:
4929     if (!selectCast(I, ISD::TRUNCATE))
4930       return selectTrunc(I);
4931     return true;
4932   case Instruction::FPExt:
4933     return selectFPExt(I);
4934   case Instruction::FPTrunc:
4935     return selectFPTrunc(I);
4936   case Instruction::SIToFP:
4937     if (!selectCast(I, ISD::SINT_TO_FP))
4938       return selectIntToFP(I, /*Signed=*/true);
4939     return true;
4940   case Instruction::UIToFP:
4941     return selectIntToFP(I, /*Signed=*/false);
4942   case Instruction::Load:
4943     return selectLoad(I);
4944   case Instruction::Store:
4945     return selectStore(I);
4946   case Instruction::FCmp:
4947   case Instruction::ICmp:
4948     return selectCmp(I);
4949   case Instruction::Select:
4950     return selectSelect(I);
4951   case Instruction::Ret:
4952     return selectRet(I);
4953   case Instruction::FRem:
4954     return selectFRem(I);
4955   case Instruction::GetElementPtr:
4956     return selectGetElementPtr(I);
4957   }
4958
4959   // fall-back to target-independent instruction selection.
4960   return selectOperator(I, I->getOpcode());
4961   // Silence warnings.
4962   (void)&CC_AArch64_DarwinPCS_VarArg;
4963 }
4964
4965 namespace llvm {
4966 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4967                                         const TargetLibraryInfo *LibInfo) {
4968   return new AArch64FastISel(FuncInfo, LibInfo);
4969 }
4970 }