AArch64: make FastISel memcpy emission more robust.
[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 "AArch64TargetMachine.h"
18 #include "AArch64Subtarget.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 private:
93   // Selection routines.
94   bool SelectLoad(const Instruction *I);
95   bool SelectStore(const Instruction *I);
96   bool SelectBranch(const Instruction *I);
97   bool SelectIndirectBr(const Instruction *I);
98   bool SelectCmp(const Instruction *I);
99   bool SelectSelect(const Instruction *I);
100   bool SelectFPExt(const Instruction *I);
101   bool SelectFPTrunc(const Instruction *I);
102   bool SelectFPToInt(const Instruction *I, bool Signed);
103   bool SelectIntToFP(const Instruction *I, bool Signed);
104   bool SelectRem(const Instruction *I, unsigned ISDOpcode);
105   bool SelectCall(const Instruction *I, const char *IntrMemName);
106   bool SelectIntrinsicCall(const IntrinsicInst &I);
107   bool SelectRet(const Instruction *I);
108   bool SelectTrunc(const Instruction *I);
109   bool SelectIntExt(const Instruction *I);
110   bool SelectMul(const Instruction *I);
111
112   // Utility helper routines.
113   bool isTypeLegal(Type *Ty, MVT &VT);
114   bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
115   bool ComputeAddress(const Value *Obj, Address &Addr);
116   bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
117                        bool UseUnscaled);
118   void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
119                             unsigned Flags, bool UseUnscaled);
120   bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
121   bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
122                           unsigned Alignment);
123   // Emit functions.
124   bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
125   bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
126                 bool UseUnscaled = false);
127   bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
128                  bool UseUnscaled = false);
129   unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
130   unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
131
132   unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
133   unsigned AArch64MaterializeGV(const GlobalValue *GV);
134
135   // Call handling routines.
136 private:
137   CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
138   bool ProcessCallArgs(SmallVectorImpl<Value *> &Args,
139                        SmallVectorImpl<unsigned> &ArgRegs,
140                        SmallVectorImpl<MVT> &ArgVTs,
141                        SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
142                        SmallVectorImpl<unsigned> &RegArgs, CallingConv::ID CC,
143                        unsigned &NumBytes);
144   bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
145                   const Instruction *I, CallingConv::ID CC, 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   // FIXME: If this is a stack pointer and the offset needs to be simplified
467   // then put the alloca address into a register, set the base type back to
468   // register and continue. This should almost never happen.
469   if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
470     return false;
471   }
472
473   // Since the offset is too large for the load/store instruction get the
474   // reg+offset into a register.
475   if (needsLowering) {
476     uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
477     unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
478                                       UnscaledOffset, MVT::i64);
479     if (ResultReg == 0)
480       return false;
481     Addr.setReg(ResultReg);
482     Addr.setOffset(0);
483   }
484   return true;
485 }
486
487 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
488                                            const MachineInstrBuilder &MIB,
489                                            unsigned Flags, bool UseUnscaled) {
490   int64_t Offset = Addr.getOffset();
491   // Frame base works a bit differently. Handle it separately.
492   if (Addr.getKind() == Address::FrameIndexBase) {
493     int FI = Addr.getFI();
494     // FIXME: We shouldn't be using getObjectSize/getObjectAlignment.  The size
495     // and alignment should be based on the VT.
496     MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
497         MachinePointerInfo::getFixedStack(FI, Offset), Flags,
498         MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
499     // Now add the rest of the operands.
500     MIB.addFrameIndex(FI).addImm(Offset).addMemOperand(MMO);
501   } else {
502     // Now add the rest of the operands.
503     MIB.addReg(Addr.getReg());
504     MIB.addImm(Offset);
505   }
506 }
507
508 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
509                                bool UseUnscaled) {
510   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
511   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
512   if (!UseUnscaled && Addr.getOffset() < 0)
513     UseUnscaled = true;
514
515   unsigned Opc;
516   const TargetRegisterClass *RC;
517   bool VTIsi1 = false;
518   int64_t ScaleFactor = 0;
519   switch (VT.SimpleTy) {
520   default:
521     return false;
522   case MVT::i1:
523     VTIsi1 = true;
524   // Intentional fall-through.
525   case MVT::i8:
526     Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
527     RC = &AArch64::GPR32RegClass;
528     ScaleFactor = 1;
529     break;
530   case MVT::i16:
531     Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
532     RC = &AArch64::GPR32RegClass;
533     ScaleFactor = 2;
534     break;
535   case MVT::i32:
536     Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
537     RC = &AArch64::GPR32RegClass;
538     ScaleFactor = 4;
539     break;
540   case MVT::i64:
541     Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
542     RC = &AArch64::GPR64RegClass;
543     ScaleFactor = 8;
544     break;
545   case MVT::f32:
546     Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
547     RC = TLI.getRegClassFor(VT);
548     ScaleFactor = 4;
549     break;
550   case MVT::f64:
551     Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
552     RC = TLI.getRegClassFor(VT);
553     ScaleFactor = 8;
554     break;
555   }
556   // Scale the offset.
557   if (!UseUnscaled) {
558     int64_t Offset = Addr.getOffset();
559     if (Offset & (ScaleFactor - 1))
560       // Retry using an unscaled, 9-bit, signed immediate offset.
561       return EmitLoad(VT, ResultReg, Addr, /*UseUnscaled*/ true);
562
563     Addr.setOffset(Offset / ScaleFactor);
564   }
565
566   // Simplify this down to something we can handle.
567   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
568     return false;
569
570   // Create the base instruction, then add the operands.
571   ResultReg = createResultReg(RC);
572   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
573                                     TII.get(Opc), ResultReg);
574   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, UseUnscaled);
575
576   // Loading an i1 requires special handling.
577   if (VTIsi1) {
578     MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
579     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
580     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
581             ANDReg)
582         .addReg(ResultReg)
583         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
584     ResultReg = ANDReg;
585   }
586   return true;
587 }
588
589 bool AArch64FastISel::SelectLoad(const Instruction *I) {
590   MVT VT;
591   // Verify we have a legal type before going any further.  Currently, we handle
592   // simple types that will directly fit in a register (i32/f32/i64/f64) or
593   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
594   if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
595     return false;
596
597   // See if we can handle this address.
598   Address Addr;
599   if (!ComputeAddress(I->getOperand(0), Addr))
600     return false;
601
602   unsigned ResultReg;
603   if (!EmitLoad(VT, ResultReg, Addr))
604     return false;
605
606   UpdateValueMap(I, ResultReg);
607   return true;
608 }
609
610 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
611                                 bool UseUnscaled) {
612   // Negative offsets require unscaled, 9-bit, signed immediate offsets.
613   // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
614   if (!UseUnscaled && Addr.getOffset() < 0)
615     UseUnscaled = true;
616
617   unsigned StrOpc;
618   bool VTIsi1 = false;
619   int64_t ScaleFactor = 0;
620   // Using scaled, 12-bit, unsigned immediate offsets.
621   switch (VT.SimpleTy) {
622   default:
623     return false;
624   case MVT::i1:
625     VTIsi1 = true;
626   case MVT::i8:
627     StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
628     ScaleFactor = 1;
629     break;
630   case MVT::i16:
631     StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
632     ScaleFactor = 2;
633     break;
634   case MVT::i32:
635     StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
636     ScaleFactor = 4;
637     break;
638   case MVT::i64:
639     StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
640     ScaleFactor = 8;
641     break;
642   case MVT::f32:
643     StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
644     ScaleFactor = 4;
645     break;
646   case MVT::f64:
647     StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
648     ScaleFactor = 8;
649     break;
650   }
651   // Scale the offset.
652   if (!UseUnscaled) {
653     int64_t Offset = Addr.getOffset();
654     if (Offset & (ScaleFactor - 1))
655       // Retry using an unscaled, 9-bit, signed immediate offset.
656       return EmitStore(VT, SrcReg, Addr, /*UseUnscaled*/ true);
657
658     Addr.setOffset(Offset / ScaleFactor);
659   }
660
661   // Simplify this down to something we can handle.
662   if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
663     return false;
664
665   // Storing an i1 requires special handling.
666   if (VTIsi1) {
667     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
668     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
669     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
670             ANDReg)
671         .addReg(SrcReg)
672         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
673     SrcReg = ANDReg;
674   }
675   // Create the base instruction, then add the operands.
676   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
677                                     TII.get(StrOpc)).addReg(SrcReg);
678   AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, UseUnscaled);
679   return true;
680 }
681
682 bool AArch64FastISel::SelectStore(const Instruction *I) {
683   MVT VT;
684   Value *Op0 = I->getOperand(0);
685   // Verify we have a legal type before going any further.  Currently, we handle
686   // simple types that will directly fit in a register (i32/f32/i64/f64) or
687   // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
688   if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
689       cast<StoreInst>(I)->isAtomic())
690     return false;
691
692   // Get the value to be stored into a register.
693   unsigned SrcReg = getRegForValue(Op0);
694   if (SrcReg == 0)
695     return false;
696
697   // See if we can handle this address.
698   Address Addr;
699   if (!ComputeAddress(I->getOperand(1), Addr))
700     return false;
701
702   if (!EmitStore(VT, SrcReg, Addr))
703     return false;
704   return true;
705 }
706
707 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
708   switch (Pred) {
709   case CmpInst::FCMP_ONE:
710   case CmpInst::FCMP_UEQ:
711   default:
712     // AL is our "false" for now. The other two need more compares.
713     return AArch64CC::AL;
714   case CmpInst::ICMP_EQ:
715   case CmpInst::FCMP_OEQ:
716     return AArch64CC::EQ;
717   case CmpInst::ICMP_SGT:
718   case CmpInst::FCMP_OGT:
719     return AArch64CC::GT;
720   case CmpInst::ICMP_SGE:
721   case CmpInst::FCMP_OGE:
722     return AArch64CC::GE;
723   case CmpInst::ICMP_UGT:
724   case CmpInst::FCMP_UGT:
725     return AArch64CC::HI;
726   case CmpInst::FCMP_OLT:
727     return AArch64CC::MI;
728   case CmpInst::ICMP_ULE:
729   case CmpInst::FCMP_OLE:
730     return AArch64CC::LS;
731   case CmpInst::FCMP_ORD:
732     return AArch64CC::VC;
733   case CmpInst::FCMP_UNO:
734     return AArch64CC::VS;
735   case CmpInst::FCMP_UGE:
736     return AArch64CC::PL;
737   case CmpInst::ICMP_SLT:
738   case CmpInst::FCMP_ULT:
739     return AArch64CC::LT;
740   case CmpInst::ICMP_SLE:
741   case CmpInst::FCMP_ULE:
742     return AArch64CC::LE;
743   case CmpInst::FCMP_UNE:
744   case CmpInst::ICMP_NE:
745     return AArch64CC::NE;
746   case CmpInst::ICMP_UGE:
747     return AArch64CC::HS;
748   case CmpInst::ICMP_ULT:
749     return AArch64CC::LO;
750   }
751 }
752
753 bool AArch64FastISel::SelectBranch(const Instruction *I) {
754   const BranchInst *BI = cast<BranchInst>(I);
755   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
756   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
757
758   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
759     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
760       // We may not handle every CC for now.
761       AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
762       if (CC == AArch64CC::AL)
763         return false;
764
765       // Emit the cmp.
766       if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
767         return false;
768
769       // Emit the branch.
770       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
771           .addImm(CC)
772           .addMBB(TBB);
773       FuncInfo.MBB->addSuccessor(TBB);
774
775       FastEmitBranch(FBB, DbgLoc);
776       return true;
777     }
778   } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
779     MVT SrcVT;
780     if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
781         (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
782       unsigned CondReg = getRegForValue(TI->getOperand(0));
783       if (CondReg == 0)
784         return false;
785
786       // Issue an extract_subreg to get the lower 32-bits.
787       if (SrcVT == MVT::i64)
788         CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
789                                              AArch64::sub_32);
790
791       MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
792       unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
793       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
794               TII.get(AArch64::ANDWri), ANDReg)
795           .addReg(CondReg)
796           .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
797       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
798               TII.get(AArch64::SUBSWri))
799           .addReg(ANDReg)
800           .addReg(ANDReg)
801           .addImm(0)
802           .addImm(0);
803
804       unsigned CC = AArch64CC::NE;
805       if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
806         std::swap(TBB, FBB);
807         CC = AArch64CC::EQ;
808       }
809       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
810           .addImm(CC)
811           .addMBB(TBB);
812       FuncInfo.MBB->addSuccessor(TBB);
813       FastEmitBranch(FBB, DbgLoc);
814       return true;
815     }
816   } else if (const ConstantInt *CI =
817                  dyn_cast<ConstantInt>(BI->getCondition())) {
818     uint64_t Imm = CI->getZExtValue();
819     MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
820     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
821         .addMBB(Target);
822     FuncInfo.MBB->addSuccessor(Target);
823     return true;
824   }
825
826   unsigned CondReg = getRegForValue(BI->getCondition());
827   if (CondReg == 0)
828     return false;
829
830   // We've been divorced from our compare!  Our block was split, and
831   // now our compare lives in a predecessor block.  We musn't
832   // re-compare here, as the children of the compare aren't guaranteed
833   // live across the block boundary (we *could* check for this).
834   // Regardless, the compare has been done in the predecessor block,
835   // and it left a value for us in a virtual register.  Ergo, we test
836   // the one-bit value left in the virtual register.
837   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
838           AArch64::WZR)
839       .addReg(CondReg)
840       .addImm(0)
841       .addImm(0);
842
843   unsigned CC = AArch64CC::NE;
844   if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
845     std::swap(TBB, FBB);
846     CC = AArch64CC::EQ;
847   }
848
849   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
850       .addImm(CC)
851       .addMBB(TBB);
852   FuncInfo.MBB->addSuccessor(TBB);
853   FastEmitBranch(FBB, DbgLoc);
854   return true;
855 }
856
857 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
858   const IndirectBrInst *BI = cast<IndirectBrInst>(I);
859   unsigned AddrReg = getRegForValue(BI->getOperand(0));
860   if (AddrReg == 0)
861     return false;
862
863   // Emit the indirect branch.
864   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
865       .addReg(AddrReg);
866
867   // Make sure the CFG is up-to-date.
868   for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
869     FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
870
871   return true;
872 }
873
874 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
875   Type *Ty = Src1Value->getType();
876   EVT SrcEVT = TLI.getValueType(Ty, true);
877   if (!SrcEVT.isSimple())
878     return false;
879   MVT SrcVT = SrcEVT.getSimpleVT();
880
881   // Check to see if the 2nd operand is a constant that we can encode directly
882   // in the compare.
883   uint64_t Imm;
884   bool UseImm = false;
885   bool isNegativeImm = false;
886   if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
887     if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
888         SrcVT == MVT::i8 || SrcVT == MVT::i1) {
889       const APInt &CIVal = ConstInt->getValue();
890
891       Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
892       if (CIVal.isNegative()) {
893         isNegativeImm = true;
894         Imm = -Imm;
895       }
896       // FIXME: We can handle more immediates using shifts.
897       UseImm = ((Imm & 0xfff) == Imm);
898     }
899   } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
900     if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
901       if (ConstFP->isZero() && !ConstFP->isNegative())
902         UseImm = true;
903   }
904
905   unsigned ZReg;
906   unsigned CmpOpc;
907   bool isICmp = true;
908   bool needsExt = false;
909   switch (SrcVT.SimpleTy) {
910   default:
911     return false;
912   case MVT::i1:
913   case MVT::i8:
914   case MVT::i16:
915     needsExt = true;
916   // Intentional fall-through.
917   case MVT::i32:
918     ZReg = AArch64::WZR;
919     if (UseImm)
920       CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
921     else
922       CmpOpc = AArch64::SUBSWrr;
923     break;
924   case MVT::i64:
925     ZReg = AArch64::XZR;
926     if (UseImm)
927       CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
928     else
929       CmpOpc = AArch64::SUBSXrr;
930     break;
931   case MVT::f32:
932     isICmp = false;
933     CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
934     break;
935   case MVT::f64:
936     isICmp = false;
937     CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
938     break;
939   }
940
941   unsigned SrcReg1 = getRegForValue(Src1Value);
942   if (SrcReg1 == 0)
943     return false;
944
945   unsigned SrcReg2;
946   if (!UseImm) {
947     SrcReg2 = getRegForValue(Src2Value);
948     if (SrcReg2 == 0)
949       return false;
950   }
951
952   // We have i1, i8, or i16, we need to either zero extend or sign extend.
953   if (needsExt) {
954     SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
955     if (SrcReg1 == 0)
956       return false;
957     if (!UseImm) {
958       SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
959       if (SrcReg2 == 0)
960         return false;
961     }
962   }
963
964   if (isICmp) {
965     if (UseImm)
966       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
967           .addReg(ZReg)
968           .addReg(SrcReg1)
969           .addImm(Imm)
970           .addImm(0);
971     else
972       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
973           .addReg(ZReg)
974           .addReg(SrcReg1)
975           .addReg(SrcReg2);
976   } else {
977     if (UseImm)
978       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
979           .addReg(SrcReg1);
980     else
981       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
982           .addReg(SrcReg1)
983           .addReg(SrcReg2);
984   }
985   return true;
986 }
987
988 bool AArch64FastISel::SelectCmp(const Instruction *I) {
989   const CmpInst *CI = cast<CmpInst>(I);
990
991   // We may not handle every CC for now.
992   AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
993   if (CC == AArch64CC::AL)
994     return false;
995
996   // Emit the cmp.
997   if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
998     return false;
999
1000   // Now set a register based on the comparison.
1001   AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1002   unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1003   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1004           ResultReg)
1005       .addReg(AArch64::WZR)
1006       .addReg(AArch64::WZR)
1007       .addImm(invertedCC);
1008
1009   UpdateValueMap(I, ResultReg);
1010   return true;
1011 }
1012
1013 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1014   const SelectInst *SI = cast<SelectInst>(I);
1015
1016   EVT DestEVT = TLI.getValueType(SI->getType(), true);
1017   if (!DestEVT.isSimple())
1018     return false;
1019
1020   MVT DestVT = DestEVT.getSimpleVT();
1021   if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1022       DestVT != MVT::f64)
1023     return false;
1024
1025   unsigned CondReg = getRegForValue(SI->getCondition());
1026   if (CondReg == 0)
1027     return false;
1028   unsigned TrueReg = getRegForValue(SI->getTrueValue());
1029   if (TrueReg == 0)
1030     return false;
1031   unsigned FalseReg = getRegForValue(SI->getFalseValue());
1032   if (FalseReg == 0)
1033     return false;
1034
1035
1036   MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1037   unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1038   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1039           ANDReg)
1040       .addReg(CondReg)
1041       .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1042
1043   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri))
1044       .addReg(ANDReg)
1045       .addReg(ANDReg)
1046       .addImm(0)
1047       .addImm(0);
1048
1049   unsigned SelectOpc;
1050   switch (DestVT.SimpleTy) {
1051   default:
1052     return false;
1053   case MVT::i32:
1054     SelectOpc = AArch64::CSELWr;
1055     break;
1056   case MVT::i64:
1057     SelectOpc = AArch64::CSELXr;
1058     break;
1059   case MVT::f32:
1060     SelectOpc = AArch64::FCSELSrrr;
1061     break;
1062   case MVT::f64:
1063     SelectOpc = AArch64::FCSELDrrr;
1064     break;
1065   }
1066
1067   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1068   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1069           ResultReg)
1070       .addReg(TrueReg)
1071       .addReg(FalseReg)
1072       .addImm(AArch64CC::NE);
1073
1074   UpdateValueMap(I, ResultReg);
1075   return true;
1076 }
1077
1078 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1079   Value *V = I->getOperand(0);
1080   if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1081     return false;
1082
1083   unsigned Op = getRegForValue(V);
1084   if (Op == 0)
1085     return false;
1086
1087   unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1088   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1089           ResultReg).addReg(Op);
1090   UpdateValueMap(I, ResultReg);
1091   return true;
1092 }
1093
1094 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1095   Value *V = I->getOperand(0);
1096   if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1097     return false;
1098
1099   unsigned Op = getRegForValue(V);
1100   if (Op == 0)
1101     return false;
1102
1103   unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1104   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1105           ResultReg).addReg(Op);
1106   UpdateValueMap(I, ResultReg);
1107   return true;
1108 }
1109
1110 // FPToUI and FPToSI
1111 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1112   MVT DestVT;
1113   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1114     return false;
1115
1116   unsigned SrcReg = getRegForValue(I->getOperand(0));
1117   if (SrcReg == 0)
1118     return false;
1119
1120   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1121   if (SrcVT == MVT::f128)
1122     return false;
1123
1124   unsigned Opc;
1125   if (SrcVT == MVT::f64) {
1126     if (Signed)
1127       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1128     else
1129       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1130   } else {
1131     if (Signed)
1132       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1133     else
1134       Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1135   }
1136   unsigned ResultReg = createResultReg(
1137       DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1138   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1139       .addReg(SrcReg);
1140   UpdateValueMap(I, ResultReg);
1141   return true;
1142 }
1143
1144 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1145   MVT DestVT;
1146   if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1147     return false;
1148   assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1149           "Unexpected value type.");
1150
1151   unsigned SrcReg = getRegForValue(I->getOperand(0));
1152   if (SrcReg == 0)
1153     return false;
1154
1155   EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1156
1157   // Handle sign-extension.
1158   if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1159     SrcReg =
1160         EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1161     if (SrcReg == 0)
1162       return false;
1163   }
1164
1165   MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1166                                                   : &AArch64::GPR32RegClass);
1167
1168   unsigned Opc;
1169   if (SrcVT == MVT::i64) {
1170     if (Signed)
1171       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1172     else
1173       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1174   } else {
1175     if (Signed)
1176       Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1177     else
1178       Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1179   }
1180
1181   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1182   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1183       .addReg(SrcReg);
1184   UpdateValueMap(I, ResultReg);
1185   return true;
1186 }
1187
1188 bool AArch64FastISel::ProcessCallArgs(
1189     SmallVectorImpl<Value *> &Args, SmallVectorImpl<unsigned> &ArgRegs,
1190     SmallVectorImpl<MVT> &ArgVTs, SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1191     SmallVectorImpl<unsigned> &RegArgs, CallingConv::ID CC,
1192     unsigned &NumBytes) {
1193   SmallVector<CCValAssign, 16> ArgLocs;
1194   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1195   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1196
1197   // Get a count of how many bytes are to be pushed on the stack.
1198   NumBytes = CCInfo.getNextStackOffset();
1199
1200   // Issue CALLSEQ_START
1201   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1202   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1203       .addImm(NumBytes);
1204
1205   // Process the args.
1206   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1207     CCValAssign &VA = ArgLocs[i];
1208     unsigned Arg = ArgRegs[VA.getValNo()];
1209     MVT ArgVT = ArgVTs[VA.getValNo()];
1210
1211     // Handle arg promotion: SExt, ZExt, AExt.
1212     switch (VA.getLocInfo()) {
1213     case CCValAssign::Full:
1214       break;
1215     case CCValAssign::SExt: {
1216       MVT DestVT = VA.getLocVT();
1217       MVT SrcVT = ArgVT;
1218       Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ false);
1219       if (Arg == 0)
1220         return false;
1221       break;
1222     }
1223     case CCValAssign::AExt:
1224     // Intentional fall-through.
1225     case CCValAssign::ZExt: {
1226       MVT DestVT = VA.getLocVT();
1227       MVT SrcVT = ArgVT;
1228       Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ true);
1229       if (Arg == 0)
1230         return false;
1231       break;
1232     }
1233     default:
1234       llvm_unreachable("Unknown arg promotion!");
1235     }
1236
1237     // Now copy/store arg to correct locations.
1238     if (VA.isRegLoc() && !VA.needsCustom()) {
1239       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1240               TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1241       RegArgs.push_back(VA.getLocReg());
1242     } else if (VA.needsCustom()) {
1243       // FIXME: Handle custom args.
1244       return false;
1245     } else {
1246       assert(VA.isMemLoc() && "Assuming store on stack.");
1247
1248       // Need to store on the stack.
1249       unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1250
1251       unsigned BEAlign = 0;
1252       if (ArgSize < 8 && !Subtarget->isLittleEndian())
1253         BEAlign = 8 - ArgSize;
1254
1255       Address Addr;
1256       Addr.setKind(Address::RegBase);
1257       Addr.setReg(AArch64::SP);
1258       Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1259
1260       if (!EmitStore(ArgVT, Arg, Addr))
1261         return false;
1262     }
1263   }
1264   return true;
1265 }
1266
1267 bool AArch64FastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1268                                  const Instruction *I, CallingConv::ID CC,
1269                                  unsigned &NumBytes) {
1270   // Issue CALLSEQ_END
1271   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1272   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1273       .addImm(NumBytes)
1274       .addImm(0);
1275
1276   // Now the return value.
1277   if (RetVT != MVT::isVoid) {
1278     SmallVector<CCValAssign, 16> RVLocs;
1279     CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1280     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1281
1282     // Only handle a single return value.
1283     if (RVLocs.size() != 1)
1284       return false;
1285
1286     // Copy all of the result registers out of their specified physreg.
1287     MVT CopyVT = RVLocs[0].getValVT();
1288     unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1289     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1290             TII.get(TargetOpcode::COPY),
1291             ResultReg).addReg(RVLocs[0].getLocReg());
1292     UsedRegs.push_back(RVLocs[0].getLocReg());
1293
1294     // Finally update the result.
1295     UpdateValueMap(I, ResultReg);
1296   }
1297
1298   return true;
1299 }
1300
1301 bool AArch64FastISel::SelectCall(const Instruction *I,
1302                                  const char *IntrMemName = nullptr) {
1303   const CallInst *CI = cast<CallInst>(I);
1304   const Value *Callee = CI->getCalledValue();
1305
1306   // Don't handle inline asm or intrinsics.
1307   if (isa<InlineAsm>(Callee))
1308     return false;
1309
1310   // Only handle global variable Callees.
1311   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1312   if (!GV)
1313     return false;
1314
1315   // Check the calling convention.
1316   ImmutableCallSite CS(CI);
1317   CallingConv::ID CC = CS.getCallingConv();
1318
1319   // Let SDISel handle vararg functions.
1320   PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1321   FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1322   if (FTy->isVarArg())
1323     return false;
1324
1325   // Handle *simple* calls for now.
1326   MVT RetVT;
1327   Type *RetTy = I->getType();
1328   if (RetTy->isVoidTy())
1329     RetVT = MVT::isVoid;
1330   else if (!isTypeLegal(RetTy, RetVT))
1331     return false;
1332
1333   // Set up the argument vectors.
1334   SmallVector<Value *, 8> Args;
1335   SmallVector<unsigned, 8> ArgRegs;
1336   SmallVector<MVT, 8> ArgVTs;
1337   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1338   Args.reserve(CS.arg_size());
1339   ArgRegs.reserve(CS.arg_size());
1340   ArgVTs.reserve(CS.arg_size());
1341   ArgFlags.reserve(CS.arg_size());
1342
1343   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1344        i != e; ++i) {
1345     // If we're lowering a memory intrinsic instead of a regular call, skip the
1346     // last two arguments, which shouldn't be passed to the underlying function.
1347     if (IntrMemName && e - i <= 2)
1348       break;
1349
1350     unsigned Arg = getRegForValue(*i);
1351     if (Arg == 0)
1352       return false;
1353
1354     ISD::ArgFlagsTy Flags;
1355     unsigned AttrInd = i - CS.arg_begin() + 1;
1356     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1357       Flags.setSExt();
1358     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1359       Flags.setZExt();
1360
1361     // FIXME: Only handle *easy* calls for now.
1362     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1363         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1364         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1365         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1366       return false;
1367
1368     MVT ArgVT;
1369     Type *ArgTy = (*i)->getType();
1370     if (!isTypeLegal(ArgTy, ArgVT) &&
1371         !(ArgVT == MVT::i1 || ArgVT == MVT::i8 || ArgVT == MVT::i16))
1372       return false;
1373
1374     // We don't handle vector parameters yet.
1375     if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1376       return false;
1377
1378     unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1379     Flags.setOrigAlign(OriginalAlignment);
1380
1381     Args.push_back(*i);
1382     ArgRegs.push_back(Arg);
1383     ArgVTs.push_back(ArgVT);
1384     ArgFlags.push_back(Flags);
1385   }
1386
1387   // Handle the arguments now that we've gotten them.
1388   SmallVector<unsigned, 4> RegArgs;
1389   unsigned NumBytes;
1390   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1391     return false;
1392
1393   // Issue the call.
1394   MachineInstrBuilder MIB;
1395   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BL));
1396   if (!IntrMemName)
1397     MIB.addGlobalAddress(GV, 0, 0);
1398   else
1399     MIB.addExternalSymbol(IntrMemName, 0);
1400
1401   // Add implicit physical register uses to the call.
1402   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1403     MIB.addReg(RegArgs[i], RegState::Implicit);
1404
1405   // Add a register mask with the call-preserved registers.
1406   // Proper defs for return values will be added by setPhysRegsDeadExcept().
1407   MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1408
1409   // Finish off the call including any return values.
1410   SmallVector<unsigned, 4> UsedRegs;
1411   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes))
1412     return false;
1413
1414   // Set all unused physreg defs as dead.
1415   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1416
1417   return true;
1418 }
1419
1420 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1421   if (Alignment)
1422     return Len / Alignment <= 4;
1423   else
1424     return Len < 32;
1425 }
1426
1427 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1428                                          uint64_t Len, unsigned Alignment) {
1429   // Make sure we don't bloat code by inlining very large memcpy's.
1430   if (!IsMemCpySmall(Len, Alignment))
1431     return false;
1432
1433   int64_t UnscaledOffset = 0;
1434   Address OrigDest = Dest;
1435   Address OrigSrc = Src;
1436
1437   while (Len) {
1438     MVT VT;
1439     if (!Alignment || Alignment >= 8) {
1440       if (Len >= 8)
1441         VT = MVT::i64;
1442       else if (Len >= 4)
1443         VT = MVT::i32;
1444       else if (Len >= 2)
1445         VT = MVT::i16;
1446       else {
1447         VT = MVT::i8;
1448       }
1449     } else {
1450       // Bound based on alignment.
1451       if (Len >= 4 && Alignment == 4)
1452         VT = MVT::i32;
1453       else if (Len >= 2 && Alignment == 2)
1454         VT = MVT::i16;
1455       else {
1456         VT = MVT::i8;
1457       }
1458     }
1459
1460     bool RV;
1461     unsigned ResultReg;
1462     RV = EmitLoad(VT, ResultReg, Src);
1463     if (!RV)
1464       return false;
1465
1466     RV = EmitStore(VT, ResultReg, Dest);
1467     if (!RV)
1468       return false;
1469
1470     int64_t Size = VT.getSizeInBits() / 8;
1471     Len -= Size;
1472     UnscaledOffset += Size;
1473
1474     // We need to recompute the unscaled offset for each iteration.
1475     Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1476     Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1477   }
1478
1479   return true;
1480 }
1481
1482 bool AArch64FastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
1483   // FIXME: Handle more intrinsics.
1484   switch (I.getIntrinsicID()) {
1485   default:
1486     return false;
1487   case Intrinsic::memcpy:
1488   case Intrinsic::memmove: {
1489     const MemTransferInst &MTI = cast<MemTransferInst>(I);
1490     // Don't handle volatile.
1491     if (MTI.isVolatile())
1492       return false;
1493
1494     // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
1495     // we would emit dead code because we don't currently handle memmoves.
1496     bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
1497     if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
1498       // Small memcpy's are common enough that we want to do them without a call
1499       // if possible.
1500       uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
1501       unsigned Alignment = MTI.getAlignment();
1502       if (IsMemCpySmall(Len, Alignment)) {
1503         Address Dest, Src;
1504         if (!ComputeAddress(MTI.getRawDest(), Dest) ||
1505             !ComputeAddress(MTI.getRawSource(), Src))
1506           return false;
1507         if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1508           return true;
1509       }
1510     }
1511
1512     if (!MTI.getLength()->getType()->isIntegerTy(64))
1513       return false;
1514
1515     if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
1516       // Fast instruction selection doesn't support the special
1517       // address spaces.
1518       return false;
1519
1520     const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
1521     return SelectCall(&I, IntrMemName);
1522   }
1523   case Intrinsic::memset: {
1524     const MemSetInst &MSI = cast<MemSetInst>(I);
1525     // Don't handle volatile.
1526     if (MSI.isVolatile())
1527       return false;
1528
1529     if (!MSI.getLength()->getType()->isIntegerTy(64))
1530       return false;
1531
1532     if (MSI.getDestAddressSpace() > 255)
1533       // Fast instruction selection doesn't support the special
1534       // address spaces.
1535       return false;
1536
1537     return SelectCall(&I, "memset");
1538   }
1539   case Intrinsic::trap: {
1540     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1541         .addImm(1);
1542     return true;
1543   }
1544   }
1545   return false;
1546 }
1547
1548 bool AArch64FastISel::SelectRet(const Instruction *I) {
1549   const ReturnInst *Ret = cast<ReturnInst>(I);
1550   const Function &F = *I->getParent()->getParent();
1551
1552   if (!FuncInfo.CanLowerReturn)
1553     return false;
1554
1555   if (F.isVarArg())
1556     return false;
1557
1558   // Build a list of return value registers.
1559   SmallVector<unsigned, 4> RetRegs;
1560
1561   if (Ret->getNumOperands() > 0) {
1562     CallingConv::ID CC = F.getCallingConv();
1563     SmallVector<ISD::OutputArg, 4> Outs;
1564     GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1565
1566     // Analyze operands of the call, assigning locations to each operand.
1567     SmallVector<CCValAssign, 16> ValLocs;
1568     CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1569                    I->getContext());
1570     CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
1571                                                      : RetCC_AArch64_AAPCS;
1572     CCInfo.AnalyzeReturn(Outs, RetCC);
1573
1574     // Only handle a single return value for now.
1575     if (ValLocs.size() != 1)
1576       return false;
1577
1578     CCValAssign &VA = ValLocs[0];
1579     const Value *RV = Ret->getOperand(0);
1580
1581     // Don't bother handling odd stuff for now.
1582     if (VA.getLocInfo() != CCValAssign::Full)
1583       return false;
1584     // Only handle register returns for now.
1585     if (!VA.isRegLoc())
1586       return false;
1587     unsigned Reg = getRegForValue(RV);
1588     if (Reg == 0)
1589       return false;
1590
1591     unsigned SrcReg = Reg + VA.getValNo();
1592     unsigned DestReg = VA.getLocReg();
1593     // Avoid a cross-class copy. This is very unlikely.
1594     if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1595       return false;
1596
1597     EVT RVEVT = TLI.getValueType(RV->getType());
1598     if (!RVEVT.isSimple())
1599       return false;
1600
1601     // Vectors (of > 1 lane) in big endian need tricky handling.
1602     if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
1603       return false;
1604
1605     MVT RVVT = RVEVT.getSimpleVT();
1606     if (RVVT == MVT::f128)
1607       return false;
1608     MVT DestVT = VA.getValVT();
1609     // Special handling for extended integers.
1610     if (RVVT != DestVT) {
1611       if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1612         return false;
1613
1614       if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1615         return false;
1616
1617       bool isZExt = Outs[0].Flags.isZExt();
1618       SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
1619       if (SrcReg == 0)
1620         return false;
1621     }
1622
1623     // Make the copy.
1624     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1625             TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1626
1627     // Add register to return instruction.
1628     RetRegs.push_back(VA.getLocReg());
1629   }
1630
1631   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1632                                     TII.get(AArch64::RET_ReallyLR));
1633   for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1634     MIB.addReg(RetRegs[i], RegState::Implicit);
1635   return true;
1636 }
1637
1638 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
1639   Type *DestTy = I->getType();
1640   Value *Op = I->getOperand(0);
1641   Type *SrcTy = Op->getType();
1642
1643   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1644   EVT DestEVT = TLI.getValueType(DestTy, true);
1645   if (!SrcEVT.isSimple())
1646     return false;
1647   if (!DestEVT.isSimple())
1648     return false;
1649
1650   MVT SrcVT = SrcEVT.getSimpleVT();
1651   MVT DestVT = DestEVT.getSimpleVT();
1652
1653   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1654       SrcVT != MVT::i8)
1655     return false;
1656   if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
1657       DestVT != MVT::i1)
1658     return false;
1659
1660   unsigned SrcReg = getRegForValue(Op);
1661   if (!SrcReg)
1662     return false;
1663
1664   // If we're truncating from i64 to a smaller non-legal type then generate an
1665   // AND.  Otherwise, we know the high bits are undefined and a truncate doesn't
1666   // generate any code.
1667   if (SrcVT == MVT::i64) {
1668     uint64_t Mask = 0;
1669     switch (DestVT.SimpleTy) {
1670     default:
1671       // Trunc i64 to i32 is handled by the target-independent fast-isel.
1672       return false;
1673     case MVT::i1:
1674       Mask = 0x1;
1675       break;
1676     case MVT::i8:
1677       Mask = 0xff;
1678       break;
1679     case MVT::i16:
1680       Mask = 0xffff;
1681       break;
1682     }
1683     // Issue an extract_subreg to get the lower 32-bits.
1684     unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
1685                                                 AArch64::sub_32);
1686     MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
1687     // Create the AND instruction which performs the actual truncation.
1688     unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1689     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1690             ANDReg)
1691         .addReg(Reg32)
1692         .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
1693     SrcReg = ANDReg;
1694   }
1695
1696   UpdateValueMap(I, SrcReg);
1697   return true;
1698 }
1699
1700 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
1701   assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
1702           DestVT == MVT::i64) &&
1703          "Unexpected value type.");
1704   // Handle i8 and i16 as i32.
1705   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1706     DestVT = MVT::i32;
1707
1708   if (isZExt) {
1709     MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
1710     unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
1711     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1712             ResultReg)
1713         .addReg(SrcReg)
1714         .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1715
1716     if (DestVT == MVT::i64) {
1717       // We're ZExt i1 to i64.  The ANDWri Wd, Ws, #1 implicitly clears the
1718       // upper 32 bits.  Emit a SUBREG_TO_REG to extend from Wd to Xd.
1719       unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1720       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1721               TII.get(AArch64::SUBREG_TO_REG), Reg64)
1722           .addImm(0)
1723           .addReg(ResultReg)
1724           .addImm(AArch64::sub_32);
1725       ResultReg = Reg64;
1726     }
1727     return ResultReg;
1728   } else {
1729     if (DestVT == MVT::i64) {
1730       // FIXME: We're SExt i1 to i64.
1731       return 0;
1732     }
1733     unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1734     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
1735             ResultReg)
1736         .addReg(SrcReg)
1737         .addImm(0)
1738         .addImm(0);
1739     return ResultReg;
1740   }
1741 }
1742
1743 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1744                                      bool isZExt) {
1745   assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
1746   unsigned Opc;
1747   unsigned Imm = 0;
1748
1749   switch (SrcVT.SimpleTy) {
1750   default:
1751     return 0;
1752   case MVT::i1:
1753     return Emiti1Ext(SrcReg, DestVT, isZExt);
1754   case MVT::i8:
1755     if (DestVT == MVT::i64)
1756       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1757     else
1758       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1759     Imm = 7;
1760     break;
1761   case MVT::i16:
1762     if (DestVT == MVT::i64)
1763       Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1764     else
1765       Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
1766     Imm = 15;
1767     break;
1768   case MVT::i32:
1769     assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
1770     Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
1771     Imm = 31;
1772     break;
1773   }
1774
1775   // Handle i8 and i16 as i32.
1776   if (DestVT == MVT::i8 || DestVT == MVT::i16)
1777     DestVT = MVT::i32;
1778   else if (DestVT == MVT::i64) {
1779     unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1780     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1781             TII.get(AArch64::SUBREG_TO_REG), Src64)
1782         .addImm(0)
1783         .addReg(SrcReg)
1784         .addImm(AArch64::sub_32);
1785     SrcReg = Src64;
1786   }
1787
1788   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1789   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1790       .addReg(SrcReg)
1791       .addImm(0)
1792       .addImm(Imm);
1793
1794   return ResultReg;
1795 }
1796
1797 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
1798   // On ARM, in general, integer casts don't involve legal types; this code
1799   // handles promotable integers.  The high bits for a type smaller than
1800   // the register size are assumed to be undefined.
1801   Type *DestTy = I->getType();
1802   Value *Src = I->getOperand(0);
1803   Type *SrcTy = Src->getType();
1804
1805   bool isZExt = isa<ZExtInst>(I);
1806   unsigned SrcReg = getRegForValue(Src);
1807   if (!SrcReg)
1808     return false;
1809
1810   EVT SrcEVT = TLI.getValueType(SrcTy, true);
1811   EVT DestEVT = TLI.getValueType(DestTy, true);
1812   if (!SrcEVT.isSimple())
1813     return false;
1814   if (!DestEVT.isSimple())
1815     return false;
1816
1817   MVT SrcVT = SrcEVT.getSimpleVT();
1818   MVT DestVT = DestEVT.getSimpleVT();
1819   unsigned ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
1820   if (ResultReg == 0)
1821     return false;
1822   UpdateValueMap(I, ResultReg);
1823   return true;
1824 }
1825
1826 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
1827   EVT DestEVT = TLI.getValueType(I->getType(), true);
1828   if (!DestEVT.isSimple())
1829     return false;
1830
1831   MVT DestVT = DestEVT.getSimpleVT();
1832   if (DestVT != MVT::i64 && DestVT != MVT::i32)
1833     return false;
1834
1835   unsigned DivOpc;
1836   bool is64bit = (DestVT == MVT::i64);
1837   switch (ISDOpcode) {
1838   default:
1839     return false;
1840   case ISD::SREM:
1841     DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
1842     break;
1843   case ISD::UREM:
1844     DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
1845     break;
1846   }
1847   unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
1848   unsigned Src0Reg = getRegForValue(I->getOperand(0));
1849   if (!Src0Reg)
1850     return false;
1851
1852   unsigned Src1Reg = getRegForValue(I->getOperand(1));
1853   if (!Src1Reg)
1854     return false;
1855
1856   unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
1857   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
1858       .addReg(Src0Reg)
1859       .addReg(Src1Reg);
1860   // The remainder is computed as numerator - (quotient * denominator) using the
1861   // MSUB instruction.
1862   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1863   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
1864       .addReg(QuotReg)
1865       .addReg(Src1Reg)
1866       .addReg(Src0Reg);
1867   UpdateValueMap(I, ResultReg);
1868   return true;
1869 }
1870
1871 bool AArch64FastISel::SelectMul(const Instruction *I) {
1872   EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1873   if (!SrcEVT.isSimple())
1874     return false;
1875   MVT SrcVT = SrcEVT.getSimpleVT();
1876
1877   // Must be simple value type.  Don't handle vectors.
1878   if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1879       SrcVT != MVT::i8)
1880     return false;
1881
1882   unsigned Opc;
1883   unsigned ZReg;
1884   switch (SrcVT.SimpleTy) {
1885   default:
1886     return false;
1887   case MVT::i8:
1888   case MVT::i16:
1889   case MVT::i32:
1890     ZReg = AArch64::WZR;
1891     Opc = AArch64::MADDWrrr;
1892     break;
1893   case MVT::i64:
1894     ZReg = AArch64::XZR;
1895     Opc = AArch64::MADDXrrr;
1896     break;
1897   }
1898
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   // Create the base instruction, then add the operands.
1908   unsigned ResultReg = createResultReg(TLI.getRegClassFor(SrcVT));
1909   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1910       .addReg(Src0Reg)
1911       .addReg(Src1Reg)
1912       .addReg(ZReg);
1913   UpdateValueMap(I, ResultReg);
1914   return true;
1915 }
1916
1917 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
1918   switch (I->getOpcode()) {
1919   default:
1920     break;
1921   case Instruction::Load:
1922     return SelectLoad(I);
1923   case Instruction::Store:
1924     return SelectStore(I);
1925   case Instruction::Br:
1926     return SelectBranch(I);
1927   case Instruction::IndirectBr:
1928     return SelectIndirectBr(I);
1929   case Instruction::FCmp:
1930   case Instruction::ICmp:
1931     return SelectCmp(I);
1932   case Instruction::Select:
1933     return SelectSelect(I);
1934   case Instruction::FPExt:
1935     return SelectFPExt(I);
1936   case Instruction::FPTrunc:
1937     return SelectFPTrunc(I);
1938   case Instruction::FPToSI:
1939     return SelectFPToInt(I, /*Signed=*/true);
1940   case Instruction::FPToUI:
1941     return SelectFPToInt(I, /*Signed=*/false);
1942   case Instruction::SIToFP:
1943     return SelectIntToFP(I, /*Signed=*/true);
1944   case Instruction::UIToFP:
1945     return SelectIntToFP(I, /*Signed=*/false);
1946   case Instruction::SRem:
1947     return SelectRem(I, ISD::SREM);
1948   case Instruction::URem:
1949     return SelectRem(I, ISD::UREM);
1950   case Instruction::Call:
1951     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1952       return SelectIntrinsicCall(*II);
1953     return SelectCall(I);
1954   case Instruction::Ret:
1955     return SelectRet(I);
1956   case Instruction::Trunc:
1957     return SelectTrunc(I);
1958   case Instruction::ZExt:
1959   case Instruction::SExt:
1960     return SelectIntExt(I);
1961   case Instruction::Mul:
1962     // FIXME: This really should be handled by the target-independent selector.
1963     return SelectMul(I);
1964   }
1965   return false;
1966   // Silence warnings.
1967   (void)&CC_AArch64_DarwinPCS_VarArg;
1968 }
1969
1970 namespace llvm {
1971 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
1972                                         const TargetLibraryInfo *libInfo) {
1973   return new AArch64FastISel(funcInfo, libInfo);
1974 }
1975 }