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