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