ARMFastISel.cpp revision c1d30212e911d1e55ff6b25bffefb503708883c3
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 "ARMRegisterInfo.h"
20#include "ARMTargetMachine.h"
21#include "ARMSubtarget.h"
22#include "ARMConstantPoolValue.h"
23#include "llvm/CallingConv.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Instructions.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/Module.h"
29#include "llvm/CodeGen/Analysis.h"
30#include "llvm/CodeGen/FastISel.h"
31#include "llvm/CodeGen/FunctionLoweringInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineConstantPool.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineMemOperand.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/PseudoSourceValue.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/GetElementPtrTypeIterator.h"
43#include "llvm/Target/TargetData.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
50static cl::opt<bool>
51DisableARMFastISel("disable-arm-fast-isel",
52                    cl::desc("Turn off experimental ARM fast-isel support"),
53                    cl::init(false), cl::Hidden);
54
55namespace {
56
57class ARMFastISel : public FastISel {
58
59  /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
60  /// make the right decision when generating code for different targets.
61  const ARMSubtarget *Subtarget;
62  const TargetMachine &TM;
63  const TargetInstrInfo &TII;
64  const TargetLowering &TLI;
65  ARMFunctionInfo *AFI;
66
67  // Convenience variables to avoid some queries.
68  bool isThumb;
69  LLVMContext *Context;
70
71  public:
72    explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
73    : FastISel(funcInfo),
74      TM(funcInfo.MF->getTarget()),
75      TII(*TM.getInstrInfo()),
76      TLI(*TM.getTargetLowering()) {
77      Subtarget = &TM.getSubtarget<ARMSubtarget>();
78      AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
79      isThumb = AFI->isThumbFunction();
80      Context = &funcInfo.Fn->getContext();
81    }
82
83    // Code from FastISel.cpp.
84    virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
85                                   const TargetRegisterClass *RC);
86    virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
87                                    const TargetRegisterClass *RC,
88                                    unsigned Op0, bool Op0IsKill);
89    virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
90                                     const TargetRegisterClass *RC,
91                                     unsigned Op0, bool Op0IsKill,
92                                     unsigned Op1, bool Op1IsKill);
93    virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
94                                     const TargetRegisterClass *RC,
95                                     unsigned Op0, bool Op0IsKill,
96                                     uint64_t Imm);
97    virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
98                                     const TargetRegisterClass *RC,
99                                     unsigned Op0, bool Op0IsKill,
100                                     const ConstantFP *FPImm);
101    virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
102                                    const TargetRegisterClass *RC,
103                                    uint64_t Imm);
104    virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
105                                      const TargetRegisterClass *RC,
106                                      unsigned Op0, bool Op0IsKill,
107                                      unsigned Op1, bool Op1IsKill,
108                                      uint64_t Imm);
109    virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
110                                                unsigned Op0, bool Op0IsKill,
111                                                uint32_t Idx);
112
113    // Backend specific FastISel code.
114    virtual bool TargetSelectInstruction(const Instruction *I);
115    virtual unsigned TargetMaterializeConstant(const Constant *C);
116    virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
117
118  #include "ARMGenFastISel.inc"
119
120    // Instruction selection routines.
121  private:
122    bool SelectLoad(const Instruction *I);
123    bool SelectStore(const Instruction *I);
124    bool SelectBranch(const Instruction *I);
125    bool SelectCmp(const Instruction *I);
126    bool SelectFPExt(const Instruction *I);
127    bool SelectFPTrunc(const Instruction *I);
128    bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
129    bool SelectSIToFP(const Instruction *I);
130    bool SelectFPToSI(const Instruction *I);
131    bool SelectSDiv(const Instruction *I);
132    bool SelectSRem(const Instruction *I);
133    bool SelectCall(const Instruction *I);
134    bool SelectSelect(const Instruction *I);
135    bool SelectRet(const Instruction *I);
136
137    // Utility routines.
138  private:
139    bool isTypeLegal(const Type *Ty, EVT &VT);
140    bool isLoadTypeLegal(const Type *Ty, EVT &VT);
141    bool ARMEmitLoad(EVT VT, unsigned &ResultReg, unsigned Base, int Offset);
142    bool ARMEmitStore(EVT VT, unsigned SrcReg, unsigned Base, int Offset);
143    bool ARMComputeRegOffset(const Value *Obj, unsigned &Base, int &Offset);
144    void ARMSimplifyRegOffset(unsigned &Base, int &Offset, EVT VT);
145    unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
146    unsigned ARMMaterializeInt(const Constant *C, EVT VT);
147    unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
148    unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
149    unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
150
151    // Call handling routines.
152  private:
153    bool FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
154                        unsigned &ResultReg);
155    CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
156    bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
157                         SmallVectorImpl<unsigned> &ArgRegs,
158                         SmallVectorImpl<EVT> &ArgVTs,
159                         SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
160                         SmallVectorImpl<unsigned> &RegArgs,
161                         CallingConv::ID CC,
162                         unsigned &NumBytes);
163    bool FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
164                    const Instruction *I, CallingConv::ID CC,
165                    unsigned &NumBytes);
166    bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
167
168    // OptionalDef handling routines.
169  private:
170    bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
171    const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
172};
173
174} // end anonymous namespace
175
176#include "ARMGenCallingConv.inc"
177
178// DefinesOptionalPredicate - This is different from DefinesPredicate in that
179// we don't care about implicit defs here, just places we'll need to add a
180// default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
181bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
182  const TargetInstrDesc &TID = MI->getDesc();
183  if (!TID.hasOptionalDef())
184    return false;
185
186  // Look to see if our OptionalDef is defining CPSR or CCR.
187  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
188    const MachineOperand &MO = MI->getOperand(i);
189    if (!MO.isReg() || !MO.isDef()) continue;
190    if (MO.getReg() == ARM::CPSR)
191      *CPSR = true;
192  }
193  return true;
194}
195
196// If the machine is predicable go ahead and add the predicate operands, if
197// it needs default CC operands add those.
198const MachineInstrBuilder &
199ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
200  MachineInstr *MI = &*MIB;
201
202  // Do we use a predicate?
203  if (TII.isPredicable(MI))
204    AddDefaultPred(MIB);
205
206  // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
207  // defines CPSR. All other OptionalDefines in ARM are the CCR register.
208  bool CPSR = false;
209  if (DefinesOptionalPredicate(MI, &CPSR)) {
210    if (CPSR)
211      AddDefaultT1CC(MIB);
212    else
213      AddDefaultCC(MIB);
214  }
215  return MIB;
216}
217
218unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
219                                    const TargetRegisterClass* RC) {
220  unsigned ResultReg = createResultReg(RC);
221  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
222
223  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
224  return ResultReg;
225}
226
227unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
228                                     const TargetRegisterClass *RC,
229                                     unsigned Op0, bool Op0IsKill) {
230  unsigned ResultReg = createResultReg(RC);
231  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
232
233  if (II.getNumDefs() >= 1)
234    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
235                   .addReg(Op0, Op0IsKill * RegState::Kill));
236  else {
237    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
238                   .addReg(Op0, Op0IsKill * RegState::Kill));
239    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
240                   TII.get(TargetOpcode::COPY), ResultReg)
241                   .addReg(II.ImplicitDefs[0]));
242  }
243  return ResultReg;
244}
245
246unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
247                                      const TargetRegisterClass *RC,
248                                      unsigned Op0, bool Op0IsKill,
249                                      unsigned Op1, bool Op1IsKill) {
250  unsigned ResultReg = createResultReg(RC);
251  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
252
253  if (II.getNumDefs() >= 1)
254    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
255                   .addReg(Op0, Op0IsKill * RegState::Kill)
256                   .addReg(Op1, Op1IsKill * RegState::Kill));
257  else {
258    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
259                   .addReg(Op0, Op0IsKill * RegState::Kill)
260                   .addReg(Op1, Op1IsKill * RegState::Kill));
261    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
262                           TII.get(TargetOpcode::COPY), ResultReg)
263                   .addReg(II.ImplicitDefs[0]));
264  }
265  return ResultReg;
266}
267
268unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
269                                      const TargetRegisterClass *RC,
270                                      unsigned Op0, bool Op0IsKill,
271                                      uint64_t Imm) {
272  unsigned ResultReg = createResultReg(RC);
273  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
274
275  if (II.getNumDefs() >= 1)
276    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
277                   .addReg(Op0, Op0IsKill * RegState::Kill)
278                   .addImm(Imm));
279  else {
280    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
281                   .addReg(Op0, Op0IsKill * RegState::Kill)
282                   .addImm(Imm));
283    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
284                           TII.get(TargetOpcode::COPY), ResultReg)
285                   .addReg(II.ImplicitDefs[0]));
286  }
287  return ResultReg;
288}
289
290unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
291                                      const TargetRegisterClass *RC,
292                                      unsigned Op0, bool Op0IsKill,
293                                      const ConstantFP *FPImm) {
294  unsigned ResultReg = createResultReg(RC);
295  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
296
297  if (II.getNumDefs() >= 1)
298    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
299                   .addReg(Op0, Op0IsKill * RegState::Kill)
300                   .addFPImm(FPImm));
301  else {
302    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
303                   .addReg(Op0, Op0IsKill * RegState::Kill)
304                   .addFPImm(FPImm));
305    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
306                           TII.get(TargetOpcode::COPY), ResultReg)
307                   .addReg(II.ImplicitDefs[0]));
308  }
309  return ResultReg;
310}
311
312unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
313                                       const TargetRegisterClass *RC,
314                                       unsigned Op0, bool Op0IsKill,
315                                       unsigned Op1, bool Op1IsKill,
316                                       uint64_t Imm) {
317  unsigned ResultReg = createResultReg(RC);
318  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
319
320  if (II.getNumDefs() >= 1)
321    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
322                   .addReg(Op0, Op0IsKill * RegState::Kill)
323                   .addReg(Op1, Op1IsKill * RegState::Kill)
324                   .addImm(Imm));
325  else {
326    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
327                   .addReg(Op0, Op0IsKill * RegState::Kill)
328                   .addReg(Op1, Op1IsKill * RegState::Kill)
329                   .addImm(Imm));
330    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
331                           TII.get(TargetOpcode::COPY), ResultReg)
332                   .addReg(II.ImplicitDefs[0]));
333  }
334  return ResultReg;
335}
336
337unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
338                                     const TargetRegisterClass *RC,
339                                     uint64_t Imm) {
340  unsigned ResultReg = createResultReg(RC);
341  const TargetInstrDesc &II = TII.get(MachineInstOpcode);
342
343  if (II.getNumDefs() >= 1)
344    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
345                   .addImm(Imm));
346  else {
347    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
348                   .addImm(Imm));
349    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
350                           TII.get(TargetOpcode::COPY), ResultReg)
351                   .addReg(II.ImplicitDefs[0]));
352  }
353  return ResultReg;
354}
355
356unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
357                                                 unsigned Op0, bool Op0IsKill,
358                                                 uint32_t Idx) {
359  unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
360  assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
361         "Cannot yet extract from physregs");
362  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
363                         DL, TII.get(TargetOpcode::COPY), ResultReg)
364                 .addReg(Op0, getKillRegState(Op0IsKill), Idx));
365  return ResultReg;
366}
367
368// TODO: Don't worry about 64-bit now, but when this is fixed remove the
369// checks from the various callers.
370unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
371  if (VT.getSimpleVT().SimpleTy == MVT::f64) return 0;
372
373  unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
374  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
375                          TII.get(ARM::VMOVRS), MoveReg)
376                  .addReg(SrcReg));
377  return MoveReg;
378}
379
380unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
381  if (VT.getSimpleVT().SimpleTy == MVT::i64) return 0;
382
383  unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
384  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
385                          TII.get(ARM::VMOVSR), MoveReg)
386                  .addReg(SrcReg));
387  return MoveReg;
388}
389
390// For double width floating point we need to materialize two constants
391// (the high and the low) into integer registers then use a move to get
392// the combined constant into an FP reg.
393unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
394  const APFloat Val = CFP->getValueAPF();
395  bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64;
396
397  // This checks to see if we can use VFP3 instructions to materialize
398  // a constant, otherwise we have to go through the constant pool.
399  if (TLI.isFPImmLegal(Val, VT)) {
400    unsigned Opc = is64bit ? ARM::FCONSTD : ARM::FCONSTS;
401    unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
402    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
403                            DestReg)
404                    .addFPImm(CFP));
405    return DestReg;
406  }
407
408  // Require VFP2 for loading fp constants.
409  if (!Subtarget->hasVFP2()) return false;
410
411  // MachineConstantPool wants an explicit alignment.
412  unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
413  if (Align == 0) {
414    // TODO: Figure out if this is correct.
415    Align = TD.getTypeAllocSize(CFP->getType());
416  }
417  unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
418  unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
419  unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
420
421  // The extra reg is for addrmode5.
422  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
423                          DestReg)
424                  .addConstantPoolIndex(Idx)
425                  .addReg(0));
426  return DestReg;
427}
428
429unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
430
431  // For now 32-bit only.
432  if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
433
434  // MachineConstantPool wants an explicit alignment.
435  unsigned Align = TD.getPrefTypeAlignment(C->getType());
436  if (Align == 0) {
437    // TODO: Figure out if this is correct.
438    Align = TD.getTypeAllocSize(C->getType());
439  }
440  unsigned Idx = MCP.getConstantPoolIndex(C, Align);
441  unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
442
443  if (isThumb)
444    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
445                            TII.get(ARM::t2LDRpci), DestReg)
446                    .addConstantPoolIndex(Idx));
447  else
448    // The extra reg and immediate are for addrmode2.
449    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
450                            TII.get(ARM::LDRcp), DestReg)
451                    .addConstantPoolIndex(Idx)
452                    .addImm(0));
453
454  return DestReg;
455}
456
457unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
458  // For now 32-bit only.
459  if (VT.getSimpleVT().SimpleTy != MVT::i32) return 0;
460
461  Reloc::Model RelocM = TM.getRelocationModel();
462
463  // TODO: No external globals for now.
464  if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) return 0;
465
466  // TODO: Need more magic for ARM PIC.
467  if (!isThumb && (RelocM == Reloc::PIC_)) return 0;
468
469  // MachineConstantPool wants an explicit alignment.
470  unsigned Align = TD.getPrefTypeAlignment(GV->getType());
471  if (Align == 0) {
472    // TODO: Figure out if this is correct.
473    Align = TD.getTypeAllocSize(GV->getType());
474  }
475
476  // Grab index.
477  unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb() ? 4 : 8);
478  unsigned Id = AFI->createConstPoolEntryUId();
479  ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, Id,
480                                                       ARMCP::CPValue, PCAdj);
481  unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
482
483  // Load value.
484  MachineInstrBuilder MIB;
485  unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
486  if (isThumb) {
487    unsigned Opc = (RelocM != Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
488    MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
489          .addConstantPoolIndex(Idx);
490    if (RelocM == Reloc::PIC_)
491      MIB.addImm(Id);
492  } else {
493    // The extra reg and immediate are for addrmode2.
494    MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
495                  DestReg)
496          .addConstantPoolIndex(Idx)
497          .addReg(0).addImm(0);
498  }
499  AddOptionalDefs(MIB);
500  return DestReg;
501}
502
503unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
504  EVT VT = TLI.getValueType(C->getType(), true);
505
506  // Only handle simple types.
507  if (!VT.isSimple()) return 0;
508
509  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
510    return ARMMaterializeFP(CFP, VT);
511  else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
512    return ARMMaterializeGV(GV, VT);
513  else if (isa<ConstantInt>(C))
514    return ARMMaterializeInt(C, VT);
515
516  return 0;
517}
518
519unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
520  // Don't handle dynamic allocas.
521  if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
522
523  EVT VT;
524  if (!isLoadTypeLegal(AI->getType(), VT)) return false;
525
526  DenseMap<const AllocaInst*, int>::iterator SI =
527    FuncInfo.StaticAllocaMap.find(AI);
528
529  // This will get lowered later into the correct offsets and registers
530  // via rewriteXFrameIndex.
531  if (SI != FuncInfo.StaticAllocaMap.end()) {
532    TargetRegisterClass* RC = TLI.getRegClassFor(VT);
533    unsigned ResultReg = createResultReg(RC);
534    unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
535    AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
536                            TII.get(Opc), ResultReg)
537                            .addFrameIndex(SI->second)
538                            .addImm(0));
539    return ResultReg;
540  }
541
542  return 0;
543}
544
545bool ARMFastISel::isTypeLegal(const Type *Ty, EVT &VT) {
546  VT = TLI.getValueType(Ty, true);
547
548  // Only handle simple types.
549  if (VT == MVT::Other || !VT.isSimple()) return false;
550
551  // Handle all legal types, i.e. a register that will directly hold this
552  // value.
553  return TLI.isTypeLegal(VT);
554}
555
556bool ARMFastISel::isLoadTypeLegal(const Type *Ty, EVT &VT) {
557  if (isTypeLegal(Ty, VT)) return true;
558
559  // If this is a type than can be sign or zero-extended to a basic operation
560  // go ahead and accept it now.
561  if (VT == MVT::i8 || VT == MVT::i16)
562    return true;
563
564  return false;
565}
566
567// Computes the Reg+Offset to get to an object.
568bool ARMFastISel::ARMComputeRegOffset(const Value *Obj, unsigned &Base,
569                                      int &Offset) {
570  // Some boilerplate from the X86 FastISel.
571  const User *U = NULL;
572  unsigned Opcode = Instruction::UserOp1;
573  if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
574    // Don't walk into other basic blocks; it's possible we haven't
575    // visited them yet, so the instructions may not yet be assigned
576    // virtual registers.
577    if (FuncInfo.MBBMap[I->getParent()] != FuncInfo.MBB)
578      return false;
579    Opcode = I->getOpcode();
580    U = I;
581  } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
582    Opcode = C->getOpcode();
583    U = C;
584  }
585
586  if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
587    if (Ty->getAddressSpace() > 255)
588      // Fast instruction selection doesn't support the special
589      // address spaces.
590      return false;
591
592  switch (Opcode) {
593    default:
594    break;
595    case Instruction::BitCast: {
596      // Look through bitcasts.
597      return ARMComputeRegOffset(U->getOperand(0), Base, Offset);
598    }
599    case Instruction::IntToPtr: {
600      // Look past no-op inttoptrs.
601      if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
602        return ARMComputeRegOffset(U->getOperand(0), Base, Offset);
603      break;
604    }
605    case Instruction::PtrToInt: {
606      // Look past no-op ptrtoints.
607      if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
608        return ARMComputeRegOffset(U->getOperand(0), Base, Offset);
609      break;
610    }
611    case Instruction::GetElementPtr: {
612      int SavedOffset = Offset;
613      unsigned SavedBase = Base;
614      int TmpOffset = Offset;
615
616      // Iterate through the GEP folding the constants into offsets where
617      // we can.
618      gep_type_iterator GTI = gep_type_begin(U);
619      for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
620           i != e; ++i, ++GTI) {
621        const Value *Op = *i;
622        if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
623          const StructLayout *SL = TD.getStructLayout(STy);
624          unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
625          TmpOffset += SL->getElementOffset(Idx);
626        } else {
627          uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
628          SmallVector<const Value *, 4> Worklist;
629          Worklist.push_back(Op);
630          do {
631            Op = Worklist.pop_back_val();
632            if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
633              // Constant-offset addressing.
634              TmpOffset += CI->getSExtValue() * S;
635            } else if (isa<AddOperator>(Op) &&
636                       isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
637              // An add with a constant operand. Fold the constant.
638              ConstantInt *CI =
639                cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
640              TmpOffset += CI->getSExtValue() * S;
641              // Add the other operand back to the work list.
642              Worklist.push_back(cast<AddOperator>(Op)->getOperand(0));
643            } else
644              goto unsupported_gep;
645          } while (!Worklist.empty());
646        }
647      }
648
649      // Try to grab the base operand now.
650      Offset = TmpOffset;
651      if (ARMComputeRegOffset(U->getOperand(0), Base, Offset)) return true;
652
653      // We failed, restore everything and try the other options.
654      Offset = SavedOffset;
655      Base = SavedBase;
656
657      unsupported_gep:
658      break;
659    }
660    case Instruction::Alloca: {
661      const AllocaInst *AI = cast<AllocaInst>(Obj);
662      unsigned Reg = TargetMaterializeAlloca(AI);
663
664      if (Reg == 0) return false;
665
666      Base = Reg;
667      return true;
668    }
669  }
670
671  // Materialize the global variable's address into a reg which can
672  // then be used later to load the variable.
673  if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
674    unsigned Tmp = ARMMaterializeGV(GV, TLI.getValueType(Obj->getType()));
675    if (Tmp == 0) return false;
676
677    Base = Tmp;
678    return true;
679  }
680
681  // Try to get this in a register if nothing else has worked.
682  if (Base == 0) Base  = getRegForValue(Obj);
683  return Base != 0;
684}
685
686void ARMFastISel::ARMSimplifyRegOffset(unsigned &Base, int &Offset, EVT VT) {
687
688  assert(VT.isSimple() && "Non-simple types are invalid here!");
689
690  bool needsLowering = false;
691  switch (VT.getSimpleVT().SimpleTy) {
692    default:
693      assert(false && "Unhandled load/store type!");
694    case MVT::i1:
695    case MVT::i8:
696    case MVT::i16:
697    case MVT::i32:
698      // Integer loads/stores handle 12-bit offsets.
699      needsLowering = ((Offset & 0xfff) != Offset);
700      break;
701    case MVT::f32:
702    case MVT::f64:
703      // Floating point operands handle 8-bit offsets.
704      needsLowering = ((Offset & 0xff) != Offset);
705      break;
706  }
707
708  // Since the offset is too large for the load/store instruction
709  // get the reg+offset into a register.
710  if (needsLowering) {
711    ARMCC::CondCodes Pred = ARMCC::AL;
712    unsigned PredReg = 0;
713
714    TargetRegisterClass *RC = isThumb ? ARM::tGPRRegisterClass :
715      ARM::GPRRegisterClass;
716    unsigned BaseReg = createResultReg(RC);
717
718    if (!isThumb)
719      emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
720                              BaseReg, Base, Offset, Pred, PredReg,
721                              static_cast<const ARMBaseInstrInfo&>(TII));
722    else {
723      assert(AFI->isThumb2Function());
724      emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
725                             BaseReg, Base, Offset, Pred, PredReg,
726                             static_cast<const ARMBaseInstrInfo&>(TII));
727    }
728    Offset = 0;
729    Base = BaseReg;
730  }
731}
732
733bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg,
734                              unsigned Base, int Offset) {
735
736  assert(VT.isSimple() && "Non-simple types are invalid here!");
737  unsigned Opc;
738  TargetRegisterClass *RC;
739  bool isFloat = false;
740  switch (VT.getSimpleVT().SimpleTy) {
741    default:
742      // This is mostly going to be Neon/vector support.
743      return false;
744    case MVT::i16:
745      Opc = isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
746      RC = ARM::GPRRegisterClass;
747      break;
748    case MVT::i8:
749      Opc = isThumb ? ARM::t2LDRBi12 : ARM::LDRBi12;
750      RC = ARM::GPRRegisterClass;
751      break;
752    case MVT::i32:
753      Opc = isThumb ? ARM::t2LDRi12 : ARM::LDRi12;
754      RC = ARM::GPRRegisterClass;
755      break;
756    case MVT::f32:
757      Opc = ARM::VLDRS;
758      RC = TLI.getRegClassFor(VT);
759      isFloat = true;
760      break;
761    case MVT::f64:
762      Opc = ARM::VLDRD;
763      RC = TLI.getRegClassFor(VT);
764      isFloat = true;
765      break;
766  }
767
768  ResultReg = createResultReg(RC);
769
770  ARMSimplifyRegOffset(Base, Offset, VT);
771
772  // addrmode5 output depends on the selection dag addressing dividing the
773  // offset by 4 that it then later multiplies. Do this here as well.
774  if (isFloat)
775    Offset /= 4;
776
777  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
778                          TII.get(Opc), ResultReg)
779                  .addReg(Base).addImm(Offset));
780  return true;
781}
782
783bool ARMFastISel::SelectLoad(const Instruction *I) {
784  // Verify we have a legal type before going any further.
785  EVT VT;
786  if (!isLoadTypeLegal(I->getType(), VT))
787    return false;
788
789  // Our register and offset with innocuous defaults.
790  unsigned Base = 0;
791  int Offset = 0;
792
793  // See if we can handle this as Reg + Offset
794  if (!ARMComputeRegOffset(I->getOperand(0), Base, Offset))
795    return false;
796
797  unsigned ResultReg;
798  if (!ARMEmitLoad(VT, ResultReg, Base, Offset)) return false;
799
800  UpdateValueMap(I, ResultReg);
801  return true;
802}
803
804bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg,
805                               unsigned Base, int Offset) {
806  unsigned StrOpc;
807  bool isFloat = false;
808  switch (VT.getSimpleVT().SimpleTy) {
809    default: return false;
810    case MVT::i1:
811    case MVT::i8:
812      StrOpc = isThumb ? ARM::t2STRBi12 : ARM::STRB;
813      break;
814    case MVT::i16:
815      StrOpc = isThumb ? ARM::t2STRHi12 : ARM::STRH;
816      break;
817    case MVT::i32:
818      StrOpc = isThumb ? ARM::t2STRi12 : ARM::STR;
819      break;
820    case MVT::f32:
821      if (!Subtarget->hasVFP2()) return false;
822      StrOpc = ARM::VSTRS;
823      isFloat = true;
824      break;
825    case MVT::f64:
826      if (!Subtarget->hasVFP2()) return false;
827      StrOpc = ARM::VSTRD;
828      isFloat = true;
829      break;
830  }
831
832  ARMSimplifyRegOffset(Base, Offset, VT);
833
834  // addrmode5 output depends on the selection dag addressing dividing the
835  // offset by 4 that it then later multiplies. Do this here as well.
836  if (isFloat)
837    Offset /= 4;
838
839  // The thumb addressing mode has operands swapped from the arm addressing
840  // mode, the floating point one only has two operands.
841  if (isFloat || isThumb)
842    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
843                            TII.get(StrOpc))
844                    .addReg(SrcReg).addReg(Base).addImm(Offset));
845  else
846    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
847                            TII.get(StrOpc))
848                    .addReg(SrcReg).addReg(Base).addReg(0).addImm(Offset));
849
850  return true;
851}
852
853bool ARMFastISel::SelectStore(const Instruction *I) {
854  Value *Op0 = I->getOperand(0);
855  unsigned SrcReg = 0;
856
857  // Yay type legalization
858  EVT VT;
859  if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
860    return false;
861
862  // Get the value to be stored into a register.
863  SrcReg = getRegForValue(Op0);
864  if (SrcReg == 0)
865    return false;
866
867  // Our register and offset with innocuous defaults.
868  unsigned Base = 0;
869  int Offset = 0;
870
871  // See if we can handle this as Reg + Offset
872  if (!ARMComputeRegOffset(I->getOperand(1), Base, Offset))
873    return false;
874
875  if (!ARMEmitStore(VT, SrcReg, Base, Offset)) return false;
876
877  return true;
878}
879
880static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
881  switch (Pred) {
882    // Needs two compares...
883    case CmpInst::FCMP_ONE:
884    case CmpInst::FCMP_UEQ:
885    default:
886      assert(false && "Unhandled CmpInst::Predicate!");
887      return ARMCC::AL;
888    case CmpInst::ICMP_EQ:
889    case CmpInst::FCMP_OEQ:
890      return ARMCC::EQ;
891    case CmpInst::ICMP_SGT:
892    case CmpInst::FCMP_OGT:
893      return ARMCC::GT;
894    case CmpInst::ICMP_SGE:
895    case CmpInst::FCMP_OGE:
896      return ARMCC::GE;
897    case CmpInst::ICMP_UGT:
898    case CmpInst::FCMP_UGT:
899      return ARMCC::HI;
900    case CmpInst::FCMP_OLT:
901      return ARMCC::MI;
902    case CmpInst::ICMP_ULE:
903    case CmpInst::FCMP_OLE:
904      return ARMCC::LS;
905    case CmpInst::FCMP_ORD:
906      return ARMCC::VC;
907    case CmpInst::FCMP_UNO:
908      return ARMCC::VS;
909    case CmpInst::FCMP_UGE:
910      return ARMCC::PL;
911    case CmpInst::ICMP_SLT:
912    case CmpInst::FCMP_ULT:
913      return ARMCC::LT;
914    case CmpInst::ICMP_SLE:
915    case CmpInst::FCMP_ULE:
916      return ARMCC::LE;
917    case CmpInst::FCMP_UNE:
918    case CmpInst::ICMP_NE:
919      return ARMCC::NE;
920    case CmpInst::ICMP_UGE:
921      return ARMCC::HS;
922    case CmpInst::ICMP_ULT:
923      return ARMCC::LO;
924  }
925}
926
927bool ARMFastISel::SelectBranch(const Instruction *I) {
928  const BranchInst *BI = cast<BranchInst>(I);
929  MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
930  MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
931
932  // Simple branch support.
933  // TODO: Try to avoid the re-computation in some places.
934  unsigned CondReg = getRegForValue(BI->getCondition());
935  if (CondReg == 0) return false;
936
937  // Re-set the flags just in case.
938  unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
939  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
940                  .addReg(CondReg).addImm(1));
941
942  unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
943  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
944                  .addMBB(TBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
945  FastEmitBranch(FBB, DL);
946  FuncInfo.MBB->addSuccessor(TBB);
947  return true;
948}
949
950bool ARMFastISel::SelectCmp(const Instruction *I) {
951  const CmpInst *CI = cast<CmpInst>(I);
952
953  EVT VT;
954  const Type *Ty = CI->getOperand(0)->getType();
955  if (!isTypeLegal(Ty, VT))
956    return false;
957
958  bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
959  if (isFloat && !Subtarget->hasVFP2())
960    return false;
961
962  unsigned CmpOpc;
963  unsigned CondReg;
964  switch (VT.getSimpleVT().SimpleTy) {
965    default: return false;
966    // TODO: Verify compares.
967    case MVT::f32:
968      CmpOpc = ARM::VCMPES;
969      CondReg = ARM::FPSCR;
970      break;
971    case MVT::f64:
972      CmpOpc = ARM::VCMPED;
973      CondReg = ARM::FPSCR;
974      break;
975    case MVT::i32:
976      CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
977      CondReg = ARM::CPSR;
978      break;
979  }
980
981  // Get the compare predicate.
982  ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
983
984  // We may not handle every CC for now.
985  if (ARMPred == ARMCC::AL) return false;
986
987  unsigned Arg1 = getRegForValue(CI->getOperand(0));
988  if (Arg1 == 0) return false;
989
990  unsigned Arg2 = getRegForValue(CI->getOperand(1));
991  if (Arg2 == 0) return false;
992
993  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
994                  .addReg(Arg1).addReg(Arg2));
995
996  // For floating point we need to move the result to a comparison register
997  // that we can then use for branches.
998  if (isFloat)
999    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1000                            TII.get(ARM::FMSTAT)));
1001
1002  // Now set a register based on the comparison. Explicitly set the predicates
1003  // here.
1004  unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
1005  TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass
1006                                    : ARM::GPRRegisterClass;
1007  unsigned DestReg = createResultReg(RC);
1008  Constant *Zero
1009    = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1010  unsigned ZeroReg = TargetMaterializeConstant(Zero);
1011  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1012          .addReg(ZeroReg).addImm(1)
1013          .addImm(ARMPred).addReg(CondReg);
1014
1015  UpdateValueMap(I, DestReg);
1016  return true;
1017}
1018
1019bool ARMFastISel::SelectFPExt(const Instruction *I) {
1020  // Make sure we have VFP and that we're extending float to double.
1021  if (!Subtarget->hasVFP2()) return false;
1022
1023  Value *V = I->getOperand(0);
1024  if (!I->getType()->isDoubleTy() ||
1025      !V->getType()->isFloatTy()) return false;
1026
1027  unsigned Op = getRegForValue(V);
1028  if (Op == 0) return false;
1029
1030  unsigned Result = createResultReg(ARM::DPRRegisterClass);
1031  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1032                          TII.get(ARM::VCVTDS), Result)
1033                  .addReg(Op));
1034  UpdateValueMap(I, Result);
1035  return true;
1036}
1037
1038bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1039  // Make sure we have VFP and that we're truncating double to float.
1040  if (!Subtarget->hasVFP2()) return false;
1041
1042  Value *V = I->getOperand(0);
1043  if (!(I->getType()->isFloatTy() &&
1044        V->getType()->isDoubleTy())) return false;
1045
1046  unsigned Op = getRegForValue(V);
1047  if (Op == 0) return false;
1048
1049  unsigned Result = createResultReg(ARM::SPRRegisterClass);
1050  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1051                          TII.get(ARM::VCVTSD), Result)
1052                  .addReg(Op));
1053  UpdateValueMap(I, Result);
1054  return true;
1055}
1056
1057bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1058  // Make sure we have VFP.
1059  if (!Subtarget->hasVFP2()) return false;
1060
1061  EVT DstVT;
1062  const Type *Ty = I->getType();
1063  if (!isTypeLegal(Ty, DstVT))
1064    return false;
1065
1066  unsigned Op = getRegForValue(I->getOperand(0));
1067  if (Op == 0) return false;
1068
1069  // The conversion routine works on fp-reg to fp-reg and the operand above
1070  // was an integer, move it to the fp registers if possible.
1071  unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1072  if (FP == 0) return false;
1073
1074  unsigned Opc;
1075  if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1076  else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1077  else return 0;
1078
1079  unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1080  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1081                          ResultReg)
1082                  .addReg(FP));
1083  UpdateValueMap(I, ResultReg);
1084  return true;
1085}
1086
1087bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1088  // Make sure we have VFP.
1089  if (!Subtarget->hasVFP2()) return false;
1090
1091  EVT DstVT;
1092  const Type *RetTy = I->getType();
1093  if (!isTypeLegal(RetTy, DstVT))
1094    return false;
1095
1096  unsigned Op = getRegForValue(I->getOperand(0));
1097  if (Op == 0) return false;
1098
1099  unsigned Opc;
1100  const Type *OpTy = I->getOperand(0)->getType();
1101  if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1102  else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1103  else return 0;
1104
1105  // f64->s32 or f32->s32 both need an intermediate f32 reg.
1106  unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1107  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1108                          ResultReg)
1109                  .addReg(Op));
1110
1111  // This result needs to be in an integer register, but the conversion only
1112  // takes place in fp-regs.
1113  unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1114  if (IntReg == 0) return false;
1115
1116  UpdateValueMap(I, IntReg);
1117  return true;
1118}
1119
1120bool ARMFastISel::SelectSelect(const Instruction *I) {
1121  EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1122  if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1123    return false;
1124
1125  // Things need to be register sized for register moves.
1126  if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
1127  const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1128
1129  unsigned CondReg = getRegForValue(I->getOperand(0));
1130  if (CondReg == 0) return false;
1131  unsigned Op1Reg = getRegForValue(I->getOperand(1));
1132  if (Op1Reg == 0) return false;
1133  unsigned Op2Reg = getRegForValue(I->getOperand(2));
1134  if (Op2Reg == 0) return false;
1135
1136  unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1137  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1138                  .addReg(CondReg).addImm(1));
1139  unsigned ResultReg = createResultReg(RC);
1140  unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1141  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1142    .addReg(Op1Reg).addReg(Op2Reg)
1143    .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1144  UpdateValueMap(I, ResultReg);
1145  return true;
1146}
1147
1148bool ARMFastISel::SelectSDiv(const Instruction *I) {
1149  EVT VT;
1150  const Type *Ty = I->getType();
1151  if (!isTypeLegal(Ty, VT))
1152    return false;
1153
1154  // If we have integer div support we should have selected this automagically.
1155  // In case we have a real miss go ahead and return false and we'll pick
1156  // it up later.
1157  if (Subtarget->hasDivide()) return false;
1158
1159  // Otherwise emit a libcall.
1160  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1161  if (VT == MVT::i8)
1162    LC = RTLIB::SDIV_I8;
1163  else if (VT == MVT::i16)
1164    LC = RTLIB::SDIV_I16;
1165  else if (VT == MVT::i32)
1166    LC = RTLIB::SDIV_I32;
1167  else if (VT == MVT::i64)
1168    LC = RTLIB::SDIV_I64;
1169  else if (VT == MVT::i128)
1170    LC = RTLIB::SDIV_I128;
1171  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1172
1173  return ARMEmitLibcall(I, LC);
1174}
1175
1176bool ARMFastISel::SelectSRem(const Instruction *I) {
1177  EVT VT;
1178  const Type *Ty = I->getType();
1179  if (!isTypeLegal(Ty, VT))
1180    return false;
1181
1182  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1183  if (VT == MVT::i8)
1184    LC = RTLIB::SREM_I8;
1185  else if (VT == MVT::i16)
1186    LC = RTLIB::SREM_I16;
1187  else if (VT == MVT::i32)
1188    LC = RTLIB::SREM_I32;
1189  else if (VT == MVT::i64)
1190    LC = RTLIB::SREM_I64;
1191  else if (VT == MVT::i128)
1192    LC = RTLIB::SREM_I128;
1193  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1194
1195  return ARMEmitLibcall(I, LC);
1196}
1197
1198bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1199  EVT VT  = TLI.getValueType(I->getType(), true);
1200
1201  // We can get here in the case when we want to use NEON for our fp
1202  // operations, but can't figure out how to. Just use the vfp instructions
1203  // if we have them.
1204  // FIXME: It'd be nice to use NEON instructions.
1205  const Type *Ty = I->getType();
1206  bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1207  if (isFloat && !Subtarget->hasVFP2())
1208    return false;
1209
1210  unsigned Op1 = getRegForValue(I->getOperand(0));
1211  if (Op1 == 0) return false;
1212
1213  unsigned Op2 = getRegForValue(I->getOperand(1));
1214  if (Op2 == 0) return false;
1215
1216  unsigned Opc;
1217  bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64 ||
1218                 VT.getSimpleVT().SimpleTy == MVT::i64;
1219  switch (ISDOpcode) {
1220    default: return false;
1221    case ISD::FADD:
1222      Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1223      break;
1224    case ISD::FSUB:
1225      Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1226      break;
1227    case ISD::FMUL:
1228      Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1229      break;
1230  }
1231  unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1232  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1233                          TII.get(Opc), ResultReg)
1234                  .addReg(Op1).addReg(Op2));
1235  UpdateValueMap(I, ResultReg);
1236  return true;
1237}
1238
1239// Call Handling Code
1240
1241bool ARMFastISel::FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src,
1242                                 EVT SrcVT, unsigned &ResultReg) {
1243  unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
1244                           Src, /*TODO: Kill=*/false);
1245
1246  if (RR != 0) {
1247    ResultReg = RR;
1248    return true;
1249  } else
1250    return false;
1251}
1252
1253// This is largely taken directly from CCAssignFnForNode - we don't support
1254// varargs in FastISel so that part has been removed.
1255// TODO: We may not support all of this.
1256CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1257  switch (CC) {
1258  default:
1259    llvm_unreachable("Unsupported calling convention");
1260  case CallingConv::Fast:
1261    // Ignore fastcc. Silence compiler warnings.
1262    (void)RetFastCC_ARM_APCS;
1263    (void)FastCC_ARM_APCS;
1264    // Fallthrough
1265  case CallingConv::C:
1266    // Use target triple & subtarget features to do actual dispatch.
1267    if (Subtarget->isAAPCS_ABI()) {
1268      if (Subtarget->hasVFP2() &&
1269          FloatABIType == FloatABI::Hard)
1270        return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1271      else
1272        return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1273    } else
1274        return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1275  case CallingConv::ARM_AAPCS_VFP:
1276    return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1277  case CallingConv::ARM_AAPCS:
1278    return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1279  case CallingConv::ARM_APCS:
1280    return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1281  }
1282}
1283
1284bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1285                                  SmallVectorImpl<unsigned> &ArgRegs,
1286                                  SmallVectorImpl<EVT> &ArgVTs,
1287                                  SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1288                                  SmallVectorImpl<unsigned> &RegArgs,
1289                                  CallingConv::ID CC,
1290                                  unsigned &NumBytes) {
1291  SmallVector<CCValAssign, 16> ArgLocs;
1292  CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1293  CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1294
1295  // Get a count of how many bytes are to be pushed on the stack.
1296  NumBytes = CCInfo.getNextStackOffset();
1297
1298  // Issue CALLSEQ_START
1299  unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1300  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1301                          TII.get(AdjStackDown))
1302                  .addImm(NumBytes));
1303
1304  // Process the args.
1305  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1306    CCValAssign &VA = ArgLocs[i];
1307    unsigned Arg = ArgRegs[VA.getValNo()];
1308    EVT ArgVT = ArgVTs[VA.getValNo()];
1309
1310    // We don't handle NEON parameters yet.
1311    if (VA.getLocVT().isVector() && VA.getLocVT().getSizeInBits() > 64)
1312      return false;
1313
1314    // Handle arg promotion, etc.
1315    switch (VA.getLocInfo()) {
1316      case CCValAssign::Full: break;
1317      case CCValAssign::SExt: {
1318        bool Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1319                                         Arg, ArgVT, Arg);
1320        assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1321        Emitted = true;
1322        ArgVT = VA.getLocVT();
1323        break;
1324      }
1325      case CCValAssign::ZExt: {
1326        bool Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1327                                         Arg, ArgVT, Arg);
1328        assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1329        Emitted = true;
1330        ArgVT = VA.getLocVT();
1331        break;
1332      }
1333      case CCValAssign::AExt: {
1334        bool Emitted = FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1335                                         Arg, ArgVT, Arg);
1336        if (!Emitted)
1337          Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1338                                      Arg, ArgVT, Arg);
1339        if (!Emitted)
1340          Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1341                                      Arg, ArgVT, Arg);
1342
1343        assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1344        ArgVT = VA.getLocVT();
1345        break;
1346      }
1347      case CCValAssign::BCvt: {
1348        unsigned BC = FastEmit_r(ArgVT.getSimpleVT(),
1349                                 VA.getLocVT().getSimpleVT(),
1350                                 ISD::BIT_CONVERT, Arg, /*TODO: Kill=*/false);
1351        assert(BC != 0 && "Failed to emit a bitcast!");
1352        Arg = BC;
1353        ArgVT = VA.getLocVT();
1354        break;
1355      }
1356      default: llvm_unreachable("Unknown arg promotion!");
1357    }
1358
1359    // Now copy/store arg to correct locations.
1360    if (VA.isRegLoc() && !VA.needsCustom()) {
1361      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1362              VA.getLocReg())
1363      .addReg(Arg);
1364      RegArgs.push_back(VA.getLocReg());
1365    } else if (VA.needsCustom()) {
1366      // TODO: We need custom lowering for vector (v2f64) args.
1367      if (VA.getLocVT() != MVT::f64) return false;
1368
1369      CCValAssign &NextVA = ArgLocs[++i];
1370
1371      // TODO: Only handle register args for now.
1372      if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1373
1374      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1375                              TII.get(ARM::VMOVRRD), VA.getLocReg())
1376                      .addReg(NextVA.getLocReg(), RegState::Define)
1377                      .addReg(Arg));
1378      RegArgs.push_back(VA.getLocReg());
1379      RegArgs.push_back(NextVA.getLocReg());
1380    } else {
1381      assert(VA.isMemLoc());
1382      // Need to store on the stack.
1383      unsigned Base = ARM::SP;
1384      int Offset = VA.getLocMemOffset();
1385
1386      if (!ARMEmitStore(ArgVT, Arg, Base, Offset)) return false;
1387    }
1388  }
1389  return true;
1390}
1391
1392bool ARMFastISel::FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1393                             const Instruction *I, CallingConv::ID CC,
1394                             unsigned &NumBytes) {
1395  // Issue CALLSEQ_END
1396  unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1397  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1398                          TII.get(AdjStackUp))
1399                  .addImm(NumBytes).addImm(0));
1400
1401  // Now the return value.
1402  if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1403    SmallVector<CCValAssign, 16> RVLocs;
1404    CCState CCInfo(CC, false, TM, RVLocs, *Context);
1405    CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1406
1407    // Copy all of the result registers out of their specified physreg.
1408    if (RVLocs.size() == 2 && RetVT.getSimpleVT().SimpleTy == MVT::f64) {
1409      // For this move we copy into two registers and then move into the
1410      // double fp reg we want.
1411      EVT DestVT = RVLocs[0].getValVT();
1412      TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1413      unsigned ResultReg = createResultReg(DstRC);
1414      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1415                              TII.get(ARM::VMOVDRR), ResultReg)
1416                      .addReg(RVLocs[0].getLocReg())
1417                      .addReg(RVLocs[1].getLocReg()));
1418
1419      UsedRegs.push_back(RVLocs[0].getLocReg());
1420      UsedRegs.push_back(RVLocs[1].getLocReg());
1421
1422      // Finally update the result.
1423      UpdateValueMap(I, ResultReg);
1424    } else {
1425      assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1426      EVT CopyVT = RVLocs[0].getValVT();
1427      TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1428
1429      unsigned ResultReg = createResultReg(DstRC);
1430      BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1431              ResultReg).addReg(RVLocs[0].getLocReg());
1432      UsedRegs.push_back(RVLocs[0].getLocReg());
1433
1434      // Finally update the result.
1435      UpdateValueMap(I, ResultReg);
1436    }
1437  }
1438
1439  return true;
1440}
1441
1442bool ARMFastISel::SelectRet(const Instruction *I) {
1443  const ReturnInst *Ret = cast<ReturnInst>(I);
1444  const Function &F = *I->getParent()->getParent();
1445
1446  if (!FuncInfo.CanLowerReturn)
1447    return false;
1448
1449  if (F.isVarArg())
1450    return false;
1451
1452  CallingConv::ID CC = F.getCallingConv();
1453  if (Ret->getNumOperands() > 0) {
1454    SmallVector<ISD::OutputArg, 4> Outs;
1455    GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1456                  Outs, TLI);
1457
1458    // Analyze operands of the call, assigning locations to each operand.
1459    SmallVector<CCValAssign, 16> ValLocs;
1460    CCState CCInfo(CC, F.isVarArg(), TM, ValLocs, I->getContext());
1461    CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1462
1463    const Value *RV = Ret->getOperand(0);
1464    unsigned Reg = getRegForValue(RV);
1465    if (Reg == 0)
1466      return false;
1467
1468    // Only handle a single return value for now.
1469    if (ValLocs.size() != 1)
1470      return false;
1471
1472    CCValAssign &VA = ValLocs[0];
1473
1474    // Don't bother handling odd stuff for now.
1475    if (VA.getLocInfo() != CCValAssign::Full)
1476      return false;
1477    // Only handle register returns for now.
1478    if (!VA.isRegLoc())
1479      return false;
1480    // TODO: For now, don't try to handle cases where getLocInfo()
1481    // says Full but the types don't match.
1482    if (VA.getValVT() != TLI.getValueType(RV->getType()))
1483      return false;
1484
1485    // Make the copy.
1486    unsigned SrcReg = Reg + VA.getValNo();
1487    unsigned DstReg = VA.getLocReg();
1488    const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1489    // Avoid a cross-class copy. This is very unlikely.
1490    if (!SrcRC->contains(DstReg))
1491      return false;
1492    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1493            DstReg).addReg(SrcReg);
1494
1495    // Mark the register as live out of the function.
1496    MRI.addLiveOut(VA.getLocReg());
1497  }
1498
1499  unsigned RetOpc = isThumb ? ARM::tBX_RET : ARM::BX_RET;
1500  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1501                          TII.get(RetOpc)));
1502  return true;
1503}
1504
1505// A quick function that will emit a call for a named libcall in F with the
1506// vector of passed arguments for the Instruction in I. We can assume that we
1507// can emit a call for any libcall we can produce. This is an abridged version
1508// of the full call infrastructure since we won't need to worry about things
1509// like computed function pointers or strange arguments at call sites.
1510// TODO: Try to unify this and the normal call bits for ARM, then try to unify
1511// with X86.
1512bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1513  CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1514
1515  // Handle *simple* calls for now.
1516  const Type *RetTy = I->getType();
1517  EVT RetVT;
1518  if (RetTy->isVoidTy())
1519    RetVT = MVT::isVoid;
1520  else if (!isTypeLegal(RetTy, RetVT))
1521    return false;
1522
1523  // For now we're using BLX etc on the assumption that we have v5t ops.
1524  if (!Subtarget->hasV5TOps()) return false;
1525
1526  // Set up the argument vectors.
1527  SmallVector<Value*, 8> Args;
1528  SmallVector<unsigned, 8> ArgRegs;
1529  SmallVector<EVT, 8> ArgVTs;
1530  SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1531  Args.reserve(I->getNumOperands());
1532  ArgRegs.reserve(I->getNumOperands());
1533  ArgVTs.reserve(I->getNumOperands());
1534  ArgFlags.reserve(I->getNumOperands());
1535  for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1536    Value *Op = I->getOperand(i);
1537    unsigned Arg = getRegForValue(Op);
1538    if (Arg == 0) return false;
1539
1540    const Type *ArgTy = Op->getType();
1541    EVT ArgVT;
1542    if (!isTypeLegal(ArgTy, ArgVT)) return false;
1543
1544    ISD::ArgFlagsTy Flags;
1545    unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1546    Flags.setOrigAlign(OriginalAlignment);
1547
1548    Args.push_back(Op);
1549    ArgRegs.push_back(Arg);
1550    ArgVTs.push_back(ArgVT);
1551    ArgFlags.push_back(Flags);
1552  }
1553
1554  // Handle the arguments now that we've gotten them.
1555  SmallVector<unsigned, 4> RegArgs;
1556  unsigned NumBytes;
1557  if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1558    return false;
1559
1560  // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1561  // TODO: Turn this into the table of arm call ops.
1562  MachineInstrBuilder MIB;
1563  unsigned CallOpc;
1564  if(isThumb)
1565    CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1566  else
1567    CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1568  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1569        .addExternalSymbol(TLI.getLibcallName(Call));
1570
1571  // Add implicit physical register uses to the call.
1572  for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1573    MIB.addReg(RegArgs[i]);
1574
1575  // Finish off the call including any return values.
1576  SmallVector<unsigned, 4> UsedRegs;
1577  if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1578
1579  // Set all unused physreg defs as dead.
1580  static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1581
1582  return true;
1583}
1584
1585bool ARMFastISel::SelectCall(const Instruction *I) {
1586  const CallInst *CI = cast<CallInst>(I);
1587  const Value *Callee = CI->getCalledValue();
1588
1589  // Can't handle inline asm or worry about intrinsics yet.
1590  if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1591
1592  // Only handle global variable Callees that are direct calls.
1593  const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1594  if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1595    return false;
1596
1597  // Check the calling convention.
1598  ImmutableCallSite CS(CI);
1599  CallingConv::ID CC = CS.getCallingConv();
1600
1601  // TODO: Avoid some calling conventions?
1602
1603  // Let SDISel handle vararg functions.
1604  const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1605  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1606  if (FTy->isVarArg())
1607    return false;
1608
1609  // Handle *simple* calls for now.
1610  const Type *RetTy = I->getType();
1611  EVT RetVT;
1612  if (RetTy->isVoidTy())
1613    RetVT = MVT::isVoid;
1614  else if (!isTypeLegal(RetTy, RetVT))
1615    return false;
1616
1617  // For now we're using BLX etc on the assumption that we have v5t ops.
1618  // TODO: Maybe?
1619  if (!Subtarget->hasV5TOps()) return false;
1620
1621  // Set up the argument vectors.
1622  SmallVector<Value*, 8> Args;
1623  SmallVector<unsigned, 8> ArgRegs;
1624  SmallVector<EVT, 8> ArgVTs;
1625  SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1626  Args.reserve(CS.arg_size());
1627  ArgRegs.reserve(CS.arg_size());
1628  ArgVTs.reserve(CS.arg_size());
1629  ArgFlags.reserve(CS.arg_size());
1630  for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1631       i != e; ++i) {
1632    unsigned Arg = getRegForValue(*i);
1633
1634    if (Arg == 0)
1635      return false;
1636    ISD::ArgFlagsTy Flags;
1637    unsigned AttrInd = i - CS.arg_begin() + 1;
1638    if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1639      Flags.setSExt();
1640    if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1641      Flags.setZExt();
1642
1643         // FIXME: Only handle *easy* calls for now.
1644    if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1645        CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1646        CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1647        CS.paramHasAttr(AttrInd, Attribute::ByVal))
1648      return false;
1649
1650    const Type *ArgTy = (*i)->getType();
1651    EVT ArgVT;
1652    if (!isTypeLegal(ArgTy, ArgVT))
1653      return false;
1654    unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1655    Flags.setOrigAlign(OriginalAlignment);
1656
1657    Args.push_back(*i);
1658    ArgRegs.push_back(Arg);
1659    ArgVTs.push_back(ArgVT);
1660    ArgFlags.push_back(Flags);
1661  }
1662
1663  // Handle the arguments now that we've gotten them.
1664  SmallVector<unsigned, 4> RegArgs;
1665  unsigned NumBytes;
1666  if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1667    return false;
1668
1669  // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1670  // TODO: Turn this into the table of arm call ops.
1671  MachineInstrBuilder MIB;
1672  unsigned CallOpc;
1673  if(isThumb)
1674    CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1675  else
1676    CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1677  MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1678              .addGlobalAddress(GV, 0, 0);
1679
1680  // Add implicit physical register uses to the call.
1681  for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1682    MIB.addReg(RegArgs[i]);
1683
1684  // Finish off the call including any return values.
1685  SmallVector<unsigned, 4> UsedRegs;
1686  if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1687
1688  // Set all unused physreg defs as dead.
1689  static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1690
1691  return true;
1692
1693}
1694
1695// TODO: SoftFP support.
1696bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1697  // No Thumb-1 for now.
1698  if (isThumb && !AFI->isThumb2Function()) return false;
1699
1700  switch (I->getOpcode()) {
1701    case Instruction::Load:
1702      return SelectLoad(I);
1703    case Instruction::Store:
1704      return SelectStore(I);
1705    case Instruction::Br:
1706      return SelectBranch(I);
1707    case Instruction::ICmp:
1708    case Instruction::FCmp:
1709      return SelectCmp(I);
1710    case Instruction::FPExt:
1711      return SelectFPExt(I);
1712    case Instruction::FPTrunc:
1713      return SelectFPTrunc(I);
1714    case Instruction::SIToFP:
1715      return SelectSIToFP(I);
1716    case Instruction::FPToSI:
1717      return SelectFPToSI(I);
1718    case Instruction::FAdd:
1719      return SelectBinaryOp(I, ISD::FADD);
1720    case Instruction::FSub:
1721      return SelectBinaryOp(I, ISD::FSUB);
1722    case Instruction::FMul:
1723      return SelectBinaryOp(I, ISD::FMUL);
1724    case Instruction::SDiv:
1725      return SelectSDiv(I);
1726    case Instruction::SRem:
1727      return SelectSRem(I);
1728    case Instruction::Call:
1729      return SelectCall(I);
1730    case Instruction::Select:
1731      return SelectSelect(I);
1732    case Instruction::Ret:
1733      return SelectRet(I);
1734    default: break;
1735  }
1736  return false;
1737}
1738
1739namespace llvm {
1740  llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1741    // Completely untested on non-darwin.
1742    const TargetMachine &TM = funcInfo.MF->getTarget();
1743    const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
1744    if (Subtarget->isTargetDarwin() && !DisableARMFastISel)
1745      return new ARMFastISel(funcInfo);
1746    return 0;
1747  }
1748}
1749