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