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