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