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