ARMFastISel.cpp revision 316a5aa0a510e6183dd1981dd8bf328ffe7361f5
1//===-- ARMFastISel.cpp - ARM 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 ARM-specific support for the FastISel class. Some
11// of the target-specific code is generated by tablegen in the file
12// ARMGenFastISel.inc, which is #included here.
13//
14//===----------------------------------------------------------------------===//
15
16#include "ARM.h"
17#include "ARMBaseInstrInfo.h"
18#include "ARMCallingConv.h"
19#include "ARMConstantPoolValue.h"
20#include "ARMSubtarget.h"
21#include "ARMTargetMachine.h"
22#include "MCTargetDesc/ARMAddressingModes.h"
23#include "llvm/CallingConv.h"
24#include "llvm/CodeGen/Analysis.h"
25#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/MachineMemOperand.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/DataLayout.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/GlobalVariable.h"
36#include "llvm/Instructions.h"
37#include "llvm/IntrinsicInst.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Support/CallSite.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/GetElementPtrTypeIterator.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetLowering.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Target/TargetOptions.h"
48using namespace llvm;
49
50extern cl::opt<bool> EnableARMLongCalls;
51
52namespace {
53
54  // All possible address modes, plus some.
55  typedef struct Address {
56    enum {
57      RegBase,
58      FrameIndexBase
59    } BaseType;
60
61    union {
62      unsigned Reg;
63      int FI;
64    } Base;
65
66    int Offset;
67
68    // Innocuous defaults for our address.
69    Address()
70     : BaseType(RegBase), Offset(0) {
71       Base.Reg = 0;
72     }
73  } Address;
74
75class ARMFastISel : public FastISel {
76
77  /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
78  /// make the right decision when generating code for different targets.
79  const ARMSubtarget *Subtarget;
80  const TargetMachine &TM;
81  const TargetInstrInfo &TII;
82  const TargetLowering &TLI;
83  ARMFunctionInfo *AFI;
84
85  // Convenience variables to avoid some queries.
86  bool isThumb2;
87  LLVMContext *Context;
88
89  public:
90    explicit ARMFastISel(FunctionLoweringInfo &funcInfo,
91                         const TargetLibraryInfo *libInfo)
92    : FastISel(funcInfo, libInfo),
93      TM(funcInfo.MF->getTarget()),
94      TII(*TM.getInstrInfo()),
95      TLI(*TM.getTargetLowering()) {
96      Subtarget = &TM.getSubtarget<ARMSubtarget>();
97      AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
98      isThumb2 = AFI->isThumbFunction();
99      Context = &funcInfo.Fn->getContext();
100    }
101
102    // Code from FastISel.cpp.
103  private:
104    unsigned FastEmitInst_(unsigned MachineInstOpcode,
105                           const TargetRegisterClass *RC);
106    unsigned FastEmitInst_r(unsigned MachineInstOpcode,
107                            const TargetRegisterClass *RC,
108                            unsigned Op0, bool Op0IsKill);
109    unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
110                             const TargetRegisterClass *RC,
111                             unsigned Op0, bool Op0IsKill,
112                             unsigned Op1, bool Op1IsKill);
113    unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
114                              const TargetRegisterClass *RC,
115                              unsigned Op0, bool Op0IsKill,
116                              unsigned Op1, bool Op1IsKill,
117                              unsigned Op2, bool Op2IsKill);
118    unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
119                             const TargetRegisterClass *RC,
120                             unsigned Op0, bool Op0IsKill,
121                             uint64_t Imm);
122    unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
123                             const TargetRegisterClass *RC,
124                             unsigned Op0, bool Op0IsKill,
125                             const ConstantFP *FPImm);
126    unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
127                              const TargetRegisterClass *RC,
128                              unsigned Op0, bool Op0IsKill,
129                              unsigned Op1, bool Op1IsKill,
130                              uint64_t Imm);
131    unsigned FastEmitInst_i(unsigned MachineInstOpcode,
132                            const TargetRegisterClass *RC,
133                            uint64_t Imm);
134    unsigned FastEmitInst_ii(unsigned MachineInstOpcode,
135                             const TargetRegisterClass *RC,
136                             uint64_t Imm1, uint64_t Imm2);
137
138    unsigned FastEmitInst_extractsubreg(MVT RetVT,
139                                        unsigned Op0, bool Op0IsKill,
140                                        uint32_t Idx);
141
142    // Backend specific FastISel code.
143  private:
144    virtual bool TargetSelectInstruction(const Instruction *I);
145    virtual unsigned TargetMaterializeConstant(const Constant *C);
146    virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
147    virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
148                               const LoadInst *LI);
149  private:
150  #include "ARMGenFastISel.inc"
151
152    // Instruction selection routines.
153  private:
154    bool SelectLoad(const Instruction *I);
155    bool SelectStore(const Instruction *I);
156    bool SelectBranch(const Instruction *I);
157    bool SelectIndirectBr(const Instruction *I);
158    bool SelectCmp(const Instruction *I);
159    bool SelectFPExt(const Instruction *I);
160    bool SelectFPTrunc(const Instruction *I);
161    bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
162    bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
163    bool SelectIToFP(const Instruction *I, bool isSigned);
164    bool SelectFPToI(const Instruction *I, bool isSigned);
165    bool SelectDiv(const Instruction *I, bool isSigned);
166    bool SelectRem(const Instruction *I, bool isSigned);
167    bool SelectCall(const Instruction *I, const char *IntrMemName);
168    bool SelectIntrinsicCall(const IntrinsicInst &I);
169    bool SelectSelect(const Instruction *I);
170    bool SelectRet(const Instruction *I);
171    bool SelectTrunc(const Instruction *I);
172    bool SelectIntExt(const Instruction *I);
173    bool SelectShift(const Instruction *I, ARM_AM::ShiftOpc ShiftTy);
174
175    // Utility routines.
176  private:
177    bool isTypeLegal(Type *Ty, MVT &VT);
178    bool isLoadTypeLegal(Type *Ty, MVT &VT);
179    bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
180                    bool isZExt);
181    bool ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
182                     unsigned Alignment = 0, bool isZExt = true,
183                     bool allocReg = true);
184    bool ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
185                      unsigned Alignment = 0);
186    bool ARMComputeAddress(const Value *Obj, Address &Addr);
187    void ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3);
188    bool ARMIsMemCpySmall(uint64_t Len);
189    bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
190                               unsigned Alignment);
191    unsigned ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
192    unsigned ARMMaterializeFP(const ConstantFP *CFP, MVT VT);
193    unsigned ARMMaterializeInt(const Constant *C, MVT VT);
194    unsigned ARMMaterializeGV(const GlobalValue *GV, MVT VT);
195    unsigned ARMMoveToFPReg(MVT VT, unsigned SrcReg);
196    unsigned ARMMoveToIntReg(MVT VT, unsigned SrcReg);
197    unsigned ARMSelectCallOp(bool UseReg);
198    unsigned ARMLowerPICELF(const GlobalValue *GV, unsigned Align, MVT VT);
199
200    // Call handling routines.
201  private:
202    CCAssignFn *CCAssignFnForCall(CallingConv::ID CC,
203                                  bool Return,
204                                  bool isVarArg);
205    bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
206                         SmallVectorImpl<unsigned> &ArgRegs,
207                         SmallVectorImpl<MVT> &ArgVTs,
208                         SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
209                         SmallVectorImpl<unsigned> &RegArgs,
210                         CallingConv::ID CC,
211                         unsigned &NumBytes,
212                         bool isVarArg);
213    unsigned getLibcallReg(const Twine &Name);
214    bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
215                    const Instruction *I, CallingConv::ID CC,
216                    unsigned &NumBytes, bool isVarArg);
217    bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
218
219    // OptionalDef handling routines.
220  private:
221    bool isARMNEONPred(const MachineInstr *MI);
222    bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
223    const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
224    void AddLoadStoreOperands(EVT VT, Address &Addr,
225                              const MachineInstrBuilder &MIB,
226                              unsigned Flags, bool useAM3);
227};
228
229} // end anonymous namespace
230
231#include "ARMGenCallingConv.inc"
232
233// DefinesOptionalPredicate - This is different from DefinesPredicate in that
234// we don't care about implicit defs here, just places we'll need to add a
235// default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
236bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
237  if (!MI->hasOptionalDef())
238    return false;
239
240  // Look to see if our OptionalDef is defining CPSR or CCR.
241  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
242    const MachineOperand &MO = MI->getOperand(i);
243    if (!MO.isReg() || !MO.isDef()) continue;
244    if (MO.getReg() == ARM::CPSR)
245      *CPSR = true;
246  }
247  return true;
248}
249
250bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
251  const MCInstrDesc &MCID = MI->getDesc();
252
253  // If we're a thumb2 or not NEON function we were handled via isPredicable.
254  if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
255       AFI->isThumb2Function())
256    return false;
257
258  for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
259    if (MCID.OpInfo[i].isPredicate())
260      return true;
261
262  return false;
263}
264
265// If the machine is predicable go ahead and add the predicate operands, if
266// it needs default CC operands add those.
267// TODO: If we want to support thumb1 then we'll need to deal with optional
268// CPSR defs that need to be added before the remaining operands. See s_cc_out
269// for descriptions why.
270const MachineInstrBuilder &
271ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
272  MachineInstr *MI = &*MIB;
273
274  // Do we use a predicate? or...
275  // Are we NEON in ARM mode and have a predicate operand? If so, I know
276  // we're not predicable but add it anyways.
277  if (TII.isPredicable(MI) || isARMNEONPred(MI))
278    AddDefaultPred(MIB);
279
280  // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
281  // defines CPSR. All other OptionalDefines in ARM are the CCR register.
282  bool CPSR = false;
283  if (DefinesOptionalPredicate(MI, &CPSR)) {
284    if (CPSR)
285      AddDefaultT1CC(MIB);
286    else
287      AddDefaultCC(MIB);
288  }
289  return MIB;
290}
291
292unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
293                                    const TargetRegisterClass* RC) {
294  unsigned ResultReg = createResultReg(RC);
295  const MCInstrDesc &II = TII.get(MachineInstOpcode);
296
297  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
298  return ResultReg;
299}
300
301unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
302                                     const TargetRegisterClass *RC,
303                                     unsigned Op0, bool Op0IsKill) {
304  unsigned ResultReg = createResultReg(RC);
305  const MCInstrDesc &II = TII.get(MachineInstOpcode);
306
307  if (II.getNumDefs() >= 1) {
308    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
309                   .addReg(Op0, Op0IsKill * RegState::Kill));
310  } else {
311    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
312                   .addReg(Op0, Op0IsKill * RegState::Kill));
313    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
314                   TII.get(TargetOpcode::COPY), ResultReg)
315                   .addReg(II.ImplicitDefs[0]));
316  }
317  return ResultReg;
318}
319
320unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
321                                      const TargetRegisterClass *RC,
322                                      unsigned Op0, bool Op0IsKill,
323                                      unsigned Op1, bool Op1IsKill) {
324  unsigned ResultReg = createResultReg(RC);
325  const MCInstrDesc &II = TII.get(MachineInstOpcode);
326
327  if (II.getNumDefs() >= 1) {
328    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
329                   .addReg(Op0, Op0IsKill * RegState::Kill)
330                   .addReg(Op1, Op1IsKill * RegState::Kill));
331  } else {
332    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
333                   .addReg(Op0, Op0IsKill * RegState::Kill)
334                   .addReg(Op1, Op1IsKill * RegState::Kill));
335    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
336                           TII.get(TargetOpcode::COPY), ResultReg)
337                   .addReg(II.ImplicitDefs[0]));
338  }
339  return ResultReg;
340}
341
342unsigned ARMFastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
343                                       const TargetRegisterClass *RC,
344                                       unsigned Op0, bool Op0IsKill,
345                                       unsigned Op1, bool Op1IsKill,
346                                       unsigned Op2, bool Op2IsKill) {
347  unsigned ResultReg = createResultReg(RC);
348  const MCInstrDesc &II = TII.get(MachineInstOpcode);
349
350  if (II.getNumDefs() >= 1) {
351    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
352                   .addReg(Op0, Op0IsKill * RegState::Kill)
353                   .addReg(Op1, Op1IsKill * RegState::Kill)
354                   .addReg(Op2, Op2IsKill * RegState::Kill));
355  } else {
356    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
357                   .addReg(Op0, Op0IsKill * RegState::Kill)
358                   .addReg(Op1, Op1IsKill * RegState::Kill)
359                   .addReg(Op2, Op2IsKill * RegState::Kill));
360    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
361                           TII.get(TargetOpcode::COPY), ResultReg)
362                   .addReg(II.ImplicitDefs[0]));
363  }
364  return ResultReg;
365}
366
367unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
368                                      const TargetRegisterClass *RC,
369                                      unsigned Op0, bool Op0IsKill,
370                                      uint64_t Imm) {
371  unsigned ResultReg = createResultReg(RC);
372  const MCInstrDesc &II = TII.get(MachineInstOpcode);
373
374  if (II.getNumDefs() >= 1) {
375    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
376                   .addReg(Op0, Op0IsKill * RegState::Kill)
377                   .addImm(Imm));
378  } else {
379    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
380                   .addReg(Op0, Op0IsKill * RegState::Kill)
381                   .addImm(Imm));
382    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
383                           TII.get(TargetOpcode::COPY), ResultReg)
384                   .addReg(II.ImplicitDefs[0]));
385  }
386  return ResultReg;
387}
388
389unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
390                                      const TargetRegisterClass *RC,
391                                      unsigned Op0, bool Op0IsKill,
392                                      const ConstantFP *FPImm) {
393  unsigned ResultReg = createResultReg(RC);
394  const MCInstrDesc &II = TII.get(MachineInstOpcode);
395
396  if (II.getNumDefs() >= 1) {
397    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
398                   .addReg(Op0, Op0IsKill * RegState::Kill)
399                   .addFPImm(FPImm));
400  } else {
401    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
402                   .addReg(Op0, Op0IsKill * RegState::Kill)
403                   .addFPImm(FPImm));
404    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
405                           TII.get(TargetOpcode::COPY), ResultReg)
406                   .addReg(II.ImplicitDefs[0]));
407  }
408  return ResultReg;
409}
410
411unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
412                                       const TargetRegisterClass *RC,
413                                       unsigned Op0, bool Op0IsKill,
414                                       unsigned Op1, bool Op1IsKill,
415                                       uint64_t Imm) {
416  unsigned ResultReg = createResultReg(RC);
417  const MCInstrDesc &II = TII.get(MachineInstOpcode);
418
419  if (II.getNumDefs() >= 1) {
420    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
421                   .addReg(Op0, Op0IsKill * RegState::Kill)
422                   .addReg(Op1, Op1IsKill * RegState::Kill)
423                   .addImm(Imm));
424  } else {
425    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
426                   .addReg(Op0, Op0IsKill * RegState::Kill)
427                   .addReg(Op1, Op1IsKill * RegState::Kill)
428                   .addImm(Imm));
429    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
430                           TII.get(TargetOpcode::COPY), ResultReg)
431                   .addReg(II.ImplicitDefs[0]));
432  }
433  return ResultReg;
434}
435
436unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
437                                     const TargetRegisterClass *RC,
438                                     uint64_t Imm) {
439  unsigned ResultReg = createResultReg(RC);
440  const MCInstrDesc &II = TII.get(MachineInstOpcode);
441
442  if (II.getNumDefs() >= 1) {
443    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
444                   .addImm(Imm));
445  } else {
446    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
447                   .addImm(Imm));
448    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
449                           TII.get(TargetOpcode::COPY), ResultReg)
450                   .addReg(II.ImplicitDefs[0]));
451  }
452  return ResultReg;
453}
454
455unsigned ARMFastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
456                                      const TargetRegisterClass *RC,
457                                      uint64_t Imm1, uint64_t Imm2) {
458  unsigned ResultReg = createResultReg(RC);
459  const MCInstrDesc &II = TII.get(MachineInstOpcode);
460
461  if (II.getNumDefs() >= 1) {
462    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
463                    .addImm(Imm1).addImm(Imm2));
464  } else {
465    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
466                    .addImm(Imm1).addImm(Imm2));
467    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
468                            TII.get(TargetOpcode::COPY),
469                            ResultReg)
470                    .addReg(II.ImplicitDefs[0]));
471  }
472  return ResultReg;
473}
474
475unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
476                                                 unsigned Op0, bool Op0IsKill,
477                                                 uint32_t Idx) {
478  unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
479  assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
480         "Cannot yet extract from physregs");
481
482  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
483                          DL, TII.get(TargetOpcode::COPY), ResultReg)
484                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
485  return ResultReg;
486}
487
488// TODO: Don't worry about 64-bit now, but when this is fixed remove the
489// checks from the various callers.
490unsigned ARMFastISel::ARMMoveToFPReg(MVT VT, unsigned SrcReg) {
491  if (VT == MVT::f64) return 0;
492
493  unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
494  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
495                          TII.get(ARM::VMOVSR), MoveReg)
496                  .addReg(SrcReg));
497  return MoveReg;
498}
499
500unsigned ARMFastISel::ARMMoveToIntReg(MVT VT, unsigned SrcReg) {
501  if (VT == MVT::i64) return 0;
502
503  unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
504  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
505                          TII.get(ARM::VMOVRS), MoveReg)
506                  .addReg(SrcReg));
507  return MoveReg;
508}
509
510// For double width floating point we need to materialize two constants
511// (the high and the low) into integer registers then use a move to get
512// the combined constant into an FP reg.
513unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, MVT VT) {
514  const APFloat Val = CFP->getValueAPF();
515  bool is64bit = VT == MVT::f64;
516
517  // This checks to see if we can use VFP3 instructions to materialize
518  // a constant, otherwise we have to go through the constant pool.
519  if (TLI.isFPImmLegal(Val, VT)) {
520    int Imm;
521    unsigned Opc;
522    if (is64bit) {
523      Imm = ARM_AM::getFP64Imm(Val);
524      Opc = ARM::FCONSTD;
525    } else {
526      Imm = ARM_AM::getFP32Imm(Val);
527      Opc = ARM::FCONSTS;
528    }
529    unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
530    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
531                            DestReg)
532                    .addImm(Imm));
533    return DestReg;
534  }
535
536  // Require VFP2 for loading fp constants.
537  if (!Subtarget->hasVFP2()) return false;
538
539  // MachineConstantPool wants an explicit alignment.
540  unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
541  if (Align == 0) {
542    // TODO: Figure out if this is correct.
543    Align = TD.getTypeAllocSize(CFP->getType());
544  }
545  unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
546  unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
547  unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
548
549  // The extra reg is for addrmode5.
550  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
551                          DestReg)
552                  .addConstantPoolIndex(Idx)
553                  .addReg(0));
554  return DestReg;
555}
556
557unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, MVT VT) {
558
559  if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
560    return false;
561
562  // If we can do this in a single instruction without a constant pool entry
563  // do so now.
564  const ConstantInt *CI = cast<ConstantInt>(C);
565  if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
566    unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
567    const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
568      &ARM::GPRRegClass;
569    unsigned ImmReg = createResultReg(RC);
570    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
571                            TII.get(Opc), ImmReg)
572                    .addImm(CI->getZExtValue()));
573    return ImmReg;
574  }
575
576  // Use MVN to emit negative constants.
577  if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
578    unsigned Imm = (unsigned)~(CI->getSExtValue());
579    bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
580      (ARM_AM::getSOImmVal(Imm) != -1);
581    if (UseImm) {
582      unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
583      unsigned ImmReg = createResultReg(TLI.getRegClassFor(MVT::i32));
584      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
585                              TII.get(Opc), ImmReg)
586                      .addImm(Imm));
587      return ImmReg;
588    }
589  }
590
591  // Load from constant pool.  For now 32-bit only.
592  if (VT != MVT::i32)
593    return false;
594
595  unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
596
597  // MachineConstantPool wants an explicit alignment.
598  unsigned Align = TD.getPrefTypeAlignment(C->getType());
599  if (Align == 0) {
600    // TODO: Figure out if this is correct.
601    Align = TD.getTypeAllocSize(C->getType());
602  }
603  unsigned Idx = MCP.getConstantPoolIndex(C, Align);
604
605  if (isThumb2)
606    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
607                            TII.get(ARM::t2LDRpci), DestReg)
608                    .addConstantPoolIndex(Idx));
609  else
610    // The extra immediate is for addrmode2.
611    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
612                            TII.get(ARM::LDRcp), DestReg)
613                    .addConstantPoolIndex(Idx)
614                    .addImm(0));
615
616  return DestReg;
617}
618
619unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, MVT VT) {
620  // For now 32-bit only.
621  if (VT != MVT::i32) return 0;
622
623  Reloc::Model RelocM = TM.getRelocationModel();
624  bool IsIndirect = Subtarget->GVIsIndirectSymbol(GV, RelocM);
625  const TargetRegisterClass *RC = isThumb2 ?
626    (const TargetRegisterClass*)&ARM::rGPRRegClass :
627    (const TargetRegisterClass*)&ARM::GPRRegClass;
628  unsigned DestReg = createResultReg(RC);
629
630  // Use movw+movt when possible, it avoids constant pool entries.
631  // Darwin targets don't support movt with Reloc::Static, see
632  // ARMTargetLowering::LowerGlobalAddressDarwin.  Other targets only support
633  // static movt relocations.
634  if (Subtarget->useMovt() &&
635      Subtarget->isTargetDarwin() == (RelocM != Reloc::Static)) {
636    unsigned Opc;
637    switch (RelocM) {
638    case Reloc::PIC_:
639      Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
640      break;
641    case Reloc::DynamicNoPIC:
642      Opc = isThumb2 ? ARM::t2MOV_ga_dyn : ARM::MOV_ga_dyn;
643      break;
644    default:
645      Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
646      break;
647    }
648    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
649                            DestReg).addGlobalAddress(GV));
650  } else {
651    // MachineConstantPool wants an explicit alignment.
652    unsigned Align = TD.getPrefTypeAlignment(GV->getType());
653    if (Align == 0) {
654      // TODO: Figure out if this is correct.
655      Align = TD.getTypeAllocSize(GV->getType());
656    }
657
658    if (Subtarget->isTargetELF() && RelocM == Reloc::PIC_)
659      return ARMLowerPICELF(GV, Align, VT);
660
661    // Grab index.
662    unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 :
663      (Subtarget->isThumb() ? 4 : 8);
664    unsigned Id = AFI->createPICLabelUId();
665    ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
666                                                                ARMCP::CPValue,
667                                                                PCAdj);
668    unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
669
670    // Load value.
671    MachineInstrBuilder MIB;
672    if (isThumb2) {
673      unsigned Opc = (RelocM!=Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
674      MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
675        .addConstantPoolIndex(Idx);
676      if (RelocM == Reloc::PIC_)
677        MIB.addImm(Id);
678      AddOptionalDefs(MIB);
679    } else {
680      // The extra immediate is for addrmode2.
681      MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
682                    DestReg)
683        .addConstantPoolIndex(Idx)
684        .addImm(0);
685      AddOptionalDefs(MIB);
686
687      if (RelocM == Reloc::PIC_) {
688        unsigned Opc = IsIndirect ? ARM::PICLDR : ARM::PICADD;
689        unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
690
691        MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
692                                          DL, TII.get(Opc), NewDestReg)
693                                  .addReg(DestReg)
694                                  .addImm(Id);
695        AddOptionalDefs(MIB);
696        return NewDestReg;
697      }
698    }
699  }
700
701  if (IsIndirect) {
702    MachineInstrBuilder MIB;
703    unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
704    if (isThumb2)
705      MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
706                    TII.get(ARM::t2LDRi12), NewDestReg)
707            .addReg(DestReg)
708            .addImm(0);
709    else
710      MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRi12),
711                    NewDestReg)
712            .addReg(DestReg)
713            .addImm(0);
714    DestReg = NewDestReg;
715    AddOptionalDefs(MIB);
716  }
717
718  return DestReg;
719}
720
721unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
722  EVT CEVT = TLI.getValueType(C->getType(), true);
723
724  // Only handle simple types.
725  if (!CEVT.isSimple()) return 0;
726  MVT VT = CEVT.getSimpleVT();
727
728  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
729    return ARMMaterializeFP(CFP, VT);
730  else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
731    return ARMMaterializeGV(GV, VT);
732  else if (isa<ConstantInt>(C))
733    return ARMMaterializeInt(C, VT);
734
735  return 0;
736}
737
738// TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
739
740unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
741  // Don't handle dynamic allocas.
742  if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
743
744  MVT VT;
745  if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
746
747  DenseMap<const AllocaInst*, int>::iterator SI =
748    FuncInfo.StaticAllocaMap.find(AI);
749
750  // This will get lowered later into the correct offsets and registers
751  // via rewriteXFrameIndex.
752  if (SI != FuncInfo.StaticAllocaMap.end()) {
753    const TargetRegisterClass* RC = TLI.getRegClassFor(VT);
754    unsigned ResultReg = createResultReg(RC);
755    unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
756    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
757                            TII.get(Opc), ResultReg)
758                            .addFrameIndex(SI->second)
759                            .addImm(0));
760    return ResultReg;
761  }
762
763  return 0;
764}
765
766bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
767  EVT evt = TLI.getValueType(Ty, true);
768
769  // Only handle simple types.
770  if (evt == MVT::Other || !evt.isSimple()) return false;
771  VT = evt.getSimpleVT();
772
773  // Handle all legal types, i.e. a register that will directly hold this
774  // value.
775  return TLI.isTypeLegal(VT);
776}
777
778bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
779  if (isTypeLegal(Ty, VT)) return true;
780
781  // If this is a type than can be sign or zero-extended to a basic operation
782  // go ahead and accept it now.
783  if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
784    return true;
785
786  return false;
787}
788
789// Computes the address to get to an object.
790bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
791  // Some boilerplate from the X86 FastISel.
792  const User *U = NULL;
793  unsigned Opcode = Instruction::UserOp1;
794  if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
795    // Don't walk into other basic blocks unless the object is an alloca from
796    // another block, otherwise it may not have a virtual register assigned.
797    if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
798        FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
799      Opcode = I->getOpcode();
800      U = I;
801    }
802  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
803    Opcode = C->getOpcode();
804    U = C;
805  }
806
807  if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
808    if (Ty->getAddressSpace() > 255)
809      // Fast instruction selection doesn't support the special
810      // address spaces.
811      return false;
812
813  switch (Opcode) {
814    default:
815    break;
816    case Instruction::BitCast: {
817      // Look through bitcasts.
818      return ARMComputeAddress(U->getOperand(0), Addr);
819    }
820    case Instruction::IntToPtr: {
821      // Look past no-op inttoptrs.
822      if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
823        return ARMComputeAddress(U->getOperand(0), Addr);
824      break;
825    }
826    case Instruction::PtrToInt: {
827      // Look past no-op ptrtoints.
828      if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
829        return ARMComputeAddress(U->getOperand(0), Addr);
830      break;
831    }
832    case Instruction::GetElementPtr: {
833      Address SavedAddr = Addr;
834      int TmpOffset = Addr.Offset;
835
836      // Iterate through the GEP folding the constants into offsets where
837      // we can.
838      gep_type_iterator GTI = gep_type_begin(U);
839      for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
840           i != e; ++i, ++GTI) {
841        const Value *Op = *i;
842        if (StructType *STy = dyn_cast<StructType>(*GTI)) {
843          const StructLayout *SL = TD.getStructLayout(STy);
844          unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
845          TmpOffset += SL->getElementOffset(Idx);
846        } else {
847          uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
848          for (;;) {
849            if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
850              // Constant-offset addressing.
851              TmpOffset += CI->getSExtValue() * S;
852              break;
853            }
854            if (isa<AddOperator>(Op) &&
855                (!isa<Instruction>(Op) ||
856                 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
857                 == FuncInfo.MBB) &&
858                isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
859              // An add (in the same block) with a constant operand. Fold the
860              // constant.
861              ConstantInt *CI =
862              cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
863              TmpOffset += CI->getSExtValue() * S;
864              // Iterate on the other operand.
865              Op = cast<AddOperator>(Op)->getOperand(0);
866              continue;
867            }
868            // Unsupported
869            goto unsupported_gep;
870          }
871        }
872      }
873
874      // Try to grab the base operand now.
875      Addr.Offset = TmpOffset;
876      if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
877
878      // We failed, restore everything and try the other options.
879      Addr = SavedAddr;
880
881      unsupported_gep:
882      break;
883    }
884    case Instruction::Alloca: {
885      const AllocaInst *AI = cast<AllocaInst>(Obj);
886      DenseMap<const AllocaInst*, int>::iterator SI =
887        FuncInfo.StaticAllocaMap.find(AI);
888      if (SI != FuncInfo.StaticAllocaMap.end()) {
889        Addr.BaseType = Address::FrameIndexBase;
890        Addr.Base.FI = SI->second;
891        return true;
892      }
893      break;
894    }
895  }
896
897  // Try to get this in a register if nothing else has worked.
898  if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
899  return Addr.Base.Reg != 0;
900}
901
902void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3) {
903
904  assert(VT.isSimple() && "Non-simple types are invalid here!");
905
906  bool needsLowering = false;
907  switch (VT.getSimpleVT().SimpleTy) {
908    default: llvm_unreachable("Unhandled load/store type!");
909    case MVT::i1:
910    case MVT::i8:
911    case MVT::i16:
912    case MVT::i32:
913      if (!useAM3) {
914        // Integer loads/stores handle 12-bit offsets.
915        needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
916        // Handle negative offsets.
917        if (needsLowering && isThumb2)
918          needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
919                            Addr.Offset > -256);
920      } else {
921        // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
922        needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
923      }
924      break;
925    case MVT::f32:
926    case MVT::f64:
927      // Floating point operands handle 8-bit offsets.
928      needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
929      break;
930  }
931
932  // If this is a stack pointer and the offset needs to be simplified then
933  // put the alloca address into a register, set the base type back to
934  // register and continue. This should almost never happen.
935  if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
936    const TargetRegisterClass *RC = isThumb2 ?
937      (const TargetRegisterClass*)&ARM::tGPRRegClass :
938      (const TargetRegisterClass*)&ARM::GPRRegClass;
939    unsigned ResultReg = createResultReg(RC);
940    unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
941    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
942                            TII.get(Opc), ResultReg)
943                            .addFrameIndex(Addr.Base.FI)
944                            .addImm(0));
945    Addr.Base.Reg = ResultReg;
946    Addr.BaseType = Address::RegBase;
947  }
948
949  // Since the offset is too large for the load/store instruction
950  // get the reg+offset into a register.
951  if (needsLowering) {
952    Addr.Base.Reg = FastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
953                                 /*Op0IsKill*/false, Addr.Offset, MVT::i32);
954    Addr.Offset = 0;
955  }
956}
957
958void ARMFastISel::AddLoadStoreOperands(EVT VT, Address &Addr,
959                                       const MachineInstrBuilder &MIB,
960                                       unsigned Flags, bool useAM3) {
961  // addrmode5 output depends on the selection dag addressing dividing the
962  // offset by 4 that it then later multiplies. Do this here as well.
963  if (VT.getSimpleVT().SimpleTy == MVT::f32 ||
964      VT.getSimpleVT().SimpleTy == MVT::f64)
965    Addr.Offset /= 4;
966
967  // Frame base works a bit differently. Handle it separately.
968  if (Addr.BaseType == Address::FrameIndexBase) {
969    int FI = Addr.Base.FI;
970    int Offset = Addr.Offset;
971    MachineMemOperand *MMO =
972          FuncInfo.MF->getMachineMemOperand(
973                                  MachinePointerInfo::getFixedStack(FI, Offset),
974                                  Flags,
975                                  MFI.getObjectSize(FI),
976                                  MFI.getObjectAlignment(FI));
977    // Now add the rest of the operands.
978    MIB.addFrameIndex(FI);
979
980    // ARM halfword load/stores and signed byte loads need an additional
981    // operand.
982    if (useAM3) {
983      signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
984      MIB.addReg(0);
985      MIB.addImm(Imm);
986    } else {
987      MIB.addImm(Addr.Offset);
988    }
989    MIB.addMemOperand(MMO);
990  } else {
991    // Now add the rest of the operands.
992    MIB.addReg(Addr.Base.Reg);
993
994    // ARM halfword load/stores and signed byte loads need an additional
995    // operand.
996    if (useAM3) {
997      signed Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
998      MIB.addReg(0);
999      MIB.addImm(Imm);
1000    } else {
1001      MIB.addImm(Addr.Offset);
1002    }
1003  }
1004  AddOptionalDefs(MIB);
1005}
1006
1007bool ARMFastISel::ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
1008                              unsigned Alignment, bool isZExt, bool allocReg) {
1009  unsigned Opc;
1010  bool useAM3 = false;
1011  bool needVMOV = false;
1012  const TargetRegisterClass *RC;
1013  switch (VT.SimpleTy) {
1014    // This is mostly going to be Neon/vector support.
1015    default: return false;
1016    case MVT::i1:
1017    case MVT::i8:
1018      if (isThumb2) {
1019        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1020          Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
1021        else
1022          Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
1023      } else {
1024        if (isZExt) {
1025          Opc = ARM::LDRBi12;
1026        } else {
1027          Opc = ARM::LDRSB;
1028          useAM3 = true;
1029        }
1030      }
1031      RC = &ARM::GPRRegClass;
1032      break;
1033    case MVT::i16:
1034      if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1035        return false;
1036
1037      if (isThumb2) {
1038        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1039          Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
1040        else
1041          Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
1042      } else {
1043        Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
1044        useAM3 = true;
1045      }
1046      RC = &ARM::GPRRegClass;
1047      break;
1048    case MVT::i32:
1049      if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1050        return false;
1051
1052      if (isThumb2) {
1053        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1054          Opc = ARM::t2LDRi8;
1055        else
1056          Opc = ARM::t2LDRi12;
1057      } else {
1058        Opc = ARM::LDRi12;
1059      }
1060      RC = &ARM::GPRRegClass;
1061      break;
1062    case MVT::f32:
1063      if (!Subtarget->hasVFP2()) return false;
1064      // Unaligned loads need special handling. Floats require word-alignment.
1065      if (Alignment && Alignment < 4) {
1066        needVMOV = true;
1067        VT = MVT::i32;
1068        Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
1069        RC = &ARM::GPRRegClass;
1070      } else {
1071        Opc = ARM::VLDRS;
1072        RC = TLI.getRegClassFor(VT);
1073      }
1074      break;
1075    case MVT::f64:
1076      if (!Subtarget->hasVFP2()) return false;
1077      // FIXME: Unaligned loads need special handling.  Doublewords require
1078      // word-alignment.
1079      if (Alignment && Alignment < 4)
1080        return false;
1081
1082      Opc = ARM::VLDRD;
1083      RC = TLI.getRegClassFor(VT);
1084      break;
1085  }
1086  // Simplify this down to something we can handle.
1087  ARMSimplifyAddress(Addr, VT, useAM3);
1088
1089  // Create the base instruction, then add the operands.
1090  if (allocReg)
1091    ResultReg = createResultReg(RC);
1092  assert (ResultReg > 255 && "Expected an allocated virtual register.");
1093  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1094                                    TII.get(Opc), ResultReg);
1095  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1096
1097  // If we had an unaligned load of a float we've converted it to an regular
1098  // load.  Now we must move from the GRP to the FP register.
1099  if (needVMOV) {
1100    unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1101    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1102                            TII.get(ARM::VMOVSR), MoveReg)
1103                    .addReg(ResultReg));
1104    ResultReg = MoveReg;
1105  }
1106  return true;
1107}
1108
1109bool ARMFastISel::SelectLoad(const Instruction *I) {
1110  // Atomic loads need special handling.
1111  if (cast<LoadInst>(I)->isAtomic())
1112    return false;
1113
1114  // Verify we have a legal type before going any further.
1115  MVT VT;
1116  if (!isLoadTypeLegal(I->getType(), VT))
1117    return false;
1118
1119  // See if we can handle this address.
1120  Address Addr;
1121  if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1122
1123  unsigned ResultReg;
1124  if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1125    return false;
1126  UpdateValueMap(I, ResultReg);
1127  return true;
1128}
1129
1130bool ARMFastISel::ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
1131                               unsigned Alignment) {
1132  unsigned StrOpc;
1133  bool useAM3 = false;
1134  switch (VT.SimpleTy) {
1135    // This is mostly going to be Neon/vector support.
1136    default: return false;
1137    case MVT::i1: {
1138      unsigned Res = createResultReg(isThumb2 ?
1139        (const TargetRegisterClass*)&ARM::tGPRRegClass :
1140        (const TargetRegisterClass*)&ARM::GPRRegClass);
1141      unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1142      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1143                              TII.get(Opc), Res)
1144                      .addReg(SrcReg).addImm(1));
1145      SrcReg = Res;
1146    } // Fallthrough here.
1147    case MVT::i8:
1148      if (isThumb2) {
1149        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1150          StrOpc = ARM::t2STRBi8;
1151        else
1152          StrOpc = ARM::t2STRBi12;
1153      } else {
1154        StrOpc = ARM::STRBi12;
1155      }
1156      break;
1157    case MVT::i16:
1158      if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1159        return false;
1160
1161      if (isThumb2) {
1162        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1163          StrOpc = ARM::t2STRHi8;
1164        else
1165          StrOpc = ARM::t2STRHi12;
1166      } else {
1167        StrOpc = ARM::STRH;
1168        useAM3 = true;
1169      }
1170      break;
1171    case MVT::i32:
1172      if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1173        return false;
1174
1175      if (isThumb2) {
1176        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1177          StrOpc = ARM::t2STRi8;
1178        else
1179          StrOpc = ARM::t2STRi12;
1180      } else {
1181        StrOpc = ARM::STRi12;
1182      }
1183      break;
1184    case MVT::f32:
1185      if (!Subtarget->hasVFP2()) return false;
1186      // Unaligned stores need special handling. Floats require word-alignment.
1187      if (Alignment && Alignment < 4) {
1188        unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1189        AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1190                                TII.get(ARM::VMOVRS), MoveReg)
1191                        .addReg(SrcReg));
1192        SrcReg = MoveReg;
1193        VT = MVT::i32;
1194        StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1195      } else {
1196        StrOpc = ARM::VSTRS;
1197      }
1198      break;
1199    case MVT::f64:
1200      if (!Subtarget->hasVFP2()) return false;
1201      // FIXME: Unaligned stores need special handling.  Doublewords require
1202      // word-alignment.
1203      if (Alignment && Alignment < 4)
1204          return false;
1205
1206      StrOpc = ARM::VSTRD;
1207      break;
1208  }
1209  // Simplify this down to something we can handle.
1210  ARMSimplifyAddress(Addr, VT, useAM3);
1211
1212  // Create the base instruction, then add the operands.
1213  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1214                                    TII.get(StrOpc))
1215                            .addReg(SrcReg);
1216  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1217  return true;
1218}
1219
1220bool ARMFastISel::SelectStore(const Instruction *I) {
1221  Value *Op0 = I->getOperand(0);
1222  unsigned SrcReg = 0;
1223
1224  // Atomic stores need special handling.
1225  if (cast<StoreInst>(I)->isAtomic())
1226    return false;
1227
1228  // Verify we have a legal type before going any further.
1229  MVT VT;
1230  if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1231    return false;
1232
1233  // Get the value to be stored into a register.
1234  SrcReg = getRegForValue(Op0);
1235  if (SrcReg == 0) return false;
1236
1237  // See if we can handle this address.
1238  Address Addr;
1239  if (!ARMComputeAddress(I->getOperand(1), Addr))
1240    return false;
1241
1242  if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1243    return false;
1244  return true;
1245}
1246
1247static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1248  switch (Pred) {
1249    // Needs two compares...
1250    case CmpInst::FCMP_ONE:
1251    case CmpInst::FCMP_UEQ:
1252    default:
1253      // AL is our "false" for now. The other two need more compares.
1254      return ARMCC::AL;
1255    case CmpInst::ICMP_EQ:
1256    case CmpInst::FCMP_OEQ:
1257      return ARMCC::EQ;
1258    case CmpInst::ICMP_SGT:
1259    case CmpInst::FCMP_OGT:
1260      return ARMCC::GT;
1261    case CmpInst::ICMP_SGE:
1262    case CmpInst::FCMP_OGE:
1263      return ARMCC::GE;
1264    case CmpInst::ICMP_UGT:
1265    case CmpInst::FCMP_UGT:
1266      return ARMCC::HI;
1267    case CmpInst::FCMP_OLT:
1268      return ARMCC::MI;
1269    case CmpInst::ICMP_ULE:
1270    case CmpInst::FCMP_OLE:
1271      return ARMCC::LS;
1272    case CmpInst::FCMP_ORD:
1273      return ARMCC::VC;
1274    case CmpInst::FCMP_UNO:
1275      return ARMCC::VS;
1276    case CmpInst::FCMP_UGE:
1277      return ARMCC::PL;
1278    case CmpInst::ICMP_SLT:
1279    case CmpInst::FCMP_ULT:
1280      return ARMCC::LT;
1281    case CmpInst::ICMP_SLE:
1282    case CmpInst::FCMP_ULE:
1283      return ARMCC::LE;
1284    case CmpInst::FCMP_UNE:
1285    case CmpInst::ICMP_NE:
1286      return ARMCC::NE;
1287    case CmpInst::ICMP_UGE:
1288      return ARMCC::HS;
1289    case CmpInst::ICMP_ULT:
1290      return ARMCC::LO;
1291  }
1292}
1293
1294bool ARMFastISel::SelectBranch(const Instruction *I) {
1295  const BranchInst *BI = cast<BranchInst>(I);
1296  MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1297  MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1298
1299  // Simple branch support.
1300
1301  // If we can, avoid recomputing the compare - redoing it could lead to wonky
1302  // behavior.
1303  if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1304    if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1305
1306      // Get the compare predicate.
1307      // Try to take advantage of fallthrough opportunities.
1308      CmpInst::Predicate Predicate = CI->getPredicate();
1309      if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1310        std::swap(TBB, FBB);
1311        Predicate = CmpInst::getInversePredicate(Predicate);
1312      }
1313
1314      ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1315
1316      // We may not handle every CC for now.
1317      if (ARMPred == ARMCC::AL) return false;
1318
1319      // Emit the compare.
1320      if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1321        return false;
1322
1323      unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1324      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1325      .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1326      FastEmitBranch(FBB, DL);
1327      FuncInfo.MBB->addSuccessor(TBB);
1328      return true;
1329    }
1330  } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1331    MVT SourceVT;
1332    if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1333        (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1334      unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1335      unsigned OpReg = getRegForValue(TI->getOperand(0));
1336      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1337                              TII.get(TstOpc))
1338                      .addReg(OpReg).addImm(1));
1339
1340      unsigned CCMode = ARMCC::NE;
1341      if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1342        std::swap(TBB, FBB);
1343        CCMode = ARMCC::EQ;
1344      }
1345
1346      unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1347      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1348      .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1349
1350      FastEmitBranch(FBB, DL);
1351      FuncInfo.MBB->addSuccessor(TBB);
1352      return true;
1353    }
1354  } else if (const ConstantInt *CI =
1355             dyn_cast<ConstantInt>(BI->getCondition())) {
1356    uint64_t Imm = CI->getZExtValue();
1357    MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1358    FastEmitBranch(Target, DL);
1359    return true;
1360  }
1361
1362  unsigned CmpReg = getRegForValue(BI->getCondition());
1363  if (CmpReg == 0) return false;
1364
1365  // We've been divorced from our compare!  Our block was split, and
1366  // now our compare lives in a predecessor block.  We musn't
1367  // re-compare here, as the children of the compare aren't guaranteed
1368  // live across the block boundary (we *could* check for this).
1369  // Regardless, the compare has been done in the predecessor block,
1370  // and it left a value for us in a virtual register.  Ergo, we test
1371  // the one-bit value left in the virtual register.
1372  unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1373  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TstOpc))
1374                  .addReg(CmpReg).addImm(1));
1375
1376  unsigned CCMode = ARMCC::NE;
1377  if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1378    std::swap(TBB, FBB);
1379    CCMode = ARMCC::EQ;
1380  }
1381
1382  unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1383  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1384                  .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1385  FastEmitBranch(FBB, DL);
1386  FuncInfo.MBB->addSuccessor(TBB);
1387  return true;
1388}
1389
1390bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
1391  unsigned AddrReg = getRegForValue(I->getOperand(0));
1392  if (AddrReg == 0) return false;
1393
1394  unsigned Opc = isThumb2 ? ARM::tBRIND : ARM::BX;
1395  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc))
1396                  .addReg(AddrReg));
1397
1398  const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1399  for (unsigned i = 0, e = IB->getNumSuccessors(); i != e; ++i)
1400    FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[IB->getSuccessor(i)]);
1401
1402  return true;
1403}
1404
1405bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1406                             bool isZExt) {
1407  Type *Ty = Src1Value->getType();
1408  EVT SrcEVT = TLI.getValueType(Ty, true);
1409  if (!SrcEVT.isSimple()) return false;
1410  MVT SrcVT = SrcEVT.getSimpleVT();
1411
1412  bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1413  if (isFloat && !Subtarget->hasVFP2())
1414    return false;
1415
1416  // Check to see if the 2nd operand is a constant that we can encode directly
1417  // in the compare.
1418  int Imm = 0;
1419  bool UseImm = false;
1420  bool isNegativeImm = false;
1421  // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1422  // Thus, Src1Value may be a ConstantInt, but we're missing it.
1423  if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1424    if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1425        SrcVT == MVT::i1) {
1426      const APInt &CIVal = ConstInt->getValue();
1427      Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1428      // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rather
1429      // then a cmn, because there is no way to represent 2147483648 as a
1430      // signed 32-bit int.
1431      if (Imm < 0 && Imm != (int)0x80000000) {
1432        isNegativeImm = true;
1433        Imm = -Imm;
1434      }
1435      UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1436        (ARM_AM::getSOImmVal(Imm) != -1);
1437    }
1438  } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1439    if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1440      if (ConstFP->isZero() && !ConstFP->isNegative())
1441        UseImm = true;
1442  }
1443
1444  unsigned CmpOpc;
1445  bool isICmp = true;
1446  bool needsExt = false;
1447  switch (SrcVT.SimpleTy) {
1448    default: return false;
1449    // TODO: Verify compares.
1450    case MVT::f32:
1451      isICmp = false;
1452      CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1453      break;
1454    case MVT::f64:
1455      isICmp = false;
1456      CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1457      break;
1458    case MVT::i1:
1459    case MVT::i8:
1460    case MVT::i16:
1461      needsExt = true;
1462    // Intentional fall-through.
1463    case MVT::i32:
1464      if (isThumb2) {
1465        if (!UseImm)
1466          CmpOpc = ARM::t2CMPrr;
1467        else
1468          CmpOpc = isNegativeImm ? ARM::t2CMNri : ARM::t2CMPri;
1469      } else {
1470        if (!UseImm)
1471          CmpOpc = ARM::CMPrr;
1472        else
1473          CmpOpc = isNegativeImm ? ARM::CMNri : ARM::CMPri;
1474      }
1475      break;
1476  }
1477
1478  unsigned SrcReg1 = getRegForValue(Src1Value);
1479  if (SrcReg1 == 0) return false;
1480
1481  unsigned SrcReg2 = 0;
1482  if (!UseImm) {
1483    SrcReg2 = getRegForValue(Src2Value);
1484    if (SrcReg2 == 0) return false;
1485  }
1486
1487  // We have i1, i8, or i16, we need to either zero extend or sign extend.
1488  if (needsExt) {
1489    SrcReg1 = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1490    if (SrcReg1 == 0) return false;
1491    if (!UseImm) {
1492      SrcReg2 = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1493      if (SrcReg2 == 0) return false;
1494    }
1495  }
1496
1497  if (!UseImm) {
1498    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1499                            TII.get(CmpOpc))
1500                    .addReg(SrcReg1).addReg(SrcReg2));
1501  } else {
1502    MachineInstrBuilder MIB;
1503    MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1504      .addReg(SrcReg1);
1505
1506    // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1507    if (isICmp)
1508      MIB.addImm(Imm);
1509    AddOptionalDefs(MIB);
1510  }
1511
1512  // For floating point we need to move the result to a comparison register
1513  // that we can then use for branches.
1514  if (Ty->isFloatTy() || Ty->isDoubleTy())
1515    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1516                            TII.get(ARM::FMSTAT)));
1517  return true;
1518}
1519
1520bool ARMFastISel::SelectCmp(const Instruction *I) {
1521  const CmpInst *CI = cast<CmpInst>(I);
1522
1523  // Get the compare predicate.
1524  ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1525
1526  // We may not handle every CC for now.
1527  if (ARMPred == ARMCC::AL) return false;
1528
1529  // Emit the compare.
1530  if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1531    return false;
1532
1533  // Now set a register based on the comparison. Explicitly set the predicates
1534  // here.
1535  unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1536  const TargetRegisterClass *RC = isThumb2 ?
1537    (const TargetRegisterClass*)&ARM::rGPRRegClass :
1538    (const TargetRegisterClass*)&ARM::GPRRegClass;
1539  unsigned DestReg = createResultReg(RC);
1540  Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1541  unsigned ZeroReg = TargetMaterializeConstant(Zero);
1542  // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use CPSR.
1543  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1544          .addReg(ZeroReg).addImm(1)
1545          .addImm(ARMPred).addReg(ARM::CPSR);
1546
1547  UpdateValueMap(I, DestReg);
1548  return true;
1549}
1550
1551bool ARMFastISel::SelectFPExt(const Instruction *I) {
1552  // Make sure we have VFP and that we're extending float to double.
1553  if (!Subtarget->hasVFP2()) return false;
1554
1555  Value *V = I->getOperand(0);
1556  if (!I->getType()->isDoubleTy() ||
1557      !V->getType()->isFloatTy()) return false;
1558
1559  unsigned Op = getRegForValue(V);
1560  if (Op == 0) return false;
1561
1562  unsigned Result = createResultReg(&ARM::DPRRegClass);
1563  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1564                          TII.get(ARM::VCVTDS), Result)
1565                  .addReg(Op));
1566  UpdateValueMap(I, Result);
1567  return true;
1568}
1569
1570bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1571  // Make sure we have VFP and that we're truncating double to float.
1572  if (!Subtarget->hasVFP2()) return false;
1573
1574  Value *V = I->getOperand(0);
1575  if (!(I->getType()->isFloatTy() &&
1576        V->getType()->isDoubleTy())) return false;
1577
1578  unsigned Op = getRegForValue(V);
1579  if (Op == 0) return false;
1580
1581  unsigned Result = createResultReg(&ARM::SPRRegClass);
1582  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1583                          TII.get(ARM::VCVTSD), Result)
1584                  .addReg(Op));
1585  UpdateValueMap(I, Result);
1586  return true;
1587}
1588
1589bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1590  // Make sure we have VFP.
1591  if (!Subtarget->hasVFP2()) return false;
1592
1593  MVT DstVT;
1594  Type *Ty = I->getType();
1595  if (!isTypeLegal(Ty, DstVT))
1596    return false;
1597
1598  Value *Src = I->getOperand(0);
1599  EVT SrcEVT = TLI.getValueType(Src->getType(), true);
1600  if (!SrcEVT.isSimple())
1601    return false;
1602  MVT SrcVT = SrcEVT.getSimpleVT();
1603  if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1604    return false;
1605
1606  unsigned SrcReg = getRegForValue(Src);
1607  if (SrcReg == 0) return false;
1608
1609  // Handle sign-extension.
1610  if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1611    SrcReg = ARMEmitIntExt(SrcVT, SrcReg, MVT::i32,
1612                                       /*isZExt*/!isSigned);
1613    if (SrcReg == 0) return false;
1614  }
1615
1616  // The conversion routine works on fp-reg to fp-reg and the operand above
1617  // was an integer, move it to the fp registers if possible.
1618  unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1619  if (FP == 0) return false;
1620
1621  unsigned Opc;
1622  if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1623  else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1624  else return false;
1625
1626  unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1627  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1628                          ResultReg)
1629                  .addReg(FP));
1630  UpdateValueMap(I, ResultReg);
1631  return true;
1632}
1633
1634bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1635  // Make sure we have VFP.
1636  if (!Subtarget->hasVFP2()) return false;
1637
1638  MVT DstVT;
1639  Type *RetTy = I->getType();
1640  if (!isTypeLegal(RetTy, DstVT))
1641    return false;
1642
1643  unsigned Op = getRegForValue(I->getOperand(0));
1644  if (Op == 0) return false;
1645
1646  unsigned Opc;
1647  Type *OpTy = I->getOperand(0)->getType();
1648  if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1649  else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1650  else return false;
1651
1652  // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1653  unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1654  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1655                          ResultReg)
1656                  .addReg(Op));
1657
1658  // This result needs to be in an integer register, but the conversion only
1659  // takes place in fp-regs.
1660  unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1661  if (IntReg == 0) return false;
1662
1663  UpdateValueMap(I, IntReg);
1664  return true;
1665}
1666
1667bool ARMFastISel::SelectSelect(const Instruction *I) {
1668  MVT VT;
1669  if (!isTypeLegal(I->getType(), VT))
1670    return false;
1671
1672  // Things need to be register sized for register moves.
1673  if (VT != MVT::i32) return false;
1674
1675  unsigned CondReg = getRegForValue(I->getOperand(0));
1676  if (CondReg == 0) return false;
1677  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1678  if (Op1Reg == 0) return false;
1679
1680  // Check to see if we can use an immediate in the conditional move.
1681  int Imm = 0;
1682  bool UseImm = false;
1683  bool isNegativeImm = false;
1684  if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1685    assert (VT == MVT::i32 && "Expecting an i32.");
1686    Imm = (int)ConstInt->getValue().getZExtValue();
1687    if (Imm < 0) {
1688      isNegativeImm = true;
1689      Imm = ~Imm;
1690    }
1691    UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1692      (ARM_AM::getSOImmVal(Imm) != -1);
1693  }
1694
1695  unsigned Op2Reg = 0;
1696  if (!UseImm) {
1697    Op2Reg = getRegForValue(I->getOperand(2));
1698    if (Op2Reg == 0) return false;
1699  }
1700
1701  unsigned CmpOpc = isThumb2 ? ARM::t2CMPri : ARM::CMPri;
1702  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1703                  .addReg(CondReg).addImm(0));
1704
1705  unsigned MovCCOpc;
1706  const TargetRegisterClass *RC;
1707  if (!UseImm) {
1708    RC = isThumb2 ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
1709    MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1710  } else {
1711    RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
1712    if (!isNegativeImm)
1713      MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1714    else
1715      MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1716  }
1717  unsigned ResultReg = createResultReg(RC);
1718  if (!UseImm)
1719    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1720    .addReg(Op2Reg).addReg(Op1Reg).addImm(ARMCC::NE).addReg(ARM::CPSR);
1721  else
1722    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1723    .addReg(Op1Reg).addImm(Imm).addImm(ARMCC::EQ).addReg(ARM::CPSR);
1724  UpdateValueMap(I, ResultReg);
1725  return true;
1726}
1727
1728bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1729  MVT VT;
1730  Type *Ty = I->getType();
1731  if (!isTypeLegal(Ty, VT))
1732    return false;
1733
1734  // If we have integer div support we should have selected this automagically.
1735  // In case we have a real miss go ahead and return false and we'll pick
1736  // it up later.
1737  if (Subtarget->hasDivide()) return false;
1738
1739  // Otherwise emit a libcall.
1740  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1741  if (VT == MVT::i8)
1742    LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1743  else if (VT == MVT::i16)
1744    LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1745  else if (VT == MVT::i32)
1746    LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1747  else if (VT == MVT::i64)
1748    LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1749  else if (VT == MVT::i128)
1750    LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1751  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1752
1753  return ARMEmitLibcall(I, LC);
1754}
1755
1756bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1757  MVT VT;
1758  Type *Ty = I->getType();
1759  if (!isTypeLegal(Ty, VT))
1760    return false;
1761
1762  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1763  if (VT == MVT::i8)
1764    LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1765  else if (VT == MVT::i16)
1766    LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1767  else if (VT == MVT::i32)
1768    LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1769  else if (VT == MVT::i64)
1770    LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1771  else if (VT == MVT::i128)
1772    LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1773  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1774
1775  return ARMEmitLibcall(I, LC);
1776}
1777
1778bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1779  EVT DestVT  = TLI.getValueType(I->getType(), true);
1780
1781  // We can get here in the case when we have a binary operation on a non-legal
1782  // type and the target independent selector doesn't know how to handle it.
1783  if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1784    return false;
1785
1786  unsigned Opc;
1787  switch (ISDOpcode) {
1788    default: return false;
1789    case ISD::ADD:
1790      Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1791      break;
1792    case ISD::OR:
1793      Opc = isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
1794      break;
1795    case ISD::SUB:
1796      Opc = isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
1797      break;
1798  }
1799
1800  unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1801  if (SrcReg1 == 0) return false;
1802
1803  // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1804  // in the instruction, rather then materializing the value in a register.
1805  unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1806  if (SrcReg2 == 0) return false;
1807
1808  unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1809  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1810                          TII.get(Opc), ResultReg)
1811                  .addReg(SrcReg1).addReg(SrcReg2));
1812  UpdateValueMap(I, ResultReg);
1813  return true;
1814}
1815
1816bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1817  EVT FPVT = TLI.getValueType(I->getType(), true);
1818  if (!FPVT.isSimple()) return false;
1819  MVT VT = FPVT.getSimpleVT();
1820
1821  // We can get here in the case when we want to use NEON for our fp
1822  // operations, but can't figure out how to. Just use the vfp instructions
1823  // if we have them.
1824  // FIXME: It'd be nice to use NEON instructions.
1825  Type *Ty = I->getType();
1826  bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1827  if (isFloat && !Subtarget->hasVFP2())
1828    return false;
1829
1830  unsigned Opc;
1831  bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1832  switch (ISDOpcode) {
1833    default: return false;
1834    case ISD::FADD:
1835      Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1836      break;
1837    case ISD::FSUB:
1838      Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1839      break;
1840    case ISD::FMUL:
1841      Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1842      break;
1843  }
1844  unsigned Op1 = getRegForValue(I->getOperand(0));
1845  if (Op1 == 0) return false;
1846
1847  unsigned Op2 = getRegForValue(I->getOperand(1));
1848  if (Op2 == 0) return false;
1849
1850  unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
1851  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1852                          TII.get(Opc), ResultReg)
1853                  .addReg(Op1).addReg(Op2));
1854  UpdateValueMap(I, ResultReg);
1855  return true;
1856}
1857
1858// Call Handling Code
1859
1860// This is largely taken directly from CCAssignFnForNode
1861// TODO: We may not support all of this.
1862CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC,
1863                                           bool Return,
1864                                           bool isVarArg) {
1865  switch (CC) {
1866  default:
1867    llvm_unreachable("Unsupported calling convention");
1868  case CallingConv::Fast:
1869    if (Subtarget->hasVFP2() && !isVarArg) {
1870      if (!Subtarget->isAAPCS_ABI())
1871        return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1872      // For AAPCS ABI targets, just use VFP variant of the calling convention.
1873      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1874    }
1875    // Fallthrough
1876  case CallingConv::C:
1877    // Use target triple & subtarget features to do actual dispatch.
1878    if (Subtarget->isAAPCS_ABI()) {
1879      if (Subtarget->hasVFP2() &&
1880          TM.Options.FloatABIType == FloatABI::Hard && !isVarArg)
1881        return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1882      else
1883        return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1884    } else
1885        return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1886  case CallingConv::ARM_AAPCS_VFP:
1887    if (!isVarArg)
1888      return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1889    // Fall through to soft float variant, variadic functions don't
1890    // use hard floating point ABI.
1891  case CallingConv::ARM_AAPCS:
1892    return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1893  case CallingConv::ARM_APCS:
1894    return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1895  case CallingConv::GHC:
1896    if (Return)
1897      llvm_unreachable("Can't return in GHC call convention");
1898    else
1899      return CC_ARM_APCS_GHC;
1900  }
1901}
1902
1903bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1904                                  SmallVectorImpl<unsigned> &ArgRegs,
1905                                  SmallVectorImpl<MVT> &ArgVTs,
1906                                  SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1907                                  SmallVectorImpl<unsigned> &RegArgs,
1908                                  CallingConv::ID CC,
1909                                  unsigned &NumBytes,
1910                                  bool isVarArg) {
1911  SmallVector<CCValAssign, 16> ArgLocs;
1912  CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs, *Context);
1913  CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags,
1914                             CCAssignFnForCall(CC, false, isVarArg));
1915
1916  // Check that we can handle all of the arguments. If we can't, then bail out
1917  // now before we add code to the MBB.
1918  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1919    CCValAssign &VA = ArgLocs[i];
1920    MVT ArgVT = ArgVTs[VA.getValNo()];
1921
1922    // We don't handle NEON/vector parameters yet.
1923    if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1924      return false;
1925
1926    // Now copy/store arg to correct locations.
1927    if (VA.isRegLoc() && !VA.needsCustom()) {
1928      continue;
1929    } else if (VA.needsCustom()) {
1930      // TODO: We need custom lowering for vector (v2f64) args.
1931      if (VA.getLocVT() != MVT::f64 ||
1932          // TODO: Only handle register args for now.
1933          !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
1934        return false;
1935    } else {
1936      switch (static_cast<EVT>(ArgVT).getSimpleVT().SimpleTy) {
1937      default:
1938        return false;
1939      case MVT::i1:
1940      case MVT::i8:
1941      case MVT::i16:
1942      case MVT::i32:
1943        break;
1944      case MVT::f32:
1945        if (!Subtarget->hasVFP2())
1946          return false;
1947        break;
1948      case MVT::f64:
1949        if (!Subtarget->hasVFP2())
1950          return false;
1951        break;
1952      }
1953    }
1954  }
1955
1956  // At the point, we are able to handle the call's arguments in fast isel.
1957
1958  // Get a count of how many bytes are to be pushed on the stack.
1959  NumBytes = CCInfo.getNextStackOffset();
1960
1961  // Issue CALLSEQ_START
1962  unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1963  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1964                          TII.get(AdjStackDown))
1965                  .addImm(NumBytes));
1966
1967  // Process the args.
1968  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1969    CCValAssign &VA = ArgLocs[i];
1970    unsigned Arg = ArgRegs[VA.getValNo()];
1971    MVT ArgVT = ArgVTs[VA.getValNo()];
1972
1973    assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <= 64) &&
1974           "We don't handle NEON/vector parameters yet.");
1975
1976    // Handle arg promotion, etc.
1977    switch (VA.getLocInfo()) {
1978      case CCValAssign::Full: break;
1979      case CCValAssign::SExt: {
1980        MVT DestVT = VA.getLocVT();
1981        Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
1982        assert (Arg != 0 && "Failed to emit a sext");
1983        ArgVT = DestVT;
1984        break;
1985      }
1986      case CCValAssign::AExt:
1987        // Intentional fall-through.  Handle AExt and ZExt.
1988      case CCValAssign::ZExt: {
1989        MVT DestVT = VA.getLocVT();
1990        Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
1991        assert (Arg != 0 && "Failed to emit a sext");
1992        ArgVT = DestVT;
1993        break;
1994      }
1995      case CCValAssign::BCvt: {
1996        unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1997                                 /*TODO: Kill=*/false);
1998        assert(BC != 0 && "Failed to emit a bitcast!");
1999        Arg = BC;
2000        ArgVT = VA.getLocVT();
2001        break;
2002      }
2003      default: llvm_unreachable("Unknown arg promotion!");
2004    }
2005
2006    // Now copy/store arg to correct locations.
2007    if (VA.isRegLoc() && !VA.needsCustom()) {
2008      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2009              VA.getLocReg())
2010        .addReg(Arg);
2011      RegArgs.push_back(VA.getLocReg());
2012    } else if (VA.needsCustom()) {
2013      // TODO: We need custom lowering for vector (v2f64) args.
2014      assert(VA.getLocVT() == MVT::f64 &&
2015             "Custom lowering for v2f64 args not available");
2016
2017      CCValAssign &NextVA = ArgLocs[++i];
2018
2019      assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2020             "We only handle register args!");
2021
2022      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2023                              TII.get(ARM::VMOVRRD), VA.getLocReg())
2024                      .addReg(NextVA.getLocReg(), RegState::Define)
2025                      .addReg(Arg));
2026      RegArgs.push_back(VA.getLocReg());
2027      RegArgs.push_back(NextVA.getLocReg());
2028    } else {
2029      assert(VA.isMemLoc());
2030      // Need to store on the stack.
2031      Address Addr;
2032      Addr.BaseType = Address::RegBase;
2033      Addr.Base.Reg = ARM::SP;
2034      Addr.Offset = VA.getLocMemOffset();
2035
2036      bool EmitRet = ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
2037      assert(EmitRet && "Could not emit a store for argument!");
2038    }
2039  }
2040
2041  return true;
2042}
2043
2044bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
2045                             const Instruction *I, CallingConv::ID CC,
2046                             unsigned &NumBytes, bool isVarArg) {
2047  // Issue CALLSEQ_END
2048  unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2049  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2050                          TII.get(AdjStackUp))
2051                  .addImm(NumBytes).addImm(0));
2052
2053  // Now the return value.
2054  if (RetVT != MVT::isVoid) {
2055    SmallVector<CCValAssign, 16> RVLocs;
2056    CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
2057    CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2058
2059    // Copy all of the result registers out of their specified physreg.
2060    if (RVLocs.size() == 2 && RetVT == MVT::f64) {
2061      // For this move we copy into two registers and then move into the
2062      // double fp reg we want.
2063      MVT DestVT = RVLocs[0].getValVT();
2064      const TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
2065      unsigned ResultReg = createResultReg(DstRC);
2066      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2067                              TII.get(ARM::VMOVDRR), ResultReg)
2068                      .addReg(RVLocs[0].getLocReg())
2069                      .addReg(RVLocs[1].getLocReg()));
2070
2071      UsedRegs.push_back(RVLocs[0].getLocReg());
2072      UsedRegs.push_back(RVLocs[1].getLocReg());
2073
2074      // Finally update the result.
2075      UpdateValueMap(I, ResultReg);
2076    } else {
2077      assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
2078      MVT CopyVT = RVLocs[0].getValVT();
2079
2080      // Special handling for extended integers.
2081      if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
2082        CopyVT = MVT::i32;
2083
2084      const TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
2085
2086      unsigned ResultReg = createResultReg(DstRC);
2087      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2088              ResultReg).addReg(RVLocs[0].getLocReg());
2089      UsedRegs.push_back(RVLocs[0].getLocReg());
2090
2091      // Finally update the result.
2092      UpdateValueMap(I, ResultReg);
2093    }
2094  }
2095
2096  return true;
2097}
2098
2099bool ARMFastISel::SelectRet(const Instruction *I) {
2100  const ReturnInst *Ret = cast<ReturnInst>(I);
2101  const Function &F = *I->getParent()->getParent();
2102
2103  if (!FuncInfo.CanLowerReturn)
2104    return false;
2105
2106  CallingConv::ID CC = F.getCallingConv();
2107  if (Ret->getNumOperands() > 0) {
2108    SmallVector<ISD::OutputArg, 4> Outs;
2109    GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
2110                  Outs, TLI);
2111
2112    // Analyze operands of the call, assigning locations to each operand.
2113    SmallVector<CCValAssign, 16> ValLocs;
2114    CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,I->getContext());
2115    CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */,
2116                                                 F.isVarArg()));
2117
2118    const Value *RV = Ret->getOperand(0);
2119    unsigned Reg = getRegForValue(RV);
2120    if (Reg == 0)
2121      return false;
2122
2123    // Only handle a single return value for now.
2124    if (ValLocs.size() != 1)
2125      return false;
2126
2127    CCValAssign &VA = ValLocs[0];
2128
2129    // Don't bother handling odd stuff for now.
2130    if (VA.getLocInfo() != CCValAssign::Full)
2131      return false;
2132    // Only handle register returns for now.
2133    if (!VA.isRegLoc())
2134      return false;
2135
2136    unsigned SrcReg = Reg + VA.getValNo();
2137    EVT RVEVT = TLI.getValueType(RV->getType());
2138    if (!RVEVT.isSimple()) return false;
2139    MVT RVVT = RVEVT.getSimpleVT();
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      assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2147
2148      // Perform extension if flagged as either zext or sext.  Otherwise, do
2149      // nothing.
2150      if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
2151        SrcReg = ARMEmitIntExt(RVVT, SrcReg, DestVT, Outs[0].Flags.isZExt());
2152        if (SrcReg == 0) return false;
2153      }
2154    }
2155
2156    // Make the copy.
2157    unsigned DstReg = VA.getLocReg();
2158    const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
2159    // Avoid a cross-class copy. This is very unlikely.
2160    if (!SrcRC->contains(DstReg))
2161      return false;
2162    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2163            DstReg).addReg(SrcReg);
2164
2165    // Mark the register as live out of the function.
2166    MRI.addLiveOut(VA.getLocReg());
2167  }
2168
2169  unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2170  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2171                          TII.get(RetOpc)));
2172  return true;
2173}
2174
2175unsigned ARMFastISel::ARMSelectCallOp(bool UseReg) {
2176  if (UseReg)
2177    return isThumb2 ? ARM::tBLXr : ARM::BLX;
2178  else
2179    return isThumb2 ? ARM::tBL : ARM::BL;
2180}
2181
2182unsigned ARMFastISel::getLibcallReg(const Twine &Name) {
2183  GlobalValue *GV = new GlobalVariable(Type::getInt32Ty(*Context), false,
2184                                       GlobalValue::ExternalLinkage, 0, Name);
2185  EVT LCREVT = TLI.getValueType(GV->getType());
2186  if (!LCREVT.isSimple()) return 0;
2187  return ARMMaterializeGV(GV, LCREVT.getSimpleVT());
2188}
2189
2190// A quick function that will emit a call for a named libcall in F with the
2191// vector of passed arguments for the Instruction in I. We can assume that we
2192// can emit a call for any libcall we can produce. This is an abridged version
2193// of the full call infrastructure since we won't need to worry about things
2194// like computed function pointers or strange arguments at call sites.
2195// TODO: Try to unify this and the normal call bits for ARM, then try to unify
2196// with X86.
2197bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2198  CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2199
2200  // Handle *simple* calls for now.
2201  Type *RetTy = I->getType();
2202  MVT RetVT;
2203  if (RetTy->isVoidTy())
2204    RetVT = MVT::isVoid;
2205  else if (!isTypeLegal(RetTy, RetVT))
2206    return false;
2207
2208  // Can't handle non-double multi-reg retvals.
2209  if (RetVT != MVT::isVoid && RetVT != MVT::i32) {
2210    SmallVector<CCValAssign, 16> RVLocs;
2211    CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
2212    CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, false));
2213    if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2214      return false;
2215  }
2216
2217  // Set up the argument vectors.
2218  SmallVector<Value*, 8> Args;
2219  SmallVector<unsigned, 8> ArgRegs;
2220  SmallVector<MVT, 8> ArgVTs;
2221  SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2222  Args.reserve(I->getNumOperands());
2223  ArgRegs.reserve(I->getNumOperands());
2224  ArgVTs.reserve(I->getNumOperands());
2225  ArgFlags.reserve(I->getNumOperands());
2226  for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2227    Value *Op = I->getOperand(i);
2228    unsigned Arg = getRegForValue(Op);
2229    if (Arg == 0) return false;
2230
2231    Type *ArgTy = Op->getType();
2232    MVT ArgVT;
2233    if (!isTypeLegal(ArgTy, ArgVT)) return false;
2234
2235    ISD::ArgFlagsTy Flags;
2236    unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2237    Flags.setOrigAlign(OriginalAlignment);
2238
2239    Args.push_back(Op);
2240    ArgRegs.push_back(Arg);
2241    ArgVTs.push_back(ArgVT);
2242    ArgFlags.push_back(Flags);
2243  }
2244
2245  // Handle the arguments now that we've gotten them.
2246  SmallVector<unsigned, 4> RegArgs;
2247  unsigned NumBytes;
2248  if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2249                       RegArgs, CC, NumBytes, false))
2250    return false;
2251
2252  unsigned CalleeReg = 0;
2253  if (EnableARMLongCalls) {
2254    CalleeReg = getLibcallReg(TLI.getLibcallName(Call));
2255    if (CalleeReg == 0) return false;
2256  }
2257
2258  // Issue the call.
2259  unsigned CallOpc = ARMSelectCallOp(EnableARMLongCalls);
2260  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2261                                    DL, TII.get(CallOpc));
2262  // BL / BLX don't take a predicate, but tBL / tBLX do.
2263  if (isThumb2)
2264    AddDefaultPred(MIB);
2265  if (EnableARMLongCalls)
2266    MIB.addReg(CalleeReg);
2267  else
2268    MIB.addExternalSymbol(TLI.getLibcallName(Call));
2269
2270  // Add implicit physical register uses to the call.
2271  for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2272    MIB.addReg(RegArgs[i], RegState::Implicit);
2273
2274  // Add a register mask with the call-preserved registers.
2275  // Proper defs for return values will be added by setPhysRegsDeadExcept().
2276  MIB.addRegMask(TRI.getCallPreservedMask(CC));
2277
2278  // Finish off the call including any return values.
2279  SmallVector<unsigned, 4> UsedRegs;
2280  if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, false)) return false;
2281
2282  // Set all unused physreg defs as dead.
2283  static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2284
2285  return true;
2286}
2287
2288bool ARMFastISel::SelectCall(const Instruction *I,
2289                             const char *IntrMemName = 0) {
2290  const CallInst *CI = cast<CallInst>(I);
2291  const Value *Callee = CI->getCalledValue();
2292
2293  // Can't handle inline asm.
2294  if (isa<InlineAsm>(Callee)) return false;
2295
2296  // Allow SelectionDAG isel to handle tail calls.
2297  if (CI->isTailCall()) return false;
2298
2299  // Check the calling convention.
2300  ImmutableCallSite CS(CI);
2301  CallingConv::ID CC = CS.getCallingConv();
2302
2303  // TODO: Avoid some calling conventions?
2304
2305  PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
2306  FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2307  bool isVarArg = FTy->isVarArg();
2308
2309  // Handle *simple* calls for now.
2310  Type *RetTy = I->getType();
2311  MVT RetVT;
2312  if (RetTy->isVoidTy())
2313    RetVT = MVT::isVoid;
2314  else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2315           RetVT != MVT::i8  && RetVT != MVT::i1)
2316    return false;
2317
2318  // Can't handle non-double multi-reg retvals.
2319  if (RetVT != MVT::isVoid && RetVT != MVT::i1 && RetVT != MVT::i8 &&
2320      RetVT != MVT::i16 && RetVT != MVT::i32) {
2321    SmallVector<CCValAssign, 16> RVLocs;
2322    CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, RVLocs, *Context);
2323    CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2324    if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2325      return false;
2326  }
2327
2328  // Set up the argument vectors.
2329  SmallVector<Value*, 8> Args;
2330  SmallVector<unsigned, 8> ArgRegs;
2331  SmallVector<MVT, 8> ArgVTs;
2332  SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2333  unsigned arg_size = CS.arg_size();
2334  Args.reserve(arg_size);
2335  ArgRegs.reserve(arg_size);
2336  ArgVTs.reserve(arg_size);
2337  ArgFlags.reserve(arg_size);
2338  for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2339       i != e; ++i) {
2340    // If we're lowering a memory intrinsic instead of a regular call, skip the
2341    // last two arguments, which shouldn't be passed to the underlying function.
2342    if (IntrMemName && e-i <= 2)
2343      break;
2344
2345    ISD::ArgFlagsTy Flags;
2346    unsigned AttrInd = i - CS.arg_begin() + 1;
2347    if (CS.paramHasAttr(AttrInd, Attributes::SExt))
2348      Flags.setSExt();
2349    if (CS.paramHasAttr(AttrInd, Attributes::ZExt))
2350      Flags.setZExt();
2351
2352    // FIXME: Only handle *easy* calls for now.
2353    if (CS.paramHasAttr(AttrInd, Attributes::InReg) ||
2354        CS.paramHasAttr(AttrInd, Attributes::StructRet) ||
2355        CS.paramHasAttr(AttrInd, Attributes::Nest) ||
2356        CS.paramHasAttr(AttrInd, Attributes::ByVal))
2357      return false;
2358
2359    Type *ArgTy = (*i)->getType();
2360    MVT ArgVT;
2361    if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2362        ArgVT != MVT::i1)
2363      return false;
2364
2365    unsigned Arg = getRegForValue(*i);
2366    if (Arg == 0)
2367      return false;
2368
2369    unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
2370    Flags.setOrigAlign(OriginalAlignment);
2371
2372    Args.push_back(*i);
2373    ArgRegs.push_back(Arg);
2374    ArgVTs.push_back(ArgVT);
2375    ArgFlags.push_back(Flags);
2376  }
2377
2378  // Handle the arguments now that we've gotten them.
2379  SmallVector<unsigned, 4> RegArgs;
2380  unsigned NumBytes;
2381  if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2382                       RegArgs, CC, NumBytes, isVarArg))
2383    return false;
2384
2385  bool UseReg = false;
2386  const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2387  if (!GV || EnableARMLongCalls) UseReg = true;
2388
2389  unsigned CalleeReg = 0;
2390  if (UseReg) {
2391    if (IntrMemName)
2392      CalleeReg = getLibcallReg(IntrMemName);
2393    else
2394      CalleeReg = getRegForValue(Callee);
2395
2396    if (CalleeReg == 0) return false;
2397  }
2398
2399  // Issue the call.
2400  unsigned CallOpc = ARMSelectCallOp(UseReg);
2401  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2402                                    DL, TII.get(CallOpc));
2403
2404  // ARM calls don't take a predicate, but tBL / tBLX do.
2405  if(isThumb2)
2406    AddDefaultPred(MIB);
2407  if (UseReg)
2408    MIB.addReg(CalleeReg);
2409  else if (!IntrMemName)
2410    MIB.addGlobalAddress(GV, 0, 0);
2411  else
2412    MIB.addExternalSymbol(IntrMemName, 0);
2413
2414  // Add implicit physical register uses to the call.
2415  for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2416    MIB.addReg(RegArgs[i], RegState::Implicit);
2417
2418  // Add a register mask with the call-preserved registers.
2419  // Proper defs for return values will be added by setPhysRegsDeadExcept().
2420  MIB.addRegMask(TRI.getCallPreservedMask(CC));
2421
2422  // Finish off the call including any return values.
2423  SmallVector<unsigned, 4> UsedRegs;
2424  if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, isVarArg))
2425    return false;
2426
2427  // Set all unused physreg defs as dead.
2428  static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2429
2430  return true;
2431}
2432
2433bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2434  return Len <= 16;
2435}
2436
2437bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
2438                                        uint64_t Len, unsigned Alignment) {
2439  // Make sure we don't bloat code by inlining very large memcpy's.
2440  if (!ARMIsMemCpySmall(Len))
2441    return false;
2442
2443  while (Len) {
2444    MVT VT;
2445    if (!Alignment || Alignment >= 4) {
2446      if (Len >= 4)
2447        VT = MVT::i32;
2448      else if (Len >= 2)
2449        VT = MVT::i16;
2450      else {
2451        assert (Len == 1 && "Expected a length of 1!");
2452        VT = MVT::i8;
2453      }
2454    } else {
2455      // Bound based on alignment.
2456      if (Len >= 2 && Alignment == 2)
2457        VT = MVT::i16;
2458      else {
2459        assert (Alignment == 1 && "Expected an alignment of 1!");
2460        VT = MVT::i8;
2461      }
2462    }
2463
2464    bool RV;
2465    unsigned ResultReg;
2466    RV = ARMEmitLoad(VT, ResultReg, Src);
2467    assert (RV == true && "Should be able to handle this load.");
2468    RV = ARMEmitStore(VT, ResultReg, Dest);
2469    assert (RV == true && "Should be able to handle this store.");
2470    (void)RV;
2471
2472    unsigned Size = VT.getSizeInBits()/8;
2473    Len -= Size;
2474    Dest.Offset += Size;
2475    Src.Offset += Size;
2476  }
2477
2478  return true;
2479}
2480
2481bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2482  // FIXME: Handle more intrinsics.
2483  switch (I.getIntrinsicID()) {
2484  default: return false;
2485  case Intrinsic::frameaddress: {
2486    MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2487    MFI->setFrameAddressIsTaken(true);
2488
2489    unsigned LdrOpc;
2490    const TargetRegisterClass *RC;
2491    if (isThumb2) {
2492      LdrOpc =  ARM::t2LDRi12;
2493      RC = (const TargetRegisterClass*)&ARM::tGPRRegClass;
2494    } else {
2495      LdrOpc =  ARM::LDRi12;
2496      RC = (const TargetRegisterClass*)&ARM::GPRRegClass;
2497    }
2498
2499    const ARMBaseRegisterInfo *RegInfo =
2500          static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
2501    unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2502    unsigned SrcReg = FramePtr;
2503
2504    // Recursively load frame address
2505    // ldr r0 [fp]
2506    // ldr r0 [r0]
2507    // ldr r0 [r0]
2508    // ...
2509    unsigned DestReg;
2510    unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2511    while (Depth--) {
2512      DestReg = createResultReg(RC);
2513      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2514                              TII.get(LdrOpc), DestReg)
2515                      .addReg(SrcReg).addImm(0));
2516      SrcReg = DestReg;
2517    }
2518    UpdateValueMap(&I, SrcReg);
2519    return true;
2520  }
2521  case Intrinsic::memcpy:
2522  case Intrinsic::memmove: {
2523    const MemTransferInst &MTI = cast<MemTransferInst>(I);
2524    // Don't handle volatile.
2525    if (MTI.isVolatile())
2526      return false;
2527
2528    // Disable inlining for memmove before calls to ComputeAddress.  Otherwise,
2529    // we would emit dead code because we don't currently handle memmoves.
2530    bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2531    if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2532      // Small memcpy's are common enough that we want to do them without a call
2533      // if possible.
2534      uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2535      if (ARMIsMemCpySmall(Len)) {
2536        Address Dest, Src;
2537        if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2538            !ARMComputeAddress(MTI.getRawSource(), Src))
2539          return false;
2540        unsigned Alignment = MTI.getAlignment();
2541        if (ARMTryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2542          return true;
2543      }
2544    }
2545
2546    if (!MTI.getLength()->getType()->isIntegerTy(32))
2547      return false;
2548
2549    if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2550      return false;
2551
2552    const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2553    return SelectCall(&I, IntrMemName);
2554  }
2555  case Intrinsic::memset: {
2556    const MemSetInst &MSI = cast<MemSetInst>(I);
2557    // Don't handle volatile.
2558    if (MSI.isVolatile())
2559      return false;
2560
2561    if (!MSI.getLength()->getType()->isIntegerTy(32))
2562      return false;
2563
2564    if (MSI.getDestAddressSpace() > 255)
2565      return false;
2566
2567    return SelectCall(&I, "memset");
2568  }
2569  case Intrinsic::trap: {
2570    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::TRAP));
2571    return true;
2572  }
2573  }
2574}
2575
2576bool ARMFastISel::SelectTrunc(const Instruction *I) {
2577  // The high bits for a type smaller than the register size are assumed to be
2578  // undefined.
2579  Value *Op = I->getOperand(0);
2580
2581  EVT SrcVT, DestVT;
2582  SrcVT = TLI.getValueType(Op->getType(), true);
2583  DestVT = TLI.getValueType(I->getType(), true);
2584
2585  if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2586    return false;
2587  if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2588    return false;
2589
2590  unsigned SrcReg = getRegForValue(Op);
2591  if (!SrcReg) return false;
2592
2593  // Because the high bits are undefined, a truncate doesn't generate
2594  // any code.
2595  UpdateValueMap(I, SrcReg);
2596  return true;
2597}
2598
2599unsigned ARMFastISel::ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2600                                    bool isZExt) {
2601  if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2602    return 0;
2603
2604  unsigned Opc;
2605  bool isBoolZext = false;
2606  const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::i32);
2607  switch (SrcVT.SimpleTy) {
2608  default: return 0;
2609  case MVT::i16:
2610    if (!Subtarget->hasV6Ops()) return 0;
2611    RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
2612    if (isZExt)
2613      Opc = isThumb2 ? ARM::t2UXTH : ARM::UXTH;
2614    else
2615      Opc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
2616    break;
2617  case MVT::i8:
2618    if (!Subtarget->hasV6Ops()) return 0;
2619    RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
2620    if (isZExt)
2621      Opc = isThumb2 ? ARM::t2UXTB : ARM::UXTB;
2622    else
2623      Opc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
2624    break;
2625  case MVT::i1:
2626    if (isZExt) {
2627      RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
2628      Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
2629      isBoolZext = true;
2630      break;
2631    }
2632    return 0;
2633  }
2634
2635  unsigned ResultReg = createResultReg(RC);
2636  MachineInstrBuilder MIB;
2637  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
2638        .addReg(SrcReg);
2639  if (isBoolZext)
2640    MIB.addImm(1);
2641  else
2642    MIB.addImm(0);
2643  AddOptionalDefs(MIB);
2644  return ResultReg;
2645}
2646
2647bool ARMFastISel::SelectIntExt(const Instruction *I) {
2648  // On ARM, in general, integer casts don't involve legal types; this code
2649  // handles promotable integers.
2650  Type *DestTy = I->getType();
2651  Value *Src = I->getOperand(0);
2652  Type *SrcTy = Src->getType();
2653
2654  bool isZExt = isa<ZExtInst>(I);
2655  unsigned SrcReg = getRegForValue(Src);
2656  if (!SrcReg) return false;
2657
2658  EVT SrcEVT, DestEVT;
2659  SrcEVT = TLI.getValueType(SrcTy, true);
2660  DestEVT = TLI.getValueType(DestTy, true);
2661  if (!SrcEVT.isSimple()) return false;
2662  if (!DestEVT.isSimple()) return false;
2663
2664  MVT SrcVT = SrcEVT.getSimpleVT();
2665  MVT DestVT = DestEVT.getSimpleVT();
2666  unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2667  if (ResultReg == 0) return false;
2668  UpdateValueMap(I, ResultReg);
2669  return true;
2670}
2671
2672bool ARMFastISel::SelectShift(const Instruction *I,
2673                              ARM_AM::ShiftOpc ShiftTy) {
2674  // We handle thumb2 mode by target independent selector
2675  // or SelectionDAG ISel.
2676  if (isThumb2)
2677    return false;
2678
2679  // Only handle i32 now.
2680  EVT DestVT = TLI.getValueType(I->getType(), true);
2681  if (DestVT != MVT::i32)
2682    return false;
2683
2684  unsigned Opc = ARM::MOVsr;
2685  unsigned ShiftImm;
2686  Value *Src2Value = I->getOperand(1);
2687  if (const ConstantInt *CI = dyn_cast<ConstantInt>(Src2Value)) {
2688    ShiftImm = CI->getZExtValue();
2689
2690    // Fall back to selection DAG isel if the shift amount
2691    // is zero or greater than the width of the value type.
2692    if (ShiftImm == 0 || ShiftImm >=32)
2693      return false;
2694
2695    Opc = ARM::MOVsi;
2696  }
2697
2698  Value *Src1Value = I->getOperand(0);
2699  unsigned Reg1 = getRegForValue(Src1Value);
2700  if (Reg1 == 0) return false;
2701
2702  unsigned Reg2 = 0;
2703  if (Opc == ARM::MOVsr) {
2704    Reg2 = getRegForValue(Src2Value);
2705    if (Reg2 == 0) return false;
2706  }
2707
2708  unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::i32));
2709  if(ResultReg == 0) return false;
2710
2711  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2712                                    TII.get(Opc), ResultReg)
2713                            .addReg(Reg1);
2714
2715  if (Opc == ARM::MOVsi)
2716    MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, ShiftImm));
2717  else if (Opc == ARM::MOVsr) {
2718    MIB.addReg(Reg2);
2719    MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, 0));
2720  }
2721
2722  AddOptionalDefs(MIB);
2723  UpdateValueMap(I, ResultReg);
2724  return true;
2725}
2726
2727// TODO: SoftFP support.
2728bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
2729
2730  switch (I->getOpcode()) {
2731    case Instruction::Load:
2732      return SelectLoad(I);
2733    case Instruction::Store:
2734      return SelectStore(I);
2735    case Instruction::Br:
2736      return SelectBranch(I);
2737    case Instruction::IndirectBr:
2738      return SelectIndirectBr(I);
2739    case Instruction::ICmp:
2740    case Instruction::FCmp:
2741      return SelectCmp(I);
2742    case Instruction::FPExt:
2743      return SelectFPExt(I);
2744    case Instruction::FPTrunc:
2745      return SelectFPTrunc(I);
2746    case Instruction::SIToFP:
2747      return SelectIToFP(I, /*isSigned*/ true);
2748    case Instruction::UIToFP:
2749      return SelectIToFP(I, /*isSigned*/ false);
2750    case Instruction::FPToSI:
2751      return SelectFPToI(I, /*isSigned*/ true);
2752    case Instruction::FPToUI:
2753      return SelectFPToI(I, /*isSigned*/ false);
2754    case Instruction::Add:
2755      return SelectBinaryIntOp(I, ISD::ADD);
2756    case Instruction::Or:
2757      return SelectBinaryIntOp(I, ISD::OR);
2758    case Instruction::Sub:
2759      return SelectBinaryIntOp(I, ISD::SUB);
2760    case Instruction::FAdd:
2761      return SelectBinaryFPOp(I, ISD::FADD);
2762    case Instruction::FSub:
2763      return SelectBinaryFPOp(I, ISD::FSUB);
2764    case Instruction::FMul:
2765      return SelectBinaryFPOp(I, ISD::FMUL);
2766    case Instruction::SDiv:
2767      return SelectDiv(I, /*isSigned*/ true);
2768    case Instruction::UDiv:
2769      return SelectDiv(I, /*isSigned*/ false);
2770    case Instruction::SRem:
2771      return SelectRem(I, /*isSigned*/ true);
2772    case Instruction::URem:
2773      return SelectRem(I, /*isSigned*/ false);
2774    case Instruction::Call:
2775      if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2776        return SelectIntrinsicCall(*II);
2777      return SelectCall(I);
2778    case Instruction::Select:
2779      return SelectSelect(I);
2780    case Instruction::Ret:
2781      return SelectRet(I);
2782    case Instruction::Trunc:
2783      return SelectTrunc(I);
2784    case Instruction::ZExt:
2785    case Instruction::SExt:
2786      return SelectIntExt(I);
2787    case Instruction::Shl:
2788      return SelectShift(I, ARM_AM::lsl);
2789    case Instruction::LShr:
2790      return SelectShift(I, ARM_AM::lsr);
2791    case Instruction::AShr:
2792      return SelectShift(I, ARM_AM::asr);
2793    default: break;
2794  }
2795  return false;
2796}
2797
2798/// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2799/// vreg is being provided by the specified load instruction.  If possible,
2800/// try to fold the load as an operand to the instruction, returning true if
2801/// successful.
2802bool ARMFastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2803                                const LoadInst *LI) {
2804  // Verify we have a legal type before going any further.
2805  MVT VT;
2806  if (!isLoadTypeLegal(LI->getType(), VT))
2807    return false;
2808
2809  // Combine load followed by zero- or sign-extend.
2810  // ldrb r1, [r0]       ldrb r1, [r0]
2811  // uxtb r2, r1     =>
2812  // mov  r3, r2         mov  r3, r1
2813  bool isZExt = true;
2814  switch(MI->getOpcode()) {
2815    default: return false;
2816    case ARM::SXTH:
2817    case ARM::t2SXTH:
2818      isZExt = false;
2819    case ARM::UXTH:
2820    case ARM::t2UXTH:
2821      if (VT != MVT::i16)
2822        return false;
2823    break;
2824    case ARM::SXTB:
2825    case ARM::t2SXTB:
2826      isZExt = false;
2827    case ARM::UXTB:
2828    case ARM::t2UXTB:
2829      if (VT != MVT::i8)
2830        return false;
2831    break;
2832  }
2833  // See if we can handle this address.
2834  Address Addr;
2835  if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2836
2837  unsigned ResultReg = MI->getOperand(0).getReg();
2838  if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2839    return false;
2840  MI->eraseFromParent();
2841  return true;
2842}
2843
2844unsigned ARMFastISel::ARMLowerPICELF(const GlobalValue *GV,
2845                                     unsigned Align, MVT VT) {
2846  bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2847  ARMConstantPoolConstant *CPV =
2848    ARMConstantPoolConstant::Create(GV, UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2849  unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
2850
2851  unsigned Opc;
2852  unsigned DestReg1 = createResultReg(TLI.getRegClassFor(VT));
2853  // Load value.
2854  if (isThumb2) {
2855    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2856                            TII.get(ARM::t2LDRpci), DestReg1)
2857                    .addConstantPoolIndex(Idx));
2858    Opc = UseGOTOFF ? ARM::t2ADDrr : ARM::t2LDRs;
2859  } else {
2860    // The extra immediate is for addrmode2.
2861    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2862                            DL, TII.get(ARM::LDRcp), DestReg1)
2863                    .addConstantPoolIndex(Idx).addImm(0));
2864    Opc = UseGOTOFF ? ARM::ADDrr : ARM::LDRrs;
2865  }
2866
2867  unsigned GlobalBaseReg = AFI->getGlobalBaseReg();
2868  if (GlobalBaseReg == 0) {
2869    GlobalBaseReg = MRI.createVirtualRegister(TLI.getRegClassFor(VT));
2870    AFI->setGlobalBaseReg(GlobalBaseReg);
2871  }
2872
2873  unsigned DestReg2 = createResultReg(TLI.getRegClassFor(VT));
2874  MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2875                                    DL, TII.get(Opc), DestReg2)
2876                            .addReg(DestReg1)
2877                            .addReg(GlobalBaseReg);
2878  if (!UseGOTOFF)
2879    MIB.addImm(0);
2880  AddOptionalDefs(MIB);
2881
2882  return DestReg2;
2883}
2884
2885namespace llvm {
2886  FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo,
2887                                const TargetLibraryInfo *libInfo) {
2888    // Completely untested on non-iOS.
2889    const TargetMachine &TM = funcInfo.MF->getTarget();
2890
2891    // Darwin and thumb1 only for now.
2892    const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
2893    if (Subtarget->isTargetIOS() && !Subtarget->isThumb1Only())
2894      return new ARMFastISel(funcInfo, libInfo);
2895    return 0;
2896  }
2897}
2898