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