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