[FastISel][AArch64] Add support for shift-immediate.
[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/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/FastISel.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/Support/CommandLine.h"
38 using namespace llvm;
39
40 namespace {
41
42 class AArch64FastISel : public FastISel {
43
44   class Address {
45   public:
46     typedef enum {
47       RegBase,
48       FrameIndexBase
49     } BaseKind;
50
51   private:
52     BaseKind Kind;
53     union {
54       unsigned Reg;
55       int FI;
56     } Base;
57     int64_t Offset;
58
59   public:
60     Address() : Kind(RegBase), Offset(0) { Base.Reg = 0; }
61     void setKind(BaseKind K) { Kind = K; }
62     BaseKind getKind() const { return Kind; }
63     bool isRegBase() const { return Kind == RegBase; }
64     bool isFIBase() const { return Kind == FrameIndexBase; }
65     void setReg(unsigned Reg) {
66       assert(isRegBase() && "Invalid base register access!");
67       Base.Reg = Reg;
68     }
69     unsigned getReg() const {
70       assert(isRegBase() && "Invalid base register access!");
71       return Base.Reg;
72     }
73     void setFI(unsigned FI) {
74       assert(isFIBase() && "Invalid base frame index  access!");
75       Base.FI = FI;
76     }
77     unsigned getFI() const {
78       assert(isFIBase() && "Invalid base frame index access!");
79       return Base.FI;
80     }
81     void setOffset(int64_t O) { Offset = O; }
82     int64_t getOffset() { return Offset; }
83
84     bool isValid() { return isFIBase() || (isRegBase() && getReg() != 0); }
85   };
86
87   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
88   /// make the right decision when generating code for different targets.
89   const AArch64Subtarget *Subtarget;
90   LLVMContext *Context;
91
92   bool FastLowerCall(CallLoweringInfo &CLI) override;
93   bool FastLowerIntrinsicCall(const IntrinsicInst *II) override;
94
95 private:
96   // Selection routines.
97   bool SelectLoad(const Instruction *I);
98   bool SelectStore(const Instruction *I);
99   bool SelectBranch(const Instruction *I);
100   bool SelectIndirectBr(const Instruction *I);
101   bool SelectCmp(const Instruction *I);
102   bool SelectSelect(const Instruction *I);
103   bool SelectFPExt(const Instruction *I);
104   bool SelectFPTrunc(const Instruction *I);
105   bool SelectFPToInt(const Instruction *I, bool Signed);
106   bool SelectIntToFP(const Instruction *I, bool Signed);
107   bool SelectRem(const Instruction *I, unsigned ISDOpcode);
108   bool SelectRet(const Instruction *I);
109   bool SelectTrunc(const Instruction *I);
110   bool SelectIntExt(const Instruction *I);
111   bool SelectMul(const Instruction *I);
112   bool SelectShift(const Instruction *I, bool IsLeftShift, bool IsArithmetic);
113
114   // Utility helper routines.
115   bool isTypeLegal(Type *Ty, MVT &VT);
116   bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
117   bool ComputeAddress(const Value *Obj, Address &Addr);
118   bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
119                        bool UseUnscaled);
120   void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
121                             unsigned Flags, bool UseUnscaled);
122   bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
123   bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
124                           unsigned Alignment);
125   // Emit functions.
126   bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
127   bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
128                 bool UseUnscaled = false);
129   bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
130                  bool UseUnscaled = false);
131   unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
132   unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
133   unsigned Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
134   unsigned Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
135   unsigned Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
136
137   unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
138   unsigned AArch64MaterializeGV(const GlobalValue *GV);
139
140   // Call handling routines.
141 private:
142   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
143   bool ProcessCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
144                        unsigned &NumBytes);
145   bool FinishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
146
147 public:
148   // Backend specific FastISel code.
149   unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
150   unsigned TargetMaterializeConstant(const Constant *C) override;
151
152   explicit AArch64FastISel(FunctionLoweringInfo &funcInfo,
153                          const TargetLibraryInfo *libInfo)
154       : FastISel(funcInfo, libInfo) {
155     Subtarget = &TM.getSubtarget<AArch64Subtarget>();
156     Context = &funcInfo.Fn->getContext();
157   }
158
159   bool TargetSelectInstruction(const Instruction *I) override;
160
161 #include "AArch64GenFastISel.inc"
162 };
163
164 } // end anonymous namespace
165
166 #include "AArch64GenCallingConv.inc"
167
168 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
169   if (CC == CallingConv::WebKit_JS)
170     return CC_AArch64_WebKit_JS;
171   return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
172 }
173
174 unsigned AArch64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
175   assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
176          "Alloca should always return a pointer.");
177
178   // Don't handle dynamic allocas.
179   if (!FuncInfo.StaticAllocaMap.count(AI))
180     return 0;
181
182   DenseMap<const AllocaInst *, int>::iterator SI =
183       FuncInfo.StaticAllocaMap.find(AI);
184
185   if (SI != FuncInfo.StaticAllocaMap.end()) {
186     unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
187     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
188             ResultReg)
189         .addFrameIndex(SI->second)
190         .addImm(0)
191         .addImm(0);
192     return ResultReg;
193   }
194
195   return 0;
196 }
197
198 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
199   if (VT != MVT::f32 && VT != MVT::f64)
200     return 0;
201
202   const APFloat Val = CFP->getValueAPF();
203   bool is64bit = (VT == MVT::f64);
204
205   // This checks to see if we can use FMOV instructions to materialize
206   // a constant, otherwise we have to materialize via the constant pool.
207   if (TLI.isFPImmLegal(Val, VT)) {
208     int Imm;
209     unsigned Opc;
210     if (is64bit) {
211       Imm = AArch64_AM::getFP64Imm(Val);
212       Opc = AArch64::FMOVDi;
213     } else {
214       Imm = AArch64_AM::getFP32Imm(Val);
215       Opc = AArch64::FMOVSi;
216     }
217     unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
218     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
219         .addImm(Imm);
220     return ResultReg;
221   }
222
223   // Materialize via constant pool.  MachineConstantPool wants an explicit
224   // alignment.
225   unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
226   if (Align == 0)
227     Align = DL.getTypeAllocSize(CFP->getType());
228
229   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
230   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
231   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
232           ADRPReg).addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGE);
233
234   unsigned Opc = is64bit ? AArch64::LDRDui : AArch64::LDRSui;
235   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
236   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
237       .addReg(ADRPReg)
238       .addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
239   return ResultReg;
240 }
241
242 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
243   // We can't handle thread-local variables quickly yet.
244   if (GV->isThreadLocal())
245     return 0;
246
247   // MachO still uses GOT for large code-model accesses, but ELF requires
248   // movz/movk sequences, which FastISel doesn't handle yet.
249   if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
250     return 0;
251
252   unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
253
254   EVT DestEVT = TLI.getValueType(GV->getType(), true);
255   if (!DestEVT.isSimple())
256     return 0;
257
258   unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
259   unsigned ResultReg;
260
261   if (OpFlags & AArch64II::MO_GOT) {
262     // ADRP + LDRX
263     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
264             ADRPReg)
265         .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
266
267     ResultReg = createResultReg(&AArch64::GPR64RegClass);
268     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
269             ResultReg)
270         .addReg(ADRPReg)
271         .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
272                           AArch64II::MO_NC);
273   } else {
274     // ADRP + ADDX
275     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
276             ADRPReg).addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
277
278     ResultReg = createResultReg(&AArch64::GPR64spRegClass);
279     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
280             ResultReg)
281         .addReg(ADRPReg)
282         .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
283         .addImm(0);
284   }
285   return ResultReg;
286 }
287
288 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
289   EVT CEVT = TLI.getValueType(C->getType(), true);
290
291   // Only handle simple types.
292   if (!CEVT.isSimple())
293     return 0;
294   MVT VT = CEVT.getSimpleVT();
295
296   // FIXME: Handle ConstantInt.
297   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
298     return AArch64MaterializeFP(CFP, VT);
299   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
300     return AArch64MaterializeGV(GV);
301
302   return 0;
303 }
304
305 // Computes the address to get to an object.
306 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
307   const User *U = nullptr;
308   unsigned Opcode = Instruction::UserOp1;
309   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
310     // Don't walk into other basic blocks unless the object is an alloca from
311     // another block, otherwise it may not have a virtual register assigned.
312     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
313         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
314       Opcode = I->getOpcode();
315       U = I;
316     }
317   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
318     Opcode = C->getOpcode();
319     U = C;
320   }
321
322   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
323     if (Ty->getAddressSpace() > 255)
324       // Fast instruction selection doesn't support the special
325       // address spaces.
326       return false;
327
328   switch (Opcode) {
329   default:
330     break;
331   case Instruction::BitCast: {
332     // Look through bitcasts.
333     return ComputeAddress(U->getOperand(0), Addr);
334   }
335   case Instruction::IntToPtr: {
336     // Look past no-op inttoptrs.
337     if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
338       return ComputeAddress(U->getOperand(0), Addr);
339     break;
340   }
341   case Instruction::PtrToInt: {
342     // Look past no-op ptrtoints.
343     if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
344       return ComputeAddress(U->getOperand(0), Addr);
345     break;
346   }
347   case Instruction::GetElementPtr: {
348     Address SavedAddr = Addr;
349     uint64_t TmpOffset = Addr.getOffset();
350
351     // Iterate through the GEP folding the constants into offsets where
352     // we can.
353     gep_type_iterator GTI = gep_type_begin(U);
354     for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
355          ++i, ++GTI) {
356       const Value *Op = *i;
357       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
358         const StructLayout *SL = DL.getStructLayout(STy);
359         unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
360         TmpOffset += SL->getElementOffset(Idx);
361       } else {
362         uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
363         for (;;) {
364           if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
365             // Constant-offset addressing.
366             TmpOffset += CI->getSExtValue() * S;
367             break;
368           }
369           if (canFoldAddIntoGEP(U, Op)) {
370             // A compatible add with a constant operand. Fold the constant.
371             ConstantInt *CI =
372                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
373             TmpOffset += CI->getSExtValue() * S;
374             // Iterate on the other operand.
375             Op = cast<AddOperator>(Op)->getOperand(0);
376             continue;
377           }
378           // Unsupported
379           goto unsupported_gep;
380         }
381       }
382     }
383
384     // Try to grab the base operand now.
385     Addr.setOffset(TmpOffset);
386     if (ComputeAddress(U->getOperand(0), Addr))
387       return true;
388
389     // We failed, restore everything and try the other options.
390     Addr = SavedAddr;
391
392   unsupported_gep:
393     break;
394   }
395   case Instruction::Alloca: {
396     const AllocaInst *AI = cast<AllocaInst>(Obj);
397     DenseMap<const AllocaInst *, int>::iterator SI =
398         FuncInfo.StaticAllocaMap.find(AI);
399     if (SI != FuncInfo.StaticAllocaMap.end()) {
400       Addr.setKind(Address::FrameIndexBase);
401       Addr.setFI(SI->second);
402       return true;
403     }
404     break;
405   }
406   }
407
408   // Try to get this in a register if nothing else has worked.
409   if (!Addr.isValid())
410     Addr.setReg(getRegForValue(Obj));
411   return Addr.isValid();
412 }
413
414 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
415   EVT evt = TLI.getValueType(Ty, true);
416
417   // Only handle simple types.
418   if (evt == MVT::Other || !evt.isSimple())
419     return false;
420   VT = evt.getSimpleVT();
421
422   // This is a legal type, but it's not something we handle in fast-isel.
423   if (VT == MVT::f128)
424     return false;
425
426   // Handle all other legal types, i.e. a register that will directly hold this
427   // value.
428   return TLI.isTypeLegal(VT);
429 }
430
431 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
432   if (isTypeLegal(Ty, VT))
433     return true;
434
435   // If this is a type than can be sign or zero-extended to a basic operation
436   // go ahead and accept it now. For stores, this reflects truncation.
437   if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
438     return true;
439
440   return false;
441 }
442
443 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT,
444                                       int64_t ScaleFactor, bool UseUnscaled) {
445   bool needsLowering = false;
446   int64_t Offset = Addr.getOffset();
447   switch (VT.SimpleTy) {
448   default:
449     return false;
450   case MVT::i1:
451   case MVT::i8:
452   case MVT::i16:
453   case MVT::i32:
454   case MVT::i64:
455   case MVT::f32:
456   case MVT::f64:
457     if (!UseUnscaled)
458       // Using scaled, 12-bit, unsigned immediate offsets.
459       needsLowering = ((Offset & 0xfff) != Offset);
460     else
461       // Using unscaled, 9-bit, signed immediate offsets.
462       needsLowering = (Offset > 256 || Offset < -256);
463     break;
464   }
465
466   //If this is a stack pointer and the offset needs to be simplified then put
467   // the alloca address into a register, set the base type back to register and
468   // continue. This should almost never happen.
469   if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
470     unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
471     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
472             ResultReg)
473         .addFrameIndex(Addr.getFI())
474         .addImm(0)
475         .addImm(0);
476     Addr.setKind(Address::RegBase);
477     Addr.setReg(ResultReg);
478   }
479
480   // Since the offset is too large for the load/store instruction get the
481   // reg+offset into a register.
482   if (needsLowering) {
483     uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
484     unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
485                                       UnscaledOffset, MVT::i64);
486     if (ResultReg == 0)
487       return false;
488     Addr.setReg(ResultReg);
489     Addr.setOffset(0);
490   }
491   return true;
492 }
493
494 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
495                                            const MachineInstrBuilder &MIB,
496                                            unsigned Flags, bool UseUnscaled) {
497   int64_t Offset = Addr.getOffset();
498   // Frame base works a bit differently. Handle it separately.
499   if (Addr.getKind() == Address::FrameIndexBase) {
500     int FI = Addr.getFI();
501     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
502     // and alignment should be based on the VT.
503     MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
504         MachinePointerInfo::getFixedStack(FI, Offset), Flags,
505         MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
506     // Now add the rest of the operands.
507     MIB.addFrameIndex(FI).addImm(Offset).addMemOperand(MMO);
508   } else {
509     // Now add the rest of the operands.
510     MIB.addReg(Addr.getReg());
511     MIB.addImm(Offset);
512   }
513 }
514
515 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
516                                bool UseUnscaled) {
517   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
518   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
519   if (!UseUnscaled && Addr.getOffset() < 0)
520     UseUnscaled = true;
521
522   unsigned Opc;
523   const TargetRegisterClass *RC;
524   bool VTIsi1 = false;
525   int64_t ScaleFactor = 0;
526   switch (VT.SimpleTy) {
527   default:
528     return false;
529   case MVT::i1:
530     VTIsi1 = true;
531   // Intentional fall-through.
532   case MVT::i8:
533     Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
534     RC = &AArch64::GPR32RegClass;
535     ScaleFactor = 1;
536     break;
537   case MVT::i16:
538     Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
539     RC = &AArch64::GPR32RegClass;
540     ScaleFactor = 2;
541     break;
542   case MVT::i32:
543     Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
544     RC = &AArch64::GPR32RegClass;
545     ScaleFactor = 4;
546     break;
547   case MVT::i64:
548     Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
549     RC = &AArch64::GPR64RegClass;
550     ScaleFactor = 8;
551     break;
552   case MVT::f32:
553     Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
554     RC = TLI.getRegClassFor(VT);
555     ScaleFactor = 4;
556     break;
557   case MVT::f64:
558     Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
559     RC = TLI.getRegClassFor(VT);
560     ScaleFactor = 8;
561     break;
562   }
563   // Scale the offset.
564   if (!UseUnscaled) {
565     int64_t Offset = Addr.getOffset();
566     if (Offset & (ScaleFactor - 1))
567       // Retry using an unscaled, 9-bit, signed immediate offset.
568       return EmitLoad(VT, ResultReg, Addr, /*UseUnscaled*/ true);
569
570     Addr.setOffset(Offset / ScaleFactor);
571   }
572
573   // Simplify this down to something we can handle.
574   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
575     return false;
576
577   // Create the base instruction, then add the operands.
578   ResultReg = createResultReg(RC);
579   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
580                                     TII.get(Opc), ResultReg);
581   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, UseUnscaled);
582
583   // Loading an i1 requires special handling.
584   if (VTIsi1) {
585     MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
586     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
587     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
588             ANDReg)
589         .addReg(ResultReg)
590         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
591     ResultReg = ANDReg;
592   }
593   return true;
594 }
595
596 bool AArch64FastISel::SelectLoad(const Instruction *I) {
597   MVT VT;
598   // Verify we have a legal type before going any further.  Currently, we handle
599   // simple types that will directly fit in a register (i32/f32/i64/f64) or
600   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
601   if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
602     return false;
603
604   // See if we can handle this address.
605   Address Addr;
606   if (!ComputeAddress(I->getOperand(0), Addr))
607     return false;
608
609   unsigned ResultReg;
610   if (!EmitLoad(VT, ResultReg, Addr))
611     return false;
612
613   UpdateValueMap(I, ResultReg);
614   return true;
615 }
616
617 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
618                                 bool UseUnscaled) {
619   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
620   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
621   if (!UseUnscaled && Addr.getOffset() < 0)
622     UseUnscaled = true;
623
624   unsigned StrOpc;
625   bool VTIsi1 = false;
626   int64_t ScaleFactor = 0;
627   // Using scaled, 12-bit, unsigned immediate offsets.
628   switch (VT.SimpleTy) {
629   default:
630     return false;
631   case MVT::i1:
632     VTIsi1 = true;
633   case MVT::i8:
634     StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
635     ScaleFactor = 1;
636     break;
637   case MVT::i16:
638     StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
639     ScaleFactor = 2;
640     break;
641   case MVT::i32:
642     StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
643     ScaleFactor = 4;
644     break;
645   case MVT::i64:
646     StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
647     ScaleFactor = 8;
648     break;
649   case MVT::f32:
650     StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
651     ScaleFactor = 4;
652     break;
653   case MVT::f64:
654     StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
655     ScaleFactor = 8;
656     break;
657   }
658   // Scale the offset.
659   if (!UseUnscaled) {
660     int64_t Offset = Addr.getOffset();
661     if (Offset & (ScaleFactor - 1))
662       // Retry using an unscaled, 9-bit, signed immediate offset.
663       return EmitStore(VT, SrcReg, Addr, /*UseUnscaled*/ true);
664
665     Addr.setOffset(Offset / ScaleFactor);
666   }
667
668   // Simplify this down to something we can handle.
669   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
670     return false;
671
672   // Storing an i1 requires special handling.
673   if (VTIsi1) {
674     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
675     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
676     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
677             ANDReg)
678         .addReg(SrcReg)
679         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
680     SrcReg = ANDReg;
681   }
682   // Create the base instruction, then add the operands.
683   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
684                                     TII.get(StrOpc)).addReg(SrcReg);
685   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, UseUnscaled);
686   return true;
687 }
688
689 bool AArch64FastISel::SelectStore(const Instruction *I) {
690   MVT VT;
691   Value *Op0 = I->getOperand(0);
692   // Verify we have a legal type before going any further.  Currently, we handle
693   // simple types that will directly fit in a register (i32/f32/i64/f64) or
694   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
695   if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
696       cast<StoreInst>(I)->isAtomic())
697     return false;
698
699   // Get the value to be stored into a register.
700   unsigned SrcReg = getRegForValue(Op0);
701   if (SrcReg == 0)
702     return false;
703
704   // See if we can handle this address.
705   Address Addr;
706   if (!ComputeAddress(I->getOperand(1), Addr))
707     return false;
708
709   if (!EmitStore(VT, SrcReg, Addr))
710     return false;
711   return true;
712 }
713
714 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
715   switch (Pred) {
716   case CmpInst::FCMP_ONE:
717   case CmpInst::FCMP_UEQ:
718   default:
719     // AL is our "false" for now. The other two need more compares.
720     return AArch64CC::AL;
721   case CmpInst::ICMP_EQ:
722   case CmpInst::FCMP_OEQ:
723     return AArch64CC::EQ;
724   case CmpInst::ICMP_SGT:
725   case CmpInst::FCMP_OGT:
726     return AArch64CC::GT;
727   case CmpInst::ICMP_SGE:
728   case CmpInst::FCMP_OGE:
729     return AArch64CC::GE;
730   case CmpInst::ICMP_UGT:
731   case CmpInst::FCMP_UGT:
732     return AArch64CC::HI;
733   case CmpInst::FCMP_OLT:
734     return AArch64CC::MI;
735   case CmpInst::ICMP_ULE:
736   case CmpInst::FCMP_OLE:
737     return AArch64CC::LS;
738   case CmpInst::FCMP_ORD:
739     return AArch64CC::VC;
740   case CmpInst::FCMP_UNO:
741     return AArch64CC::VS;
742   case CmpInst::FCMP_UGE:
743     return AArch64CC::PL;
744   case CmpInst::ICMP_SLT:
745   case CmpInst::FCMP_ULT:
746     return AArch64CC::LT;
747   case CmpInst::ICMP_SLE:
748   case CmpInst::FCMP_ULE:
749     return AArch64CC::LE;
750   case CmpInst::FCMP_UNE:
751   case CmpInst::ICMP_NE:
752     return AArch64CC::NE;
753   case CmpInst::ICMP_UGE:
754     return AArch64CC::HS;
755   case CmpInst::ICMP_ULT:
756     return AArch64CC::LO;
757   }
758 }
759
760 bool AArch64FastISel::SelectBranch(const Instruction *I) {
761   const BranchInst *BI = cast<BranchInst>(I);
762   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
763   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
764
765   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
766     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
767       // We may not handle every CC for now.
768       AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
769       if (CC == AArch64CC::AL)
770         return false;
771
772       // Emit the cmp.
773       if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
774         return false;
775
776       // Emit the branch.
777       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
778           .addImm(CC)
779           .addMBB(TBB);
780       FuncInfo.MBB->addSuccessor(TBB);
781
782       FastEmitBranch(FBB, DbgLoc);
783       return true;
784     }
785   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
786     MVT SrcVT;
787     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
788         (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
789       unsigned CondReg = getRegForValue(TI->getOperand(0));
790       if (CondReg == 0)
791         return false;
792
793       // Issue an extract_subreg to get the lower 32-bits.
794       if (SrcVT == MVT::i64)
795         CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
796                                              AArch64::sub_32);
797
798       MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
799       unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
800       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
801               TII.get(AArch64::ANDWri), ANDReg)
802           .addReg(CondReg)
803           .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
804       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
805               TII.get(AArch64::SUBSWri))
806           .addReg(ANDReg)
807           .addReg(ANDReg)
808           .addImm(0)
809           .addImm(0);
810
811       unsigned CC = AArch64CC::NE;
812       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
813         std::swap(TBB, FBB);
814         CC = AArch64CC::EQ;
815       }
816       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
817           .addImm(CC)
818           .addMBB(TBB);
819       FuncInfo.MBB->addSuccessor(TBB);
820       FastEmitBranch(FBB, DbgLoc);
821       return true;
822     }
823   } else if (const ConstantInt *CI =
824                  dyn_cast<ConstantInt>(BI->getCondition())) {
825     uint64_t Imm = CI->getZExtValue();
826     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
827     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
828         .addMBB(Target);
829     FuncInfo.MBB->addSuccessor(Target);
830     return true;
831   }
832
833   unsigned CondReg = getRegForValue(BI->getCondition());
834   if (CondReg == 0)
835     return false;
836
837   // We've been divorced from our compare!  Our block was split, and
838   // now our compare lives in a predecessor block.  We musn't
839   // re-compare here, as the children of the compare aren't guaranteed
840   // live across the block boundary (we *could* check for this).
841   // Regardless, the compare has been done in the predecessor block,
842   // and it left a value for us in a virtual register.  Ergo, we test
843   // the one-bit value left in the virtual register.
844   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
845           AArch64::WZR)
846       .addReg(CondReg)
847       .addImm(0)
848       .addImm(0);
849
850   unsigned CC = AArch64CC::NE;
851   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
852     std::swap(TBB, FBB);
853     CC = AArch64CC::EQ;
854   }
855
856   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
857       .addImm(CC)
858       .addMBB(TBB);
859   FuncInfo.MBB->addSuccessor(TBB);
860   FastEmitBranch(FBB, DbgLoc);
861   return true;
862 }
863
864 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
865   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
866   unsigned AddrReg = getRegForValue(BI->getOperand(0));
867   if (AddrReg == 0)
868     return false;
869
870   // Emit the indirect branch.
871   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
872       .addReg(AddrReg);
873
874   // Make sure the CFG is up-to-date.
875   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
876     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
877
878   return true;
879 }
880
881 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
882   Type *Ty = Src1Value->getType();
883   EVT SrcEVT = TLI.getValueType(Ty, true);
884   if (!SrcEVT.isSimple())
885     return false;
886   MVT SrcVT = SrcEVT.getSimpleVT();
887
888   // Check to see if the 2nd operand is a constant that we can encode directly
889   // in the compare.
890   uint64_t Imm;
891   bool UseImm = false;
892   bool isNegativeImm = false;
893   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
894     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
895         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
896       const APInt &CIVal = ConstInt->getValue();
897
898       Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
899       if (CIVal.isNegative()) {
900         isNegativeImm = true;
901         Imm = -Imm;
902       }
903       // FIXME: We can handle more immediates using shifts.
904       UseImm = ((Imm & 0xfff) == Imm);
905     }
906   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
907     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
908       if (ConstFP->isZero() && !ConstFP->isNegative())
909         UseImm = true;
910   }
911
912   unsigned ZReg;
913   unsigned CmpOpc;
914   bool isICmp = true;
915   bool needsExt = false;
916   switch (SrcVT.SimpleTy) {
917   default:
918     return false;
919   case MVT::i1:
920   case MVT::i8:
921   case MVT::i16:
922     needsExt = true;
923   // Intentional fall-through.
924   case MVT::i32:
925     ZReg = AArch64::WZR;
926     if (UseImm)
927       CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
928     else
929       CmpOpc = AArch64::SUBSWrr;
930     break;
931   case MVT::i64:
932     ZReg = AArch64::XZR;
933     if (UseImm)
934       CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
935     else
936       CmpOpc = AArch64::SUBSXrr;
937     break;
938   case MVT::f32:
939     isICmp = false;
940     CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
941     break;
942   case MVT::f64:
943     isICmp = false;
944     CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
945     break;
946   }
947
948   unsigned SrcReg1 = getRegForValue(Src1Value);
949   if (SrcReg1 == 0)
950     return false;
951
952   unsigned SrcReg2;
953   if (!UseImm) {
954     SrcReg2 = getRegForValue(Src2Value);
955     if (SrcReg2 == 0)
956       return false;
957   }
958
959   // We have i1, i8, or i16, we need to either zero extend or sign extend.
960   if (needsExt) {
961     SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
962     if (SrcReg1 == 0)
963       return false;
964     if (!UseImm) {
965       SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
966       if (SrcReg2 == 0)
967         return false;
968     }
969   }
970
971   if (isICmp) {
972     if (UseImm)
973       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
974           .addReg(ZReg)
975           .addReg(SrcReg1)
976           .addImm(Imm)
977           .addImm(0);
978     else
979       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
980           .addReg(ZReg)
981           .addReg(SrcReg1)
982           .addReg(SrcReg2);
983   } else {
984     if (UseImm)
985       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
986           .addReg(SrcReg1);
987     else
988       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
989           .addReg(SrcReg1)
990           .addReg(SrcReg2);
991   }
992   return true;
993 }
994
995 bool AArch64FastISel::SelectCmp(const Instruction *I) {
996   const CmpInst *CI = cast<CmpInst>(I);
997
998   // We may not handle every CC for now.
999   AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
1000   if (CC == AArch64CC::AL)
1001     return false;
1002
1003   // Emit the cmp.
1004   if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1005     return false;
1006
1007   // Now set a register based on the comparison.
1008   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1009   unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1010   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1011           ResultReg)
1012       .addReg(AArch64::WZR)
1013       .addReg(AArch64::WZR)
1014       .addImm(invertedCC);
1015
1016   UpdateValueMap(I, ResultReg);
1017   return true;
1018 }
1019
1020 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1021   const SelectInst *SI = cast<SelectInst>(I);
1022
1023   EVT DestEVT = TLI.getValueType(SI->getType(), true);
1024   if (!DestEVT.isSimple())
1025     return false;
1026
1027   MVT DestVT = DestEVT.getSimpleVT();
1028   if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1029       DestVT != MVT::f64)
1030     return false;
1031
1032   unsigned CondReg = getRegForValue(SI->getCondition());
1033   if (CondReg == 0)
1034     return false;
1035   unsigned TrueReg = getRegForValue(SI->getTrueValue());
1036   if (TrueReg == 0)
1037     return false;
1038   unsigned FalseReg = getRegForValue(SI->getFalseValue());
1039   if (FalseReg == 0)
1040     return false;
1041
1042
1043   MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1044   unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1045   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1046           ANDReg)
1047       .addReg(CondReg)
1048       .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1049
1050   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri))
1051       .addReg(ANDReg)
1052       .addReg(ANDReg)
1053       .addImm(0)
1054       .addImm(0);
1055
1056   unsigned SelectOpc;
1057   switch (DestVT.SimpleTy) {
1058   default:
1059     return false;
1060   case MVT::i32:
1061     SelectOpc = AArch64::CSELWr;
1062     break;
1063   case MVT::i64:
1064     SelectOpc = AArch64::CSELXr;
1065     break;
1066   case MVT::f32:
1067     SelectOpc = AArch64::FCSELSrrr;
1068     break;
1069   case MVT::f64:
1070     SelectOpc = AArch64::FCSELDrrr;
1071     break;
1072   }
1073
1074   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1075   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1076           ResultReg)
1077       .addReg(TrueReg)
1078       .addReg(FalseReg)
1079       .addImm(AArch64CC::NE);
1080
1081   UpdateValueMap(I, ResultReg);
1082   return true;
1083 }
1084
1085 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1086   Value *V = I->getOperand(0);
1087   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1088     return false;
1089
1090   unsigned Op = getRegForValue(V);
1091   if (Op == 0)
1092     return false;
1093
1094   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1095   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1096           ResultReg).addReg(Op);
1097   UpdateValueMap(I, ResultReg);
1098   return true;
1099 }
1100
1101 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1102   Value *V = I->getOperand(0);
1103   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1104     return false;
1105
1106   unsigned Op = getRegForValue(V);
1107   if (Op == 0)
1108     return false;
1109
1110   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1111   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1112           ResultReg).addReg(Op);
1113   UpdateValueMap(I, ResultReg);
1114   return true;
1115 }
1116
1117 // FPToUI and FPToSI
1118 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1119   MVT DestVT;
1120   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1121     return false;
1122
1123   unsigned SrcReg = getRegForValue(I->getOperand(0));
1124   if (SrcReg == 0)
1125     return false;
1126
1127   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1128   if (SrcVT == MVT::f128)
1129     return false;
1130
1131   unsigned Opc;
1132   if (SrcVT == MVT::f64) {
1133     if (Signed)
1134       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1135     else
1136       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1137   } else {
1138     if (Signed)
1139       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1140     else
1141       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1142   }
1143   unsigned ResultReg = createResultReg(
1144       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1145   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1146       .addReg(SrcReg);
1147   UpdateValueMap(I, ResultReg);
1148   return true;
1149 }
1150
1151 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1152   MVT DestVT;
1153   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1154     return false;
1155   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1156           "Unexpected value type.");
1157
1158   unsigned SrcReg = getRegForValue(I->getOperand(0));
1159   if (SrcReg == 0)
1160     return false;
1161
1162   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1163
1164   // Handle sign-extension.
1165   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1166     SrcReg =
1167         EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1168     if (SrcReg == 0)
1169       return false;
1170   }
1171
1172   MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1173                                                   : &AArch64::GPR32RegClass);
1174
1175   unsigned Opc;
1176   if (SrcVT == MVT::i64) {
1177     if (Signed)
1178       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1179     else
1180       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1181   } else {
1182     if (Signed)
1183       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1184     else
1185       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1186   }
1187
1188   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1189   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1190       .addReg(SrcReg);
1191   UpdateValueMap(I, ResultReg);
1192   return true;
1193 }
1194
1195 bool AArch64FastISel::ProcessCallArgs(CallLoweringInfo &CLI,
1196                                       SmallVectorImpl<MVT> &OutVTs,
1197                                       unsigned &NumBytes) {
1198   CallingConv::ID CC = CLI.CallConv;
1199   SmallVector<CCValAssign, 16> ArgLocs;
1200   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1201   CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
1202
1203   // Get a count of how many bytes are to be pushed on the stack.
1204   NumBytes = CCInfo.getNextStackOffset();
1205
1206   // Issue CALLSEQ_START
1207   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1208   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1209     .addImm(NumBytes);
1210
1211   // Process the args.
1212   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1213     CCValAssign &VA = ArgLocs[i];
1214     const Value *ArgVal = CLI.OutVals[VA.getValNo()];
1215     MVT ArgVT = OutVTs[VA.getValNo()];
1216
1217     unsigned ArgReg = getRegForValue(ArgVal);
1218     if (!ArgReg)
1219       return false;
1220
1221     // Handle arg promotion: SExt, ZExt, AExt.
1222     switch (VA.getLocInfo()) {
1223     case CCValAssign::Full:
1224       break;
1225     case CCValAssign::SExt: {
1226       MVT DestVT = VA.getLocVT();
1227       MVT SrcVT = ArgVT;
1228       ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1229       if (!ArgReg)
1230         return false;
1231       break;
1232     }
1233     case CCValAssign::AExt:
1234     // Intentional fall-through.
1235     case CCValAssign::ZExt: {
1236       MVT DestVT = VA.getLocVT();
1237       MVT SrcVT = ArgVT;
1238       ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1239       if (!ArgReg)
1240         return false;
1241       break;
1242     }
1243     default:
1244       llvm_unreachable("Unknown arg promotion!");
1245     }
1246
1247     // Now copy/store arg to correct locations.
1248     if (VA.isRegLoc() && !VA.needsCustom()) {
1249       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1250               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1251       CLI.OutRegs.push_back(VA.getLocReg());
1252     } else if (VA.needsCustom()) {
1253       // FIXME: Handle custom args.
1254       return false;
1255     } else {
1256       assert(VA.isMemLoc() && "Assuming store on stack.");
1257
1258       // Need to store on the stack.
1259       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1260
1261       unsigned BEAlign = 0;
1262       if (ArgSize < 8 && !Subtarget->isLittleEndian())
1263         BEAlign = 8 - ArgSize;
1264
1265       Address Addr;
1266       Addr.setKind(Address::RegBase);
1267       Addr.setReg(AArch64::SP);
1268       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1269
1270       if (!EmitStore(ArgVT, ArgReg, Addr))
1271         return false;
1272     }
1273   }
1274   return true;
1275 }
1276
1277 bool AArch64FastISel::FinishCall(CallLoweringInfo &CLI, MVT RetVT,
1278                                  unsigned NumBytes) {
1279   CallingConv::ID CC = CLI.CallConv;
1280
1281   // Issue CALLSEQ_END
1282   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1283   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1284     .addImm(NumBytes).addImm(0);
1285
1286   // Now the return value.
1287   if (RetVT != MVT::isVoid) {
1288     SmallVector<CCValAssign, 16> RVLocs;
1289     CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1290     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1291
1292     // Only handle a single return value.
1293     if (RVLocs.size() != 1)
1294       return false;
1295
1296     // Copy all of the result registers out of their specified physreg.
1297     MVT CopyVT = RVLocs[0].getValVT();
1298     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1299     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1300             TII.get(TargetOpcode::COPY), ResultReg)
1301       .addReg(RVLocs[0].getLocReg());
1302     CLI.InRegs.push_back(RVLocs[0].getLocReg());
1303
1304     CLI.ResultReg = ResultReg;
1305     CLI.NumResultRegs = 1;
1306   }
1307
1308   return true;
1309 }
1310
1311 bool AArch64FastISel::FastLowerCall(CallLoweringInfo &CLI) {
1312   CallingConv::ID CC  = CLI.CallConv;
1313   bool IsVarArg       = CLI.IsVarArg;
1314   const Value *Callee = CLI.Callee;
1315   const char *SymName = CLI.SymName;
1316
1317   // Only handle global variable Callees.
1318   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1319   if (!GV)
1320     return false;
1321
1322   // Let SDISel handle vararg functions.
1323   if (IsVarArg)
1324     return false;
1325
1326   // FIXME: Only handle *simple* calls for now.
1327   MVT RetVT;
1328   if (CLI.RetTy->isVoidTy())
1329     RetVT = MVT::isVoid;
1330   else if (!isTypeLegal(CLI.RetTy, RetVT))
1331     return false;
1332
1333   for (auto Flag : CLI.OutFlags)
1334     if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1335       return false;
1336
1337   // Set up the argument vectors.
1338   SmallVector<MVT, 16> OutVTs;
1339   OutVTs.reserve(CLI.OutVals.size());
1340
1341   for (auto *Val : CLI.OutVals) {
1342     MVT VT;
1343     if (!isTypeLegal(Val->getType(), VT) &&
1344         !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1345       return false;
1346
1347     // We don't handle vector parameters yet.
1348     if (VT.isVector() || VT.getSizeInBits() > 64)
1349       return false;
1350
1351     OutVTs.push_back(VT);
1352   }
1353
1354   // Handle the arguments now that we've gotten them.
1355   unsigned NumBytes;
1356   if (!ProcessCallArgs(CLI, OutVTs, NumBytes))
1357     return false;
1358
1359   // Issue the call.
1360   MachineInstrBuilder MIB;
1361   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BL));
1362   CLI.Call = MIB;
1363   if (!SymName)
1364     MIB.addGlobalAddress(GV, 0, 0);
1365   else
1366     MIB.addExternalSymbol(SymName, 0);
1367
1368   // Add implicit physical register uses to the call.
1369   for (auto Reg : CLI.OutRegs)
1370     MIB.addReg(Reg, RegState::Implicit);
1371
1372   // Add a register mask with the call-preserved registers.
1373   // Proper defs for return values will be added by setPhysRegsDeadExcept().
1374   MIB.addRegMask(TRI.getCallPreservedMask(CC));
1375
1376   // Finish off the call including any return values.
1377   return FinishCall(CLI, RetVT, NumBytes);
1378 }
1379
1380 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1381   if (Alignment)
1382     return Len / Alignment <= 4;
1383   else
1384     return Len < 32;
1385 }
1386
1387 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1388                                          uint64_t Len, unsigned Alignment) {
1389   // Make sure we don't bloat code by inlining very large memcpy's.
1390   if (!IsMemCpySmall(Len, Alignment))
1391     return false;
1392
1393   int64_t UnscaledOffset = 0;
1394   Address OrigDest = Dest;
1395   Address OrigSrc = Src;
1396
1397   while (Len) {
1398     MVT VT;
1399     if (!Alignment || Alignment >= 8) {
1400       if (Len >= 8)
1401         VT = MVT::i64;
1402       else if (Len >= 4)
1403         VT = MVT::i32;
1404       else if (Len >= 2)
1405         VT = MVT::i16;
1406       else {
1407         VT = MVT::i8;
1408       }
1409     } else {
1410       // Bound based on alignment.
1411       if (Len >= 4 && Alignment == 4)
1412         VT = MVT::i32;
1413       else if (Len >= 2 && Alignment == 2)
1414         VT = MVT::i16;
1415       else {
1416         VT = MVT::i8;
1417       }
1418     }
1419
1420     bool RV;
1421     unsigned ResultReg;
1422     RV = EmitLoad(VT, ResultReg, Src);
1423     if (!RV)
1424       return false;
1425
1426     RV = EmitStore(VT, ResultReg, Dest);
1427     if (!RV)
1428       return false;
1429
1430     int64_t Size = VT.getSizeInBits() / 8;
1431     Len -= Size;
1432     UnscaledOffset += Size;
1433
1434     // We need to recompute the unscaled offset for each iteration.
1435     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1436     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1437   }
1438
1439   return true;
1440 }
1441
1442 bool AArch64FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
1443   // FIXME: Handle more intrinsics.
1444   switch (II->getIntrinsicID()) {
1445   default: return false;
1446   case Intrinsic::frameaddress: {
1447     MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1448     MFI->setFrameAddressIsTaken(true);
1449
1450     const AArch64RegisterInfo *RegInfo =
1451       static_cast<const AArch64RegisterInfo *>(TM.getRegisterInfo());
1452     unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
1453     unsigned SrcReg = FramePtr;
1454
1455     // Recursively load frame address
1456     // ldr x0, [fp]
1457     // ldr x0, [x0]
1458     // ldr x0, [x0]
1459     // ...
1460     unsigned DestReg;
1461     unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
1462     while (Depth--) {
1463       DestReg = createResultReg(&AArch64::GPR64RegClass);
1464       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1465               TII.get(AArch64::LDRXui), DestReg)
1466         .addReg(SrcReg).addImm(0);
1467       SrcReg = DestReg;
1468     }
1469
1470     UpdateValueMap(II, SrcReg);
1471     return true;
1472   }
1473   case Intrinsic::memcpy:
1474   case Intrinsic::memmove: {
1475     const auto *MTI = cast<MemTransferInst>(II);
1476     // Don't handle volatile.
1477     if (MTI->isVolatile())
1478       return false;
1479
1480     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
1481     // we would emit dead code because we don't currently handle memmoves.
1482     bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
1483     if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
1484       // Small memcpy's are common enough that we want to do them without a call
1485       // if possible.
1486       uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
1487       unsigned Alignment = MTI->getAlignment();
1488       if (IsMemCpySmall(Len, Alignment)) {
1489         Address Dest, Src;
1490         if (!ComputeAddress(MTI->getRawDest(), Dest) ||
1491             !ComputeAddress(MTI->getRawSource(), Src))
1492           return false;
1493         if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1494           return true;
1495       }
1496     }
1497
1498     if (!MTI->getLength()->getType()->isIntegerTy(64))
1499       return false;
1500
1501     if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
1502       // Fast instruction selection doesn't support the special
1503       // address spaces.
1504       return false;
1505
1506     const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
1507     return LowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
1508   }
1509   case Intrinsic::memset: {
1510     const MemSetInst *MSI = cast<MemSetInst>(II);
1511     // Don't handle volatile.
1512     if (MSI->isVolatile())
1513       return false;
1514
1515     if (!MSI->getLength()->getType()->isIntegerTy(64))
1516       return false;
1517
1518     if (MSI->getDestAddressSpace() > 255)
1519       // Fast instruction selection doesn't support the special
1520       // address spaces.
1521       return false;
1522
1523     return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
1524   }
1525   case Intrinsic::trap: {
1526     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1527         .addImm(1);
1528     return true;
1529   }
1530   }
1531   return false;
1532 }
1533
1534 bool AArch64FastISel::SelectRet(const Instruction *I) {
1535   const ReturnInst *Ret = cast<ReturnInst>(I);
1536   const Function &F = *I->getParent()->getParent();
1537
1538   if (!FuncInfo.CanLowerReturn)
1539     return false;
1540
1541   if (F.isVarArg())
1542     return false;
1543
1544   // Build a list of return value registers.
1545   SmallVector<unsigned, 4> RetRegs;
1546
1547   if (Ret->getNumOperands() > 0) {
1548     CallingConv::ID CC = F.getCallingConv();
1549     SmallVector<ISD::OutputArg, 4> Outs;
1550     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1551
1552     // Analyze operands of the call, assigning locations to each operand.
1553     SmallVector<CCValAssign, 16> ValLocs;
1554     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1555                    I->getContext());
1556     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
1557                                                      : RetCC_AArch64_AAPCS;
1558     CCInfo.AnalyzeReturn(Outs, RetCC);
1559
1560     // Only handle a single return value for now.
1561     if (ValLocs.size() != 1)
1562       return false;
1563
1564     CCValAssign &VA = ValLocs[0];
1565     const Value *RV = Ret->getOperand(0);
1566
1567     // Don't bother handling odd stuff for now.
1568     if (VA.getLocInfo() != CCValAssign::Full)
1569       return false;
1570     // Only handle register returns for now.
1571     if (!VA.isRegLoc())
1572       return false;
1573     unsigned Reg = getRegForValue(RV);
1574     if (Reg == 0)
1575       return false;
1576
1577     unsigned SrcReg = Reg + VA.getValNo();
1578     unsigned DestReg = VA.getLocReg();
1579     // Avoid a cross-class copy. This is very unlikely.
1580     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1581       return false;
1582
1583     EVT RVEVT = TLI.getValueType(RV->getType());
1584     if (!RVEVT.isSimple())
1585       return false;
1586
1587     // Vectors (of > 1 lane) in big endian need tricky handling.
1588     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
1589       return false;
1590
1591     MVT RVVT = RVEVT.getSimpleVT();
1592     if (RVVT == MVT::f128)
1593       return false;
1594     MVT DestVT = VA.getValVT();
1595     // Special handling for extended integers.
1596     if (RVVT != DestVT) {
1597       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1598         return false;
1599
1600       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1601         return false;
1602
1603       bool isZExt = Outs[0].Flags.isZExt();
1604       SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
1605       if (SrcReg == 0)
1606         return false;
1607     }
1608
1609     // Make the copy.
1610     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1611             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1612
1613     // Add register to return instruction.
1614     RetRegs.push_back(VA.getLocReg());
1615   }
1616
1617   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1618                                     TII.get(AArch64::RET_ReallyLR));
1619   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1620     MIB.addReg(RetRegs[i], RegState::Implicit);
1621   return true;
1622 }
1623
1624 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
1625   Type *DestTy = I->getType();
1626   Value *Op = I->getOperand(0);
1627   Type *SrcTy = Op->getType();
1628
1629   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1630   EVT DestEVT = TLI.getValueType(DestTy, true);
1631   if (!SrcEVT.isSimple())
1632     return false;
1633   if (!DestEVT.isSimple())
1634     return false;
1635
1636   MVT SrcVT = SrcEVT.getSimpleVT();
1637   MVT DestVT = DestEVT.getSimpleVT();
1638
1639   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1640       SrcVT != MVT::i8)
1641     return false;
1642   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
1643       DestVT != MVT::i1)
1644     return false;
1645
1646   unsigned SrcReg = getRegForValue(Op);
1647   if (!SrcReg)
1648     return false;
1649
1650   // If we're truncating from i64 to a smaller non-legal type then generate an
1651   // AND.  Otherwise, we know the high bits are undefined and a truncate doesn't
1652   // generate any code.
1653   if (SrcVT == MVT::i64) {
1654     uint64_t Mask = 0;
1655     switch (DestVT.SimpleTy) {
1656     default:
1657       // Trunc i64 to i32 is handled by the target-independent fast-isel.
1658       return false;
1659     case MVT::i1:
1660       Mask = 0x1;
1661       break;
1662     case MVT::i8:
1663       Mask = 0xff;
1664       break;
1665     case MVT::i16:
1666       Mask = 0xffff;
1667       break;
1668     }
1669     // Issue an extract_subreg to get the lower 32-bits.
1670     unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
1671                                                 AArch64::sub_32);
1672     MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
1673     // Create the AND instruction which performs the actual truncation.
1674     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1675     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1676             ANDReg)
1677         .addReg(Reg32)
1678         .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
1679     SrcReg = ANDReg;
1680   }
1681
1682   UpdateValueMap(I, SrcReg);
1683   return true;
1684 }
1685
1686 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
1687   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
1688           DestVT == MVT::i64) &&
1689          "Unexpected value type.");
1690   // Handle i8 and i16 as i32.
1691   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1692     DestVT = MVT::i32;
1693
1694   if (isZExt) {
1695     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
1696     unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
1697     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1698             ResultReg)
1699         .addReg(SrcReg)
1700         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1701
1702     if (DestVT == MVT::i64) {
1703       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
1704       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
1705       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1706       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1707               TII.get(AArch64::SUBREG_TO_REG), Reg64)
1708           .addImm(0)
1709           .addReg(ResultReg)
1710           .addImm(AArch64::sub_32);
1711       ResultReg = Reg64;
1712     }
1713     return ResultReg;
1714   } else {
1715     if (DestVT == MVT::i64) {
1716       // FIXME: We're SExt i1 to i64.
1717       return 0;
1718     }
1719     unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1720     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
1721             ResultReg)
1722         .addReg(SrcReg)
1723         .addImm(0)
1724         .addImm(0);
1725     return ResultReg;
1726   }
1727 }
1728
1729 unsigned AArch64FastISel::Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
1730                                       uint64_t Shift) {
1731   unsigned Opc, ImmR, ImmS;
1732   switch (RetVT.SimpleTy) {
1733   default: return 0;
1734   case MVT::i8:
1735   case MVT::i16:
1736   case MVT::i32:
1737     RetVT = MVT::i32;
1738     Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 31 - Shift; break;
1739   case MVT::i64:
1740     Opc = AArch64::UBFMXri; ImmR = -Shift % 64; ImmS = 63 - Shift; break;
1741   }
1742
1743   return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, ImmR,
1744                           ImmS);
1745 }
1746
1747 unsigned AArch64FastISel::Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
1748                                       uint64_t Shift) {
1749   unsigned Opc, ImmS;
1750   switch (RetVT.SimpleTy) {
1751   default: return 0;
1752   case MVT::i8:
1753   case MVT::i16:
1754   case MVT::i32:
1755     RetVT = MVT::i32;
1756     Opc = AArch64::UBFMWri; ImmS = 31; break;
1757   case MVT::i64:
1758     Opc = AArch64::UBFMXri; ImmS = 63; break;
1759   }
1760
1761   return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
1762                           ImmS);
1763 }
1764
1765 unsigned AArch64FastISel::Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
1766                                       uint64_t Shift) {
1767   unsigned Opc, ImmS;
1768   switch (RetVT.SimpleTy) {
1769   default: return 0;
1770   case MVT::i8:
1771   case MVT::i16:
1772   case MVT::i32:
1773     RetVT = MVT::i32;
1774     Opc = AArch64::SBFMWri; ImmS = 31; break;
1775   case MVT::i64:
1776     Opc = AArch64::SBFMXri; ImmS = 63; break;
1777   }
1778
1779   return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
1780                           ImmS);
1781 }
1782
1783 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1784                                      bool isZExt) {
1785   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
1786
1787   // FastISel does not have plumbing to deal with extensions where the SrcVT or
1788   // DestVT are odd things, so test to make sure that they are both types we can
1789   // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
1790   // bail out to SelectionDAG.
1791   if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
1792        (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
1793       ((SrcVT !=  MVT::i1) && (SrcVT !=  MVT::i8) &&
1794        (SrcVT !=  MVT::i16) && (SrcVT !=  MVT::i32)))
1795     return 0;
1796
1797   unsigned Opc;
1798   unsigned Imm = 0;
1799
1800   switch (SrcVT.SimpleTy) {
1801   default:
1802     return 0;
1803   case MVT::i1:
1804     return Emiti1Ext(SrcReg, DestVT, isZExt);
1805   case MVT::i8:
1806     if (DestVT == MVT::i64)
1807       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1808     else
1809       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1810     Imm = 7;
1811     break;
1812   case MVT::i16:
1813     if (DestVT == MVT::i64)
1814       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1815     else
1816       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1817     Imm = 15;
1818     break;
1819   case MVT::i32:
1820     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
1821     Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1822     Imm = 31;
1823     break;
1824   }
1825
1826   // Handle i8 and i16 as i32.
1827   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1828     DestVT = MVT::i32;
1829   else if (DestVT == MVT::i64) {
1830     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1831     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1832             TII.get(AArch64::SUBREG_TO_REG), Src64)
1833         .addImm(0)
1834         .addReg(SrcReg)
1835         .addImm(AArch64::sub_32);
1836     SrcReg = Src64;
1837   }
1838
1839   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1840   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1841       .addReg(SrcReg)
1842       .addImm(0)
1843       .addImm(Imm);
1844
1845   return ResultReg;
1846 }
1847
1848 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
1849   // On ARM, in general, integer casts don't involve legal types; this code
1850   // handles promotable integers.  The high bits for a type smaller than
1851   // the register size are assumed to be undefined.
1852   Type *DestTy = I->getType();
1853   Value *Src = I->getOperand(0);
1854   Type *SrcTy = Src->getType();
1855
1856   bool isZExt = isa<ZExtInst>(I);
1857   unsigned SrcReg = getRegForValue(Src);
1858   if (!SrcReg)
1859     return false;
1860
1861   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1862   EVT DestEVT = TLI.getValueType(DestTy, true);
1863   if (!SrcEVT.isSimple())
1864     return false;
1865   if (!DestEVT.isSimple())
1866     return false;
1867
1868   MVT SrcVT = SrcEVT.getSimpleVT();
1869   MVT DestVT = DestEVT.getSimpleVT();
1870   unsigned ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
1871   if (ResultReg == 0)
1872     return false;
1873   UpdateValueMap(I, ResultReg);
1874   return true;
1875 }
1876
1877 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
1878   EVT DestEVT = TLI.getValueType(I->getType(), true);
1879   if (!DestEVT.isSimple())
1880     return false;
1881
1882   MVT DestVT = DestEVT.getSimpleVT();
1883   if (DestVT != MVT::i64 && DestVT != MVT::i32)
1884     return false;
1885
1886   unsigned DivOpc;
1887   bool is64bit = (DestVT == MVT::i64);
1888   switch (ISDOpcode) {
1889   default:
1890     return false;
1891   case ISD::SREM:
1892     DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
1893     break;
1894   case ISD::UREM:
1895     DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
1896     break;
1897   }
1898   unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
1899   unsigned Src0Reg = getRegForValue(I->getOperand(0));
1900   if (!Src0Reg)
1901     return false;
1902
1903   unsigned Src1Reg = getRegForValue(I->getOperand(1));
1904   if (!Src1Reg)
1905     return false;
1906
1907   unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
1908   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
1909       .addReg(Src0Reg)
1910       .addReg(Src1Reg);
1911   // The remainder is computed as numerator - (quotient * denominator) using the
1912   // MSUB instruction.
1913   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1914   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
1915       .addReg(QuotReg)
1916       .addReg(Src1Reg)
1917       .addReg(Src0Reg);
1918   UpdateValueMap(I, ResultReg);
1919   return true;
1920 }
1921
1922 bool AArch64FastISel::SelectMul(const Instruction *I) {
1923   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1924   if (!SrcEVT.isSimple())
1925     return false;
1926   MVT SrcVT = SrcEVT.getSimpleVT();
1927
1928   // Must be simple value type.  Don't handle vectors.
1929   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1930       SrcVT != MVT::i8)
1931     return false;
1932
1933   unsigned Opc;
1934   unsigned ZReg;
1935   switch (SrcVT.SimpleTy) {
1936   default:
1937     return false;
1938   case MVT::i8:
1939   case MVT::i16:
1940   case MVT::i32:
1941     ZReg = AArch64::WZR;
1942     Opc = AArch64::MADDWrrr;
1943     SrcVT = MVT::i32;
1944     break;
1945   case MVT::i64:
1946     ZReg = AArch64::XZR;
1947     Opc = AArch64::MADDXrrr;
1948     break;
1949   }
1950
1951   unsigned Src0Reg = getRegForValue(I->getOperand(0));
1952   if (!Src0Reg)
1953     return false;
1954
1955   unsigned Src1Reg = getRegForValue(I->getOperand(1));
1956   if (!Src1Reg)
1957     return false;
1958
1959   // Create the base instruction, then add the operands.
1960   unsigned ResultReg = createResultReg(TLI.getRegClassFor(SrcVT));
1961   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1962       .addReg(Src0Reg)
1963       .addReg(Src1Reg)
1964       .addReg(ZReg);
1965   UpdateValueMap(I, ResultReg);
1966   return true;
1967 }
1968
1969 bool AArch64FastISel::SelectShift(const Instruction *I, bool IsLeftShift,
1970                                   bool IsArithmetic) {
1971   EVT RetEVT = TLI.getValueType(I->getType(), true);
1972   if (!RetEVT.isSimple())
1973     return false;
1974   MVT RetVT = RetEVT.getSimpleVT();
1975
1976   if (!isa<ConstantInt>(I->getOperand(1)))
1977     return false;
1978
1979   unsigned Op0Reg = getRegForValue(I->getOperand(0));
1980   if (!Op0Reg)
1981     return false;
1982   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
1983
1984   uint64_t ShiftVal = cast<ConstantInt>(I->getOperand(1))->getZExtValue();
1985
1986   unsigned ResultReg;
1987   if (IsLeftShift)
1988     ResultReg = Emit_LSL_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
1989   else {
1990     if (IsArithmetic)
1991       ResultReg = Emit_ASR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
1992     else
1993       ResultReg = Emit_LSR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
1994   }
1995
1996   if (!ResultReg)
1997     return false;
1998
1999   UpdateValueMap(I, ResultReg);
2000   return true;
2001 }
2002
2003 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
2004   switch (I->getOpcode()) {
2005   default:
2006     break;
2007   case Instruction::Load:
2008     return SelectLoad(I);
2009   case Instruction::Store:
2010     return SelectStore(I);
2011   case Instruction::Br:
2012     return SelectBranch(I);
2013   case Instruction::IndirectBr:
2014     return SelectIndirectBr(I);
2015   case Instruction::FCmp:
2016   case Instruction::ICmp:
2017     return SelectCmp(I);
2018   case Instruction::Select:
2019     return SelectSelect(I);
2020   case Instruction::FPExt:
2021     return SelectFPExt(I);
2022   case Instruction::FPTrunc:
2023     return SelectFPTrunc(I);
2024   case Instruction::FPToSI:
2025     return SelectFPToInt(I, /*Signed=*/true);
2026   case Instruction::FPToUI:
2027     return SelectFPToInt(I, /*Signed=*/false);
2028   case Instruction::SIToFP:
2029     return SelectIntToFP(I, /*Signed=*/true);
2030   case Instruction::UIToFP:
2031     return SelectIntToFP(I, /*Signed=*/false);
2032   case Instruction::SRem:
2033     return SelectRem(I, ISD::SREM);
2034   case Instruction::URem:
2035     return SelectRem(I, ISD::UREM);
2036   case Instruction::Ret:
2037     return SelectRet(I);
2038   case Instruction::Trunc:
2039     return SelectTrunc(I);
2040   case Instruction::ZExt:
2041   case Instruction::SExt:
2042     return SelectIntExt(I);
2043
2044   // FIXME: All of these should really be handled by the target-independent
2045   // selector -> improve FastISel tblgen.
2046   case Instruction::Mul:
2047     return SelectMul(I);
2048   case Instruction::Shl:
2049       return SelectShift(I, /*IsLeftShift=*/true, /*IsArithmetic=*/false);
2050   case Instruction::LShr:
2051     return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/false);
2052   case Instruction::AShr:
2053     return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/true);
2054   }
2055   return false;
2056   // Silence warnings.
2057   (void)&CC_AArch64_DarwinPCS_VarArg;
2058 }
2059
2060 namespace llvm {
2061 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
2062                                         const TargetLibraryInfo *libInfo) {
2063   return new AArch64FastISel(funcInfo, libInfo);
2064 }
2065 }