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