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