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