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