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