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