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