Update comment.
[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 "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FastISel.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 using namespace llvm;
49
50 static cl::opt<bool>
51 DisableARMFastISel("disable-arm-fast-isel",
52                     cl::desc("Turn off experimental ARM fast-isel support"),
53                     cl::init(false), cl::Hidden);
54
55 namespace {
56   
57   // All possible address modes, plus some.
58   typedef struct Address {
59     enum {
60       RegBase,
61       FrameIndexBase
62     } BaseType;
63     
64     union {
65       unsigned Reg;
66       int FI;
67     } Base;
68     
69     int Offset;
70     unsigned Scale;
71     unsigned PlusReg;
72     
73     // Innocuous defaults for our address.
74     Address()
75      : BaseType(RegBase), Offset(0), Scale(0), PlusReg(0) {
76        Base.Reg = 0;
77      }
78   } Address;
79
80 class ARMFastISel : public FastISel {
81
82   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
83   /// make the right decision when generating code for different targets.
84   const ARMSubtarget *Subtarget;
85   const TargetMachine &TM;
86   const TargetInstrInfo &TII;
87   const TargetLowering &TLI;
88   ARMFunctionInfo *AFI;
89
90   // Convenience variables to avoid some queries.
91   bool isThumb;
92   LLVMContext *Context;
93
94   public:
95     explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
96     : FastISel(funcInfo),
97       TM(funcInfo.MF->getTarget()),
98       TII(*TM.getInstrInfo()),
99       TLI(*TM.getTargetLowering()) {
100       Subtarget = &TM.getSubtarget<ARMSubtarget>();
101       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
102       isThumb = AFI->isThumbFunction();
103       Context = &funcInfo.Fn->getContext();
104     }
105
106     // Code from FastISel.cpp.
107     virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
108                                    const TargetRegisterClass *RC);
109     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
110                                     const TargetRegisterClass *RC,
111                                     unsigned Op0, bool Op0IsKill);
112     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
113                                      const TargetRegisterClass *RC,
114                                      unsigned Op0, bool Op0IsKill,
115                                      unsigned Op1, bool Op1IsKill);
116     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
117                                      const TargetRegisterClass *RC,
118                                      unsigned Op0, bool Op0IsKill,
119                                      uint64_t Imm);
120     virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
121                                      const TargetRegisterClass *RC,
122                                      unsigned Op0, bool Op0IsKill,
123                                      const ConstantFP *FPImm);
124     virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
125                                     const TargetRegisterClass *RC,
126                                     uint64_t Imm);
127     virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
128                                       const TargetRegisterClass *RC,
129                                       unsigned Op0, bool Op0IsKill,
130                                       unsigned Op1, bool Op1IsKill,
131                                       uint64_t Imm);
132     virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
133                                                 unsigned Op0, bool Op0IsKill,
134                                                 uint32_t Idx);
135
136     // Backend specific FastISel code.
137     virtual bool TargetSelectInstruction(const Instruction *I);
138     virtual unsigned TargetMaterializeConstant(const Constant *C);
139     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
140
141   #include "ARMGenFastISel.inc"
142
143     // Instruction selection routines.
144   private:
145     bool SelectLoad(const Instruction *I);
146     bool SelectStore(const Instruction *I);
147     bool SelectBranch(const Instruction *I);
148     bool SelectCmp(const Instruction *I);
149     bool SelectFPExt(const Instruction *I);
150     bool SelectFPTrunc(const Instruction *I);
151     bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
152     bool SelectSIToFP(const Instruction *I);
153     bool SelectFPToSI(const Instruction *I);
154     bool SelectSDiv(const Instruction *I);
155     bool SelectSRem(const Instruction *I);
156     bool SelectCall(const Instruction *I);
157     bool SelectSelect(const Instruction *I);
158     bool SelectRet(const Instruction *I);
159
160     // Utility routines.
161   private:
162     bool isTypeLegal(const Type *Ty, MVT &VT);
163     bool isLoadTypeLegal(const Type *Ty, MVT &VT);
164     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr);
165     bool ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr);
166     bool ARMComputeAddress(const Value *Obj, Address &Addr);
167     void ARMSimplifyAddress(Address &Addr, EVT VT);
168     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
169     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
170     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
171     unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
172     unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
173
174     // Call handling routines.
175   private:
176     bool FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
177                         unsigned &ResultReg);
178     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
179     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
180                          SmallVectorImpl<unsigned> &ArgRegs,
181                          SmallVectorImpl<MVT> &ArgVTs,
182                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
183                          SmallVectorImpl<unsigned> &RegArgs,
184                          CallingConv::ID CC,
185                          unsigned &NumBytes);
186     bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
187                     const Instruction *I, CallingConv::ID CC,
188                     unsigned &NumBytes);
189     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
190
191     // OptionalDef handling routines.
192   private:
193     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
194     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
195 };
196
197 } // end anonymous namespace
198
199 #include "ARMGenCallingConv.inc"
200
201 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
202 // we don't care about implicit defs here, just places we'll need to add a
203 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
204 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
205   const TargetInstrDesc &TID = MI->getDesc();
206   if (!TID.hasOptionalDef())
207     return false;
208
209   // Look to see if our OptionalDef is defining CPSR or CCR.
210   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
211     const MachineOperand &MO = MI->getOperand(i);
212     if (!MO.isReg() || !MO.isDef()) continue;
213     if (MO.getReg() == ARM::CPSR)
214       *CPSR = true;
215   }
216   return true;
217 }
218
219 // If the machine is predicable go ahead and add the predicate operands, if
220 // it needs default CC operands add those.
221 // TODO: If we want to support thumb1 then we'll need to deal with optional
222 // CPSR defs that need to be added before the remaining operands. See s_cc_out
223 // for descriptions why.
224 const MachineInstrBuilder &
225 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
226   MachineInstr *MI = &*MIB;
227
228   // Do we use a predicate?
229   if (TII.isPredicable(MI))
230     AddDefaultPred(MIB);
231
232   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
233   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
234   bool CPSR = false;
235   if (DefinesOptionalPredicate(MI, &CPSR)) {
236     if (CPSR)
237       AddDefaultT1CC(MIB);
238     else
239       AddDefaultCC(MIB);
240   }
241   return MIB;
242 }
243
244 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
245                                     const TargetRegisterClass* RC) {
246   unsigned ResultReg = createResultReg(RC);
247   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
248
249   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
250   return ResultReg;
251 }
252
253 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
254                                      const TargetRegisterClass *RC,
255                                      unsigned Op0, bool Op0IsKill) {
256   unsigned ResultReg = createResultReg(RC);
257   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
258
259   if (II.getNumDefs() >= 1)
260     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
261                    .addReg(Op0, Op0IsKill * RegState::Kill));
262   else {
263     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
264                    .addReg(Op0, Op0IsKill * RegState::Kill));
265     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
266                    TII.get(TargetOpcode::COPY), ResultReg)
267                    .addReg(II.ImplicitDefs[0]));
268   }
269   return ResultReg;
270 }
271
272 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
273                                       const TargetRegisterClass *RC,
274                                       unsigned Op0, bool Op0IsKill,
275                                       unsigned Op1, bool Op1IsKill) {
276   unsigned ResultReg = createResultReg(RC);
277   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
278
279   if (II.getNumDefs() >= 1)
280     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
281                    .addReg(Op0, Op0IsKill * RegState::Kill)
282                    .addReg(Op1, Op1IsKill * RegState::Kill));
283   else {
284     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
285                    .addReg(Op0, Op0IsKill * RegState::Kill)
286                    .addReg(Op1, Op1IsKill * RegState::Kill));
287     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
288                            TII.get(TargetOpcode::COPY), ResultReg)
289                    .addReg(II.ImplicitDefs[0]));
290   }
291   return ResultReg;
292 }
293
294 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
295                                       const TargetRegisterClass *RC,
296                                       unsigned Op0, bool Op0IsKill,
297                                       uint64_t Imm) {
298   unsigned ResultReg = createResultReg(RC);
299   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
300
301   if (II.getNumDefs() >= 1)
302     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
303                    .addReg(Op0, Op0IsKill * RegState::Kill)
304                    .addImm(Imm));
305   else {
306     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
307                    .addReg(Op0, Op0IsKill * RegState::Kill)
308                    .addImm(Imm));
309     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
310                            TII.get(TargetOpcode::COPY), ResultReg)
311                    .addReg(II.ImplicitDefs[0]));
312   }
313   return ResultReg;
314 }
315
316 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
317                                       const TargetRegisterClass *RC,
318                                       unsigned Op0, bool Op0IsKill,
319                                       const ConstantFP *FPImm) {
320   unsigned ResultReg = createResultReg(RC);
321   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
322
323   if (II.getNumDefs() >= 1)
324     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
325                    .addReg(Op0, Op0IsKill * RegState::Kill)
326                    .addFPImm(FPImm));
327   else {
328     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
329                    .addReg(Op0, Op0IsKill * RegState::Kill)
330                    .addFPImm(FPImm));
331     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
332                            TII.get(TargetOpcode::COPY), ResultReg)
333                    .addReg(II.ImplicitDefs[0]));
334   }
335   return ResultReg;
336 }
337
338 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
339                                        const TargetRegisterClass *RC,
340                                        unsigned Op0, bool Op0IsKill,
341                                        unsigned Op1, bool Op1IsKill,
342                                        uint64_t Imm) {
343   unsigned ResultReg = createResultReg(RC);
344   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
345
346   if (II.getNumDefs() >= 1)
347     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
348                    .addReg(Op0, Op0IsKill * RegState::Kill)
349                    .addReg(Op1, Op1IsKill * RegState::Kill)
350                    .addImm(Imm));
351   else {
352     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
353                    .addReg(Op0, Op0IsKill * RegState::Kill)
354                    .addReg(Op1, Op1IsKill * RegState::Kill)
355                    .addImm(Imm));
356     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
357                            TII.get(TargetOpcode::COPY), ResultReg)
358                    .addReg(II.ImplicitDefs[0]));
359   }
360   return ResultReg;
361 }
362
363 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
364                                      const TargetRegisterClass *RC,
365                                      uint64_t Imm) {
366   unsigned ResultReg = createResultReg(RC);
367   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
368
369   if (II.getNumDefs() >= 1)
370     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
371                    .addImm(Imm));
372   else {
373     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
374                    .addImm(Imm));
375     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
376                            TII.get(TargetOpcode::COPY), ResultReg)
377                    .addReg(II.ImplicitDefs[0]));
378   }
379   return ResultReg;
380 }
381
382 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
383                                                  unsigned Op0, bool Op0IsKill,
384                                                  uint32_t Idx) {
385   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
386   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
387          "Cannot yet extract from physregs");
388   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
389                          DL, TII.get(TargetOpcode::COPY), ResultReg)
390                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
391   return ResultReg;
392 }
393
394 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
395 // checks from the various callers.
396 unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
397   if (VT == MVT::f64) return 0;
398
399   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
400   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
401                           TII.get(ARM::VMOVRS), MoveReg)
402                   .addReg(SrcReg));
403   return MoveReg;
404 }
405
406 unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
407   if (VT == MVT::i64) return 0;
408
409   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
410   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
411                           TII.get(ARM::VMOVSR), MoveReg)
412                   .addReg(SrcReg));
413   return MoveReg;
414 }
415
416 // For double width floating point we need to materialize two constants
417 // (the high and the low) into integer registers then use a move to get
418 // the combined constant into an FP reg.
419 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
420   const APFloat Val = CFP->getValueAPF();
421   bool is64bit = VT == MVT::f64;
422
423   // This checks to see if we can use VFP3 instructions to materialize
424   // a constant, otherwise we have to go through the constant pool.
425   if (TLI.isFPImmLegal(Val, VT)) {
426     unsigned Opc = is64bit ? ARM::FCONSTD : ARM::FCONSTS;
427     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
428     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
429                             DestReg)
430                     .addFPImm(CFP));
431     return DestReg;
432   }
433
434   // Require VFP2 for loading fp constants.
435   if (!Subtarget->hasVFP2()) return false;
436
437   // MachineConstantPool wants an explicit alignment.
438   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
439   if (Align == 0) {
440     // TODO: Figure out if this is correct.
441     Align = TD.getTypeAllocSize(CFP->getType());
442   }
443   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
444   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
445   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
446
447   // The extra reg is for addrmode5.
448   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
449                           DestReg)
450                   .addConstantPoolIndex(Idx)
451                   .addReg(0));
452   return DestReg;
453 }
454
455 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
456
457   // For now 32-bit only.
458   if (VT != MVT::i32) return false;
459
460   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
461
462   // If we can do this in a single instruction without a constant pool entry
463   // do so now.
464   const ConstantInt *CI = cast<ConstantInt>(C);
465   if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getSExtValue())) {
466     unsigned Opc = isThumb ? ARM::t2MOVi16 : ARM::MOVi16;
467     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
468                             TII.get(Opc), DestReg)
469                     .addImm(CI->getSExtValue()));
470     return DestReg;
471   }
472
473   // MachineConstantPool wants an explicit alignment.
474   unsigned Align = TD.getPrefTypeAlignment(C->getType());
475   if (Align == 0) {
476     // TODO: Figure out if this is correct.
477     Align = TD.getTypeAllocSize(C->getType());
478   }
479   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
480
481   if (isThumb)
482     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
483                             TII.get(ARM::t2LDRpci), DestReg)
484                     .addConstantPoolIndex(Idx));
485   else
486     // The extra immediate is for addrmode2.
487     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
488                             TII.get(ARM::LDRcp), DestReg)
489                     .addConstantPoolIndex(Idx)
490                     .addImm(0));
491
492   return DestReg;
493 }
494
495 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
496   // For now 32-bit only.
497   if (VT != MVT::i32) return 0;
498
499   Reloc::Model RelocM = TM.getRelocationModel();
500
501   // TODO: No external globals for now.
502   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) return 0;
503
504   // TODO: Need more magic for ARM PIC.
505   if (!isThumb && (RelocM == Reloc::PIC_)) return 0;
506
507   // MachineConstantPool wants an explicit alignment.
508   unsigned Align = TD.getPrefTypeAlignment(GV->getType());
509   if (Align == 0) {
510     // TODO: Figure out if this is correct.
511     Align = TD.getTypeAllocSize(GV->getType());
512   }
513
514   // Grab index.
515   unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb() ? 4 : 8);
516   unsigned Id = AFI->createConstPoolEntryUId();
517   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, Id,
518                                                        ARMCP::CPValue, PCAdj);
519   unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
520
521   // Load value.
522   MachineInstrBuilder MIB;
523   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
524   if (isThumb) {
525     unsigned Opc = (RelocM != Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
526     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
527           .addConstantPoolIndex(Idx);
528     if (RelocM == Reloc::PIC_)
529       MIB.addImm(Id);
530   } else {
531     // The extra immediate is for addrmode2.
532     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
533                   DestReg)
534           .addConstantPoolIndex(Idx)
535           .addImm(0);
536   }
537   AddOptionalDefs(MIB);
538   return DestReg;
539 }
540
541 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
542   EVT VT = TLI.getValueType(C->getType(), true);
543
544   // Only handle simple types.
545   if (!VT.isSimple()) return 0;
546
547   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
548     return ARMMaterializeFP(CFP, VT);
549   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
550     return ARMMaterializeGV(GV, VT);
551   else if (isa<ConstantInt>(C))
552     return ARMMaterializeInt(C, VT);
553
554   return 0;
555 }
556
557 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
558   // Don't handle dynamic allocas.
559   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
560
561   MVT VT;
562   if (!isLoadTypeLegal(AI->getType(), VT)) return false;
563
564   DenseMap<const AllocaInst*, int>::iterator SI =
565     FuncInfo.StaticAllocaMap.find(AI);
566
567   // This will get lowered later into the correct offsets and registers
568   // via rewriteXFrameIndex.
569   if (SI != FuncInfo.StaticAllocaMap.end()) {
570     TargetRegisterClass* RC = TLI.getRegClassFor(VT);
571     unsigned ResultReg = createResultReg(RC);
572     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
573     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
574                             TII.get(Opc), ResultReg)
575                             .addFrameIndex(SI->second)
576                             .addImm(0));
577     return ResultReg;
578   }
579
580   return 0;
581 }
582
583 bool ARMFastISel::isTypeLegal(const Type *Ty, MVT &VT) {
584   EVT evt = TLI.getValueType(Ty, true);
585
586   // Only handle simple types.
587   if (evt == MVT::Other || !evt.isSimple()) return false;
588   VT = evt.getSimpleVT();
589
590   // Handle all legal types, i.e. a register that will directly hold this
591   // value.
592   return TLI.isTypeLegal(VT);
593 }
594
595 bool ARMFastISel::isLoadTypeLegal(const Type *Ty, MVT &VT) {
596   if (isTypeLegal(Ty, VT)) return true;
597
598   // If this is a type than can be sign or zero-extended to a basic operation
599   // go ahead and accept it now.
600   if (VT == MVT::i8 || VT == MVT::i16)
601     return true;
602
603   return false;
604 }
605
606 // Computes the address to get to an object.
607 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
608   // Some boilerplate from the X86 FastISel.
609   const User *U = NULL;
610   unsigned Opcode = Instruction::UserOp1;
611   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
612     // Don't walk into other basic blocks; it's possible we haven't
613     // visited them yet, so the instructions may not yet be assigned
614     // virtual registers.
615     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
616         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
617       Opcode = I->getOpcode();
618       U = I;
619     }
620   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
621     Opcode = C->getOpcode();
622     U = C;
623   }
624
625   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
626     if (Ty->getAddressSpace() > 255)
627       // Fast instruction selection doesn't support the special
628       // address spaces.
629       return false;
630
631   switch (Opcode) {
632     default:
633     break;
634     case Instruction::BitCast: {
635       // Look through bitcasts.
636       return ARMComputeAddress(U->getOperand(0), Addr);
637     }
638     case Instruction::IntToPtr: {
639       // Look past no-op inttoptrs.
640       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
641         return ARMComputeAddress(U->getOperand(0), Addr);
642       break;
643     }
644     case Instruction::PtrToInt: {
645       // Look past no-op ptrtoints.
646       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
647         return ARMComputeAddress(U->getOperand(0), Addr);
648       break;
649     }
650     case Instruction::GetElementPtr: {
651       int SavedOffset = Addr.Offset;
652       unsigned SavedBase = Addr.Base.Reg;
653       int TmpOffset = Addr.Offset;
654
655       // Iterate through the GEP folding the constants into offsets where
656       // we can.
657       gep_type_iterator GTI = gep_type_begin(U);
658       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
659            i != e; ++i, ++GTI) {
660         const Value *Op = *i;
661         if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
662           const StructLayout *SL = TD.getStructLayout(STy);
663           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
664           TmpOffset += SL->getElementOffset(Idx);
665         } else {
666           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
667           SmallVector<const Value *, 4> Worklist;
668           Worklist.push_back(Op);
669           do {
670             Op = Worklist.pop_back_val();
671             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
672               // Constant-offset addressing.
673               TmpOffset += CI->getSExtValue() * S;
674             } else if (isa<AddOperator>(Op) &&
675                        isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
676               // An add with a constant operand. Fold the constant.
677               ConstantInt *CI =
678                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
679               TmpOffset += CI->getSExtValue() * S;
680               // Add the other operand back to the work list.
681               Worklist.push_back(cast<AddOperator>(Op)->getOperand(0));
682             } else
683               goto unsupported_gep;
684           } while (!Worklist.empty());
685         }
686       }
687
688       // Try to grab the base operand now.
689       Addr.Offset = TmpOffset;
690       if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
691
692       // We failed, restore everything and try the other options.
693       Addr.Offset = SavedOffset;
694       Addr.Base.Reg = SavedBase;
695
696       unsupported_gep:
697       break;
698     }
699     case Instruction::Alloca: {
700       const AllocaInst *AI = cast<AllocaInst>(Obj);
701       unsigned Reg = TargetMaterializeAlloca(AI);
702
703       if (Reg == 0) return false;
704
705       Addr.Base.Reg = Reg;
706       return true;
707     }
708   }
709
710   // Materialize the global variable's address into a reg which can
711   // then be used later to load the variable.
712   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
713     unsigned Tmp = ARMMaterializeGV(GV, TLI.getValueType(Obj->getType()));
714     if (Tmp == 0) return false;
715
716     Addr.Base.Reg = Tmp;
717     return true;
718   }
719
720   // Try to get this in a register if nothing else has worked.
721   if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
722   return Addr.Base.Reg != 0;
723 }
724
725 void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT) {
726
727   assert(VT.isSimple() && "Non-simple types are invalid here!");
728
729   bool needsLowering = false;
730   switch (VT.getSimpleVT().SimpleTy) {
731     default:
732       assert(false && "Unhandled load/store type!");
733     case MVT::i1:
734     case MVT::i8:
735     case MVT::i16:
736     case MVT::i32:
737       // Integer loads/stores handle 12-bit offsets.
738       needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
739       break;
740     case MVT::f32:
741     case MVT::f64:
742       // Floating point operands handle 8-bit offsets.
743       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
744       break;
745   }
746
747   // Since the offset is too large for the load/store instruction
748   // get the reg+offset into a register.
749   if (needsLowering) {
750     ARMCC::CondCodes Pred = ARMCC::AL;
751     unsigned PredReg = 0;
752
753     TargetRegisterClass *RC = isThumb ? ARM::tGPRRegisterClass :
754       ARM::GPRRegisterClass;
755     unsigned BaseReg = createResultReg(RC);
756
757     if (!isThumb)
758       emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
759                               BaseReg, Addr.Base.Reg, Addr.Offset,
760                               Pred, PredReg,
761                               static_cast<const ARMBaseInstrInfo&>(TII));
762     else {
763       assert(AFI->isThumb2Function());
764       emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
765                              BaseReg, Addr.Base.Reg, Addr.Offset, Pred, PredReg,
766                              static_cast<const ARMBaseInstrInfo&>(TII));
767     }
768     Addr.Offset = 0;
769     Addr.Base.Reg = BaseReg;
770   }
771 }
772
773 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr) {
774
775   assert(VT.isSimple() && "Non-simple types are invalid here!");
776   unsigned Opc;
777   TargetRegisterClass *RC;
778   bool isFloat = false;
779   switch (VT.getSimpleVT().SimpleTy) {
780     default:
781       // This is mostly going to be Neon/vector support.
782       return false;
783     case MVT::i16:
784       Opc = isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
785       RC = ARM::GPRRegisterClass;
786       break;
787     case MVT::i8:
788       Opc = isThumb ? ARM::t2LDRBi12 : ARM::LDRBi12;
789       RC = ARM::GPRRegisterClass;
790       break;
791     case MVT::i32:
792       Opc = isThumb ? ARM::t2LDRi12 : ARM::LDRi12;
793       RC = ARM::GPRRegisterClass;
794       break;
795     case MVT::f32:
796       Opc = ARM::VLDRS;
797       RC = TLI.getRegClassFor(VT);
798       isFloat = true;
799       break;
800     case MVT::f64:
801       Opc = ARM::VLDRD;
802       RC = TLI.getRegClassFor(VT);
803       isFloat = true;
804       break;
805   }
806
807   ResultReg = createResultReg(RC);
808
809   ARMSimplifyAddress(Addr, VT);
810
811   // addrmode5 output depends on the selection dag addressing dividing the
812   // offset by 4 that it then later multiplies. Do this here as well.
813   if (isFloat)
814     Addr.Offset /= 4;
815
816   // LDRH needs an additional operand.
817   if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16)
818     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
819                             TII.get(Opc), ResultReg)
820                     .addReg(Addr.Base.Reg).addReg(0).addImm(Addr.Offset));
821   else
822     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
823                             TII.get(Opc), ResultReg)
824                     .addReg(Addr.Base.Reg).addImm(Addr.Offset));
825   return true;
826 }
827
828 bool ARMFastISel::SelectLoad(const Instruction *I) {
829   // Verify we have a legal type before going any further.
830   MVT VT;
831   if (!isLoadTypeLegal(I->getType(), VT))
832     return false;
833
834   // Our register and offset with innocuous defaults.
835   Address Addr;
836
837   // See if we can handle this as Reg + Offset
838   if (!ARMComputeAddress(I->getOperand(0), Addr))
839     return false;
840
841   unsigned ResultReg;
842   if (!ARMEmitLoad(VT, ResultReg, Addr)) return false;
843
844   UpdateValueMap(I, ResultReg);
845   return true;
846 }
847
848 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr) {
849   unsigned StrOpc;
850   bool isFloat = false;
851   bool needReg0Op = false;
852   switch (VT.getSimpleVT().SimpleTy) {
853     default: return false;
854     case MVT::i1: {
855       unsigned Res = createResultReg(isThumb ? ARM::tGPRRegisterClass :
856                                                ARM::GPRRegisterClass);
857       unsigned Opc = isThumb ? ARM::t2ANDri : ARM::ANDri;
858       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
859                               TII.get(Opc), Res)
860                       .addReg(SrcReg).addImm(1));
861       SrcReg = Res;
862     } // Fallthrough here.
863     case MVT::i8:
864       StrOpc = isThumb ? ARM::t2STRBi12 : ARM::STRBi12;
865       break;
866     case MVT::i16:
867       StrOpc = isThumb ? ARM::t2STRHi12 : ARM::STRH;
868       needReg0Op = true;
869       break;
870     case MVT::i32:
871       StrOpc = isThumb ? ARM::t2STRi12 : ARM::STRi12;
872       break;
873     case MVT::f32:
874       if (!Subtarget->hasVFP2()) return false;
875       StrOpc = ARM::VSTRS;
876       isFloat = true;
877       break;
878     case MVT::f64:
879       if (!Subtarget->hasVFP2()) return false;
880       StrOpc = ARM::VSTRD;
881       isFloat = true;
882       break;
883   }
884
885   ARMSimplifyAddress(Addr, VT);
886
887   // addrmode5 output depends on the selection dag addressing dividing the
888   // offset by 4 that it then later multiplies. Do this here as well.
889   if (isFloat)
890     Addr.Offset /= 4;
891
892   // FIXME: The 'needReg0Op' bit goes away once STRH is converted to
893   // not use the mega-addrmode stuff.
894   if (!needReg0Op)
895     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
896                             TII.get(StrOpc))
897                     .addReg(SrcReg).addReg(Addr.Base.Reg).addImm(Addr.Offset));
898   else
899     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
900                             TII.get(StrOpc))
901                     .addReg(SrcReg).addReg(Addr.Base.Reg)
902                     .addReg(0).addImm(Addr.Offset));
903
904   return true;
905 }
906
907 bool ARMFastISel::SelectStore(const Instruction *I) {
908   Value *Op0 = I->getOperand(0);
909   unsigned SrcReg = 0;
910
911   // Yay type legalization
912   MVT VT;
913   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
914     return false;
915
916   // Get the value to be stored into a register.
917   SrcReg = getRegForValue(Op0);
918   if (SrcReg == 0)
919     return false;
920
921   // Our register and offset with innocuous defaults.
922   Address Addr;
923
924   // See if we can handle this as Reg + Offset
925   if (!ARMComputeAddress(I->getOperand(1), Addr))
926     return false;
927
928   if (!ARMEmitStore(VT, SrcReg, Addr)) return false;
929
930   return true;
931 }
932
933 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
934   switch (Pred) {
935     // Needs two compares...
936     case CmpInst::FCMP_ONE:
937     case CmpInst::FCMP_UEQ:
938     default:
939       // AL is our "false" for now. The other two need more compares.
940       return ARMCC::AL;
941     case CmpInst::ICMP_EQ:
942     case CmpInst::FCMP_OEQ:
943       return ARMCC::EQ;
944     case CmpInst::ICMP_SGT:
945     case CmpInst::FCMP_OGT:
946       return ARMCC::GT;
947     case CmpInst::ICMP_SGE:
948     case CmpInst::FCMP_OGE:
949       return ARMCC::GE;
950     case CmpInst::ICMP_UGT:
951     case CmpInst::FCMP_UGT:
952       return ARMCC::HI;
953     case CmpInst::FCMP_OLT:
954       return ARMCC::MI;
955     case CmpInst::ICMP_ULE:
956     case CmpInst::FCMP_OLE:
957       return ARMCC::LS;
958     case CmpInst::FCMP_ORD:
959       return ARMCC::VC;
960     case CmpInst::FCMP_UNO:
961       return ARMCC::VS;
962     case CmpInst::FCMP_UGE:
963       return ARMCC::PL;
964     case CmpInst::ICMP_SLT:
965     case CmpInst::FCMP_ULT:
966       return ARMCC::LT;
967     case CmpInst::ICMP_SLE:
968     case CmpInst::FCMP_ULE:
969       return ARMCC::LE;
970     case CmpInst::FCMP_UNE:
971     case CmpInst::ICMP_NE:
972       return ARMCC::NE;
973     case CmpInst::ICMP_UGE:
974       return ARMCC::HS;
975     case CmpInst::ICMP_ULT:
976       return ARMCC::LO;
977   }
978 }
979
980 bool ARMFastISel::SelectBranch(const Instruction *I) {
981   const BranchInst *BI = cast<BranchInst>(I);
982   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
983   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
984
985   // Simple branch support.
986
987   // If we can, avoid recomputing the compare - redoing it could lead to wonky
988   // behavior.
989   // TODO: Factor this out.
990   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
991     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
992       MVT VT;
993       const Type *Ty = CI->getOperand(0)->getType();
994       if (!isTypeLegal(Ty, VT))
995         return false;
996
997       bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
998       if (isFloat && !Subtarget->hasVFP2())
999         return false;
1000
1001       unsigned CmpOpc;
1002       unsigned CondReg;
1003       switch (VT.SimpleTy) {
1004         default: return false;
1005         // TODO: Verify compares.
1006         case MVT::f32:
1007           CmpOpc = ARM::VCMPES;
1008           CondReg = ARM::FPSCR;
1009           break;
1010         case MVT::f64:
1011           CmpOpc = ARM::VCMPED;
1012           CondReg = ARM::FPSCR;
1013           break;
1014         case MVT::i32:
1015           CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1016           CondReg = ARM::CPSR;
1017           break;
1018       }
1019
1020       // Get the compare predicate.
1021       ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1022
1023       // We may not handle every CC for now.
1024       if (ARMPred == ARMCC::AL) return false;
1025
1026       unsigned Arg1 = getRegForValue(CI->getOperand(0));
1027       if (Arg1 == 0) return false;
1028
1029       unsigned Arg2 = getRegForValue(CI->getOperand(1));
1030       if (Arg2 == 0) return false;
1031
1032       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1033                               TII.get(CmpOpc))
1034                       .addReg(Arg1).addReg(Arg2));
1035
1036       // For floating point we need to move the result to a comparison register
1037       // that we can then use for branches.
1038       if (isFloat)
1039         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1040                                 TII.get(ARM::FMSTAT)));
1041
1042       unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1043       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1044       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1045       FastEmitBranch(FBB, DL);
1046       FuncInfo.MBB->addSuccessor(TBB);
1047       return true;
1048     }
1049   }
1050
1051   unsigned CmpReg = getRegForValue(BI->getCondition());
1052   if (CmpReg == 0) return false;
1053
1054   // Re-set the flags just in case.
1055   unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
1056   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1057                   .addReg(CmpReg).addImm(0));
1058
1059   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1060   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1061                   .addMBB(TBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
1062   FastEmitBranch(FBB, DL);
1063   FuncInfo.MBB->addSuccessor(TBB);
1064   return true;
1065 }
1066
1067 bool ARMFastISel::SelectCmp(const Instruction *I) {
1068   const CmpInst *CI = cast<CmpInst>(I);
1069
1070   MVT VT;
1071   const Type *Ty = CI->getOperand(0)->getType();
1072   if (!isTypeLegal(Ty, VT))
1073     return false;
1074
1075   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1076   if (isFloat && !Subtarget->hasVFP2())
1077     return false;
1078
1079   unsigned CmpOpc;
1080   unsigned CondReg;
1081   switch (VT.SimpleTy) {
1082     default: return false;
1083     // TODO: Verify compares.
1084     case MVT::f32:
1085       CmpOpc = ARM::VCMPES;
1086       CondReg = ARM::FPSCR;
1087       break;
1088     case MVT::f64:
1089       CmpOpc = ARM::VCMPED;
1090       CondReg = ARM::FPSCR;
1091       break;
1092     case MVT::i32:
1093       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1094       CondReg = ARM::CPSR;
1095       break;
1096   }
1097
1098   // Get the compare predicate.
1099   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1100
1101   // We may not handle every CC for now.
1102   if (ARMPred == ARMCC::AL) return false;
1103
1104   unsigned Arg1 = getRegForValue(CI->getOperand(0));
1105   if (Arg1 == 0) return false;
1106
1107   unsigned Arg2 = getRegForValue(CI->getOperand(1));
1108   if (Arg2 == 0) return false;
1109
1110   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1111                   .addReg(Arg1).addReg(Arg2));
1112
1113   // For floating point we need to move the result to a comparison register
1114   // that we can then use for branches.
1115   if (isFloat)
1116     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1117                             TII.get(ARM::FMSTAT)));
1118
1119   // Now set a register based on the comparison. Explicitly set the predicates
1120   // here.
1121   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
1122   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass
1123                                     : ARM::GPRRegisterClass;
1124   unsigned DestReg = createResultReg(RC);
1125   Constant *Zero
1126     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1127   unsigned ZeroReg = TargetMaterializeConstant(Zero);
1128   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1129           .addReg(ZeroReg).addImm(1)
1130           .addImm(ARMPred).addReg(CondReg);
1131
1132   UpdateValueMap(I, DestReg);
1133   return true;
1134 }
1135
1136 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1137   // Make sure we have VFP and that we're extending float to double.
1138   if (!Subtarget->hasVFP2()) return false;
1139
1140   Value *V = I->getOperand(0);
1141   if (!I->getType()->isDoubleTy() ||
1142       !V->getType()->isFloatTy()) return false;
1143
1144   unsigned Op = getRegForValue(V);
1145   if (Op == 0) return false;
1146
1147   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1148   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1149                           TII.get(ARM::VCVTDS), Result)
1150                   .addReg(Op));
1151   UpdateValueMap(I, Result);
1152   return true;
1153 }
1154
1155 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1156   // Make sure we have VFP and that we're truncating double to float.
1157   if (!Subtarget->hasVFP2()) return false;
1158
1159   Value *V = I->getOperand(0);
1160   if (!(I->getType()->isFloatTy() &&
1161         V->getType()->isDoubleTy())) return false;
1162
1163   unsigned Op = getRegForValue(V);
1164   if (Op == 0) return false;
1165
1166   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1167   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1168                           TII.get(ARM::VCVTSD), Result)
1169                   .addReg(Op));
1170   UpdateValueMap(I, Result);
1171   return true;
1172 }
1173
1174 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1175   // Make sure we have VFP.
1176   if (!Subtarget->hasVFP2()) return false;
1177
1178   MVT DstVT;
1179   const Type *Ty = I->getType();
1180   if (!isTypeLegal(Ty, DstVT))
1181     return false;
1182
1183   unsigned Op = getRegForValue(I->getOperand(0));
1184   if (Op == 0) return false;
1185
1186   // The conversion routine works on fp-reg to fp-reg and the operand above
1187   // was an integer, move it to the fp registers if possible.
1188   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1189   if (FP == 0) return false;
1190
1191   unsigned Opc;
1192   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1193   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1194   else return 0;
1195
1196   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1197   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1198                           ResultReg)
1199                   .addReg(FP));
1200   UpdateValueMap(I, ResultReg);
1201   return true;
1202 }
1203
1204 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1205   // Make sure we have VFP.
1206   if (!Subtarget->hasVFP2()) return false;
1207
1208   MVT DstVT;
1209   const Type *RetTy = I->getType();
1210   if (!isTypeLegal(RetTy, DstVT))
1211     return false;
1212
1213   unsigned Op = getRegForValue(I->getOperand(0));
1214   if (Op == 0) return false;
1215
1216   unsigned Opc;
1217   const Type *OpTy = I->getOperand(0)->getType();
1218   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1219   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1220   else return 0;
1221
1222   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1223   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1224   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1225                           ResultReg)
1226                   .addReg(Op));
1227
1228   // This result needs to be in an integer register, but the conversion only
1229   // takes place in fp-regs.
1230   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1231   if (IntReg == 0) return false;
1232
1233   UpdateValueMap(I, IntReg);
1234   return true;
1235 }
1236
1237 bool ARMFastISel::SelectSelect(const Instruction *I) {
1238   MVT VT;
1239   if (!isTypeLegal(I->getType(), VT))
1240     return false;
1241
1242   // Things need to be register sized for register moves.
1243   if (VT != MVT::i32) return false;
1244   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1245
1246   unsigned CondReg = getRegForValue(I->getOperand(0));
1247   if (CondReg == 0) return false;
1248   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1249   if (Op1Reg == 0) return false;
1250   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1251   if (Op2Reg == 0) return false;
1252
1253   unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1254   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1255                   .addReg(CondReg).addImm(1));
1256   unsigned ResultReg = createResultReg(RC);
1257   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1258   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1259     .addReg(Op1Reg).addReg(Op2Reg)
1260     .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1261   UpdateValueMap(I, ResultReg);
1262   return true;
1263 }
1264
1265 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1266   MVT VT;
1267   const Type *Ty = I->getType();
1268   if (!isTypeLegal(Ty, VT))
1269     return false;
1270
1271   // If we have integer div support we should have selected this automagically.
1272   // In case we have a real miss go ahead and return false and we'll pick
1273   // it up later.
1274   if (Subtarget->hasDivide()) return false;
1275
1276   // Otherwise emit a libcall.
1277   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1278   if (VT == MVT::i8)
1279     LC = RTLIB::SDIV_I8;
1280   else if (VT == MVT::i16)
1281     LC = RTLIB::SDIV_I16;
1282   else if (VT == MVT::i32)
1283     LC = RTLIB::SDIV_I32;
1284   else if (VT == MVT::i64)
1285     LC = RTLIB::SDIV_I64;
1286   else if (VT == MVT::i128)
1287     LC = RTLIB::SDIV_I128;
1288   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1289
1290   return ARMEmitLibcall(I, LC);
1291 }
1292
1293 bool ARMFastISel::SelectSRem(const Instruction *I) {
1294   MVT VT;
1295   const Type *Ty = I->getType();
1296   if (!isTypeLegal(Ty, VT))
1297     return false;
1298
1299   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1300   if (VT == MVT::i8)
1301     LC = RTLIB::SREM_I8;
1302   else if (VT == MVT::i16)
1303     LC = RTLIB::SREM_I16;
1304   else if (VT == MVT::i32)
1305     LC = RTLIB::SREM_I32;
1306   else if (VT == MVT::i64)
1307     LC = RTLIB::SREM_I64;
1308   else if (VT == MVT::i128)
1309     LC = RTLIB::SREM_I128;
1310   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1311
1312   return ARMEmitLibcall(I, LC);
1313 }
1314
1315 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1316   EVT VT  = TLI.getValueType(I->getType(), true);
1317
1318   // We can get here in the case when we want to use NEON for our fp
1319   // operations, but can't figure out how to. Just use the vfp instructions
1320   // if we have them.
1321   // FIXME: It'd be nice to use NEON instructions.
1322   const Type *Ty = I->getType();
1323   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1324   if (isFloat && !Subtarget->hasVFP2())
1325     return false;
1326
1327   unsigned Op1 = getRegForValue(I->getOperand(0));
1328   if (Op1 == 0) return false;
1329
1330   unsigned Op2 = getRegForValue(I->getOperand(1));
1331   if (Op2 == 0) return false;
1332
1333   unsigned Opc;
1334   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1335   switch (ISDOpcode) {
1336     default: return false;
1337     case ISD::FADD:
1338       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1339       break;
1340     case ISD::FSUB:
1341       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1342       break;
1343     case ISD::FMUL:
1344       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1345       break;
1346   }
1347   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1348   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1349                           TII.get(Opc), ResultReg)
1350                   .addReg(Op1).addReg(Op2));
1351   UpdateValueMap(I, ResultReg);
1352   return true;
1353 }
1354
1355 // Call Handling Code
1356
1357 bool ARMFastISel::FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src,
1358                                  EVT SrcVT, unsigned &ResultReg) {
1359   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
1360                            Src, /*TODO: Kill=*/false);
1361
1362   if (RR != 0) {
1363     ResultReg = RR;
1364     return true;
1365   } else
1366     return false;
1367 }
1368
1369 // This is largely taken directly from CCAssignFnForNode - we don't support
1370 // varargs in FastISel so that part has been removed.
1371 // TODO: We may not support all of this.
1372 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1373   switch (CC) {
1374   default:
1375     llvm_unreachable("Unsupported calling convention");
1376   case CallingConv::Fast:
1377     // Ignore fastcc. Silence compiler warnings.
1378     (void)RetFastCC_ARM_APCS;
1379     (void)FastCC_ARM_APCS;
1380     // Fallthrough
1381   case CallingConv::C:
1382     // Use target triple & subtarget features to do actual dispatch.
1383     if (Subtarget->isAAPCS_ABI()) {
1384       if (Subtarget->hasVFP2() &&
1385           FloatABIType == FloatABI::Hard)
1386         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1387       else
1388         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1389     } else
1390         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1391   case CallingConv::ARM_AAPCS_VFP:
1392     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1393   case CallingConv::ARM_AAPCS:
1394     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1395   case CallingConv::ARM_APCS:
1396     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1397   }
1398 }
1399
1400 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1401                                   SmallVectorImpl<unsigned> &ArgRegs,
1402                                   SmallVectorImpl<MVT> &ArgVTs,
1403                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1404                                   SmallVectorImpl<unsigned> &RegArgs,
1405                                   CallingConv::ID CC,
1406                                   unsigned &NumBytes) {
1407   SmallVector<CCValAssign, 16> ArgLocs;
1408   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1409   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1410
1411   // Get a count of how many bytes are to be pushed on the stack.
1412   NumBytes = CCInfo.getNextStackOffset();
1413
1414   // Issue CALLSEQ_START
1415   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1416   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1417                           TII.get(AdjStackDown))
1418                   .addImm(NumBytes));
1419
1420   // Process the args.
1421   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1422     CCValAssign &VA = ArgLocs[i];
1423     unsigned Arg = ArgRegs[VA.getValNo()];
1424     MVT ArgVT = ArgVTs[VA.getValNo()];
1425
1426     // We don't handle NEON parameters yet.
1427     if (VA.getLocVT().isVector() && VA.getLocVT().getSizeInBits() > 64)
1428       return false;
1429
1430     // Handle arg promotion, etc.
1431     switch (VA.getLocInfo()) {
1432       case CCValAssign::Full: break;
1433       case CCValAssign::SExt: {
1434         bool Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1435                                          Arg, ArgVT, Arg);
1436         assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1437         Emitted = true;
1438         ArgVT = VA.getLocVT();
1439         break;
1440       }
1441       case CCValAssign::ZExt: {
1442         bool Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1443                                          Arg, ArgVT, Arg);
1444         assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1445         Emitted = true;
1446         ArgVT = VA.getLocVT();
1447         break;
1448       }
1449       case CCValAssign::AExt: {
1450         bool Emitted = FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1451                                          Arg, ArgVT, Arg);
1452         if (!Emitted)
1453           Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1454                                       Arg, ArgVT, Arg);
1455         if (!Emitted)
1456           Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1457                                       Arg, ArgVT, Arg);
1458
1459         assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1460         ArgVT = VA.getLocVT();
1461         break;
1462       }
1463       case CCValAssign::BCvt: {
1464         unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BIT_CONVERT, Arg,
1465                                  /*TODO: Kill=*/false);
1466         assert(BC != 0 && "Failed to emit a bitcast!");
1467         Arg = BC;
1468         ArgVT = VA.getLocVT();
1469         break;
1470       }
1471       default: llvm_unreachable("Unknown arg promotion!");
1472     }
1473
1474     // Now copy/store arg to correct locations.
1475     if (VA.isRegLoc() && !VA.needsCustom()) {
1476       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1477               VA.getLocReg())
1478       .addReg(Arg);
1479       RegArgs.push_back(VA.getLocReg());
1480     } else if (VA.needsCustom()) {
1481       // TODO: We need custom lowering for vector (v2f64) args.
1482       if (VA.getLocVT() != MVT::f64) return false;
1483
1484       CCValAssign &NextVA = ArgLocs[++i];
1485
1486       // TODO: Only handle register args for now.
1487       if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1488
1489       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1490                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1491                       .addReg(NextVA.getLocReg(), RegState::Define)
1492                       .addReg(Arg));
1493       RegArgs.push_back(VA.getLocReg());
1494       RegArgs.push_back(NextVA.getLocReg());
1495     } else {
1496       assert(VA.isMemLoc());
1497       // Need to store on the stack.
1498       Address Addr;
1499       Addr.BaseType = Address::RegBase;
1500       Addr.Base.Reg = ARM::SP;
1501       Addr.Offset = VA.getLocMemOffset();
1502
1503       if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
1504     }
1505   }
1506   return true;
1507 }
1508
1509 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1510                              const Instruction *I, CallingConv::ID CC,
1511                              unsigned &NumBytes) {
1512   // Issue CALLSEQ_END
1513   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1514   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1515                           TII.get(AdjStackUp))
1516                   .addImm(NumBytes).addImm(0));
1517
1518   // Now the return value.
1519   if (RetVT != MVT::isVoid) {
1520     SmallVector<CCValAssign, 16> RVLocs;
1521     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1522     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1523
1524     // Copy all of the result registers out of their specified physreg.
1525     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
1526       // For this move we copy into two registers and then move into the
1527       // double fp reg we want.
1528       EVT DestVT = RVLocs[0].getValVT();
1529       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1530       unsigned ResultReg = createResultReg(DstRC);
1531       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1532                               TII.get(ARM::VMOVDRR), ResultReg)
1533                       .addReg(RVLocs[0].getLocReg())
1534                       .addReg(RVLocs[1].getLocReg()));
1535
1536       UsedRegs.push_back(RVLocs[0].getLocReg());
1537       UsedRegs.push_back(RVLocs[1].getLocReg());
1538
1539       // Finally update the result.
1540       UpdateValueMap(I, ResultReg);
1541     } else {
1542       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1543       EVT CopyVT = RVLocs[0].getValVT();
1544       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1545
1546       unsigned ResultReg = createResultReg(DstRC);
1547       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1548               ResultReg).addReg(RVLocs[0].getLocReg());
1549       UsedRegs.push_back(RVLocs[0].getLocReg());
1550
1551       // Finally update the result.
1552       UpdateValueMap(I, ResultReg);
1553     }
1554   }
1555
1556   return true;
1557 }
1558
1559 bool ARMFastISel::SelectRet(const Instruction *I) {
1560   const ReturnInst *Ret = cast<ReturnInst>(I);
1561   const Function &F = *I->getParent()->getParent();
1562
1563   if (!FuncInfo.CanLowerReturn)
1564     return false;
1565
1566   if (F.isVarArg())
1567     return false;
1568
1569   CallingConv::ID CC = F.getCallingConv();
1570   if (Ret->getNumOperands() > 0) {
1571     SmallVector<ISD::OutputArg, 4> Outs;
1572     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1573                   Outs, TLI);
1574
1575     // Analyze operands of the call, assigning locations to each operand.
1576     SmallVector<CCValAssign, 16> ValLocs;
1577     CCState CCInfo(CC, F.isVarArg(), TM, ValLocs, I->getContext());
1578     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1579
1580     const Value *RV = Ret->getOperand(0);
1581     unsigned Reg = getRegForValue(RV);
1582     if (Reg == 0)
1583       return false;
1584
1585     // Only handle a single return value for now.
1586     if (ValLocs.size() != 1)
1587       return false;
1588
1589     CCValAssign &VA = ValLocs[0];
1590
1591     // Don't bother handling odd stuff for now.
1592     if (VA.getLocInfo() != CCValAssign::Full)
1593       return false;
1594     // Only handle register returns for now.
1595     if (!VA.isRegLoc())
1596       return false;
1597     // TODO: For now, don't try to handle cases where getLocInfo()
1598     // says Full but the types don't match.
1599     if (TLI.getValueType(RV->getType()) != VA.getValVT())
1600       return false;
1601
1602     // Make the copy.
1603     unsigned SrcReg = Reg + VA.getValNo();
1604     unsigned DstReg = VA.getLocReg();
1605     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1606     // Avoid a cross-class copy. This is very unlikely.
1607     if (!SrcRC->contains(DstReg))
1608       return false;
1609     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1610             DstReg).addReg(SrcReg);
1611
1612     // Mark the register as live out of the function.
1613     MRI.addLiveOut(VA.getLocReg());
1614   }
1615
1616   unsigned RetOpc = isThumb ? ARM::tBX_RET : ARM::BX_RET;
1617   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1618                           TII.get(RetOpc)));
1619   return true;
1620 }
1621
1622 // A quick function that will emit a call for a named libcall in F with the
1623 // vector of passed arguments for the Instruction in I. We can assume that we
1624 // can emit a call for any libcall we can produce. This is an abridged version
1625 // of the full call infrastructure since we won't need to worry about things
1626 // like computed function pointers or strange arguments at call sites.
1627 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1628 // with X86.
1629 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1630   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1631
1632   // Handle *simple* calls for now.
1633   const Type *RetTy = I->getType();
1634   MVT RetVT;
1635   if (RetTy->isVoidTy())
1636     RetVT = MVT::isVoid;
1637   else if (!isTypeLegal(RetTy, RetVT))
1638     return false;
1639
1640   // For now we're using BLX etc on the assumption that we have v5t ops.
1641   if (!Subtarget->hasV5TOps()) return false;
1642
1643   // Set up the argument vectors.
1644   SmallVector<Value*, 8> Args;
1645   SmallVector<unsigned, 8> ArgRegs;
1646   SmallVector<MVT, 8> ArgVTs;
1647   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1648   Args.reserve(I->getNumOperands());
1649   ArgRegs.reserve(I->getNumOperands());
1650   ArgVTs.reserve(I->getNumOperands());
1651   ArgFlags.reserve(I->getNumOperands());
1652   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1653     Value *Op = I->getOperand(i);
1654     unsigned Arg = getRegForValue(Op);
1655     if (Arg == 0) return false;
1656
1657     const Type *ArgTy = Op->getType();
1658     MVT ArgVT;
1659     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1660
1661     ISD::ArgFlagsTy Flags;
1662     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1663     Flags.setOrigAlign(OriginalAlignment);
1664
1665     Args.push_back(Op);
1666     ArgRegs.push_back(Arg);
1667     ArgVTs.push_back(ArgVT);
1668     ArgFlags.push_back(Flags);
1669   }
1670
1671   // Handle the arguments now that we've gotten them.
1672   SmallVector<unsigned, 4> RegArgs;
1673   unsigned NumBytes;
1674   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1675     return false;
1676
1677   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1678   // TODO: Turn this into the table of arm call ops.
1679   MachineInstrBuilder MIB;
1680   unsigned CallOpc;
1681   if(isThumb)
1682     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1683   else
1684     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1685   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1686         .addExternalSymbol(TLI.getLibcallName(Call));
1687
1688   // Add implicit physical register uses to the call.
1689   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1690     MIB.addReg(RegArgs[i]);
1691
1692   // Finish off the call including any return values.
1693   SmallVector<unsigned, 4> UsedRegs;
1694   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1695
1696   // Set all unused physreg defs as dead.
1697   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1698
1699   return true;
1700 }
1701
1702 bool ARMFastISel::SelectCall(const Instruction *I) {
1703   const CallInst *CI = cast<CallInst>(I);
1704   const Value *Callee = CI->getCalledValue();
1705
1706   // Can't handle inline asm or worry about intrinsics yet.
1707   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1708
1709   // Only handle global variable Callees that are direct calls.
1710   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1711   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1712     return false;
1713
1714   // Check the calling convention.
1715   ImmutableCallSite CS(CI);
1716   CallingConv::ID CC = CS.getCallingConv();
1717
1718   // TODO: Avoid some calling conventions?
1719
1720   // Let SDISel handle vararg functions.
1721   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1722   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1723   if (FTy->isVarArg())
1724     return false;
1725
1726   // Handle *simple* calls for now.
1727   const Type *RetTy = I->getType();
1728   MVT RetVT;
1729   if (RetTy->isVoidTy())
1730     RetVT = MVT::isVoid;
1731   else if (!isTypeLegal(RetTy, RetVT))
1732     return false;
1733
1734   // For now we're using BLX etc on the assumption that we have v5t ops.
1735   // TODO: Maybe?
1736   if (!Subtarget->hasV5TOps()) return false;
1737
1738   // Set up the argument vectors.
1739   SmallVector<Value*, 8> Args;
1740   SmallVector<unsigned, 8> ArgRegs;
1741   SmallVector<MVT, 8> ArgVTs;
1742   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1743   Args.reserve(CS.arg_size());
1744   ArgRegs.reserve(CS.arg_size());
1745   ArgVTs.reserve(CS.arg_size());
1746   ArgFlags.reserve(CS.arg_size());
1747   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1748        i != e; ++i) {
1749     unsigned Arg = getRegForValue(*i);
1750
1751     if (Arg == 0)
1752       return false;
1753     ISD::ArgFlagsTy Flags;
1754     unsigned AttrInd = i - CS.arg_begin() + 1;
1755     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1756       Flags.setSExt();
1757     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1758       Flags.setZExt();
1759
1760          // FIXME: Only handle *easy* calls for now.
1761     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1762         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1763         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1764         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1765       return false;
1766
1767     const Type *ArgTy = (*i)->getType();
1768     MVT ArgVT;
1769     if (!isTypeLegal(ArgTy, ArgVT))
1770       return false;
1771     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1772     Flags.setOrigAlign(OriginalAlignment);
1773
1774     Args.push_back(*i);
1775     ArgRegs.push_back(Arg);
1776     ArgVTs.push_back(ArgVT);
1777     ArgFlags.push_back(Flags);
1778   }
1779
1780   // Handle the arguments now that we've gotten them.
1781   SmallVector<unsigned, 4> RegArgs;
1782   unsigned NumBytes;
1783   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1784     return false;
1785
1786   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1787   // TODO: Turn this into the table of arm call ops.
1788   MachineInstrBuilder MIB;
1789   unsigned CallOpc;
1790   if(isThumb)
1791     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1792   else
1793     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1794   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1795               .addGlobalAddress(GV, 0, 0);
1796
1797   // Add implicit physical register uses to the call.
1798   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1799     MIB.addReg(RegArgs[i]);
1800
1801   // Finish off the call including any return values.
1802   SmallVector<unsigned, 4> UsedRegs;
1803   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1804
1805   // Set all unused physreg defs as dead.
1806   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1807
1808   return true;
1809
1810 }
1811
1812 // TODO: SoftFP support.
1813 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1814
1815   switch (I->getOpcode()) {
1816     case Instruction::Load:
1817       return SelectLoad(I);
1818     case Instruction::Store:
1819       return SelectStore(I);
1820     case Instruction::Br:
1821       return SelectBranch(I);
1822     case Instruction::ICmp:
1823     case Instruction::FCmp:
1824       return SelectCmp(I);
1825     case Instruction::FPExt:
1826       return SelectFPExt(I);
1827     case Instruction::FPTrunc:
1828       return SelectFPTrunc(I);
1829     case Instruction::SIToFP:
1830       return SelectSIToFP(I);
1831     case Instruction::FPToSI:
1832       return SelectFPToSI(I);
1833     case Instruction::FAdd:
1834       return SelectBinaryOp(I, ISD::FADD);
1835     case Instruction::FSub:
1836       return SelectBinaryOp(I, ISD::FSUB);
1837     case Instruction::FMul:
1838       return SelectBinaryOp(I, ISD::FMUL);
1839     case Instruction::SDiv:
1840       return SelectSDiv(I);
1841     case Instruction::SRem:
1842       return SelectSRem(I);
1843     case Instruction::Call:
1844       return SelectCall(I);
1845     case Instruction::Select:
1846       return SelectSelect(I);
1847     case Instruction::Ret:
1848       return SelectRet(I);
1849     default: break;
1850   }
1851   return false;
1852 }
1853
1854 namespace llvm {
1855   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1856     // Completely untested on non-darwin.
1857     const TargetMachine &TM = funcInfo.MF->getTarget();
1858
1859     // Darwin and thumb1 only for now.
1860     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
1861     if (Subtarget->isTargetDarwin() && !Subtarget->isThumb1Only() &&
1862         !DisableARMFastISel)
1863       return new ARMFastISel(funcInfo);
1864     return 0;
1865   }
1866 }