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